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 "clientmap.h"
29 #include "content_cao.h"
30 #include "drawscene.h"
31 #include "event_manager.h"
32 #include "fontengine.h"
37 #include "guiChatConsole.h"
38 #include "guiFormSpecMenu.h"
39 #include "guiKeyChangeMenu.h"
40 #include "guiPasswordChange.h"
41 #include "guiVolumeChange.h"
43 #include "mainmenumanager.h"
45 #include "nodedef.h" // Needed for determining pointing to nodes
46 #include "nodemetadata.h"
47 #include "particles.h"
49 #include "quicktune_shortcutter.h"
52 #include "shader.h" // For ShaderSource
56 #include "util/directiontables.h"
57 #include "util/pointedthing.h"
60 #include "mapblock_mesh.h"
65 #include "sound_openal.h"
68 #ifdef HAVE_TOUCHSCREENGUI
69 #include "touchscreengui.h"
72 extern Settings *g_settings;
73 extern Profiler *g_profiler;
79 struct TextDestNodeMetadata : public TextDest {
80 TextDestNodeMetadata(v3s16 p, Client *client)
85 // This is deprecated I guess? -celeron55
86 void gotText(std::wstring text)
88 std::string ntext = wide_to_utf8(text);
89 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
90 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
92 fields["text"] = ntext;
93 m_client->sendNodemetaFields(m_p, "", fields);
95 void gotText(const StringMap &fields)
97 m_client->sendNodemetaFields(m_p, "", fields);
104 struct TextDestPlayerInventory : public TextDest {
105 TextDestPlayerInventory(Client *client)
110 TextDestPlayerInventory(Client *client, std::string formname)
113 m_formname = formname;
115 void gotText(const StringMap &fields)
117 m_client->sendInventoryFields(m_formname, fields);
123 struct LocalFormspecHandler : public TextDest {
124 LocalFormspecHandler();
125 LocalFormspecHandler(std::string formname) :
128 m_formname = formname;
131 LocalFormspecHandler(std::string formname, Client *client) :
134 m_formname = formname;
137 void gotText(std::wstring message)
139 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
142 void gotText(const StringMap &fields)
144 if (m_formname == "MT_PAUSE_MENU") {
145 if (fields.find("btn_sound") != fields.end()) {
146 g_gamecallback->changeVolume();
150 if (fields.find("btn_key_config") != fields.end()) {
151 g_gamecallback->keyConfig();
155 if (fields.find("btn_exit_menu") != fields.end()) {
156 g_gamecallback->disconnect();
160 if (fields.find("btn_exit_os") != fields.end()) {
161 g_gamecallback->exitToOS();
165 if (fields.find("btn_change_password") != fields.end()) {
166 g_gamecallback->changePassword();
170 if (fields.find("quit") != fields.end()) {
174 if (fields.find("btn_continue") != fields.end()) {
179 if (m_formname == "MT_DEATH_SCREEN") {
180 assert(m_client != 0);
182 if ((fields.find("btn_respawn") != fields.end())) {
183 m_client->sendRespawn();
187 if (fields.find("quit") != fields.end()) {
188 m_client->sendRespawn();
193 // don't show error message for unhandled cursor keys
194 if ((fields.find("key_up") != fields.end()) ||
195 (fields.find("key_down") != fields.end()) ||
196 (fields.find("key_left") != fields.end()) ||
197 (fields.find("key_right") != fields.end())) {
201 errorstream << "LocalFormspecHandler::gotText unhandled >"
202 << m_formname << "< event" << std::endl;
205 StringMap::const_iterator it;
206 for (it = fields.begin(); it != fields.end(); ++it) {
207 errorstream << "\t" << i << ": " << it->first
208 << "=" << it->second << std::endl;
216 /* Form update callback */
218 class NodeMetadataFormSource: public IFormSource
221 NodeMetadataFormSource(ClientMap *map, v3s16 p):
226 std::string getForm()
228 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
233 return meta->getString("formspec");
235 std::string resolveText(std::string str)
237 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
242 return meta->resolveString(str);
249 class PlayerInventoryFormSource: public IFormSource
252 PlayerInventoryFormSource(Client *client):
256 std::string getForm()
258 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
259 return player->inventory_formspec;
266 Check if a node is pointable
268 inline bool isPointableNode(const MapNode &n,
269 Client *client, bool liquids_pointable)
271 const ContentFeatures &features = client->getNodeDefManager()->get(n);
272 return features.pointable ||
273 (liquids_pointable && features.isLiquid());
276 static inline void getNeighborConnectingFace(v3s16 p, INodeDefManager *nodedef,
277 ClientMap *map, MapNode n, u8 bitmask, u8 *neighbors)
279 MapNode n2 = map->getNodeNoEx(p);
280 if (nodedef->nodeboxConnects(n, n2, bitmask))
281 *neighbors |= bitmask;
284 static inline u8 getNeighbors(v3s16 p, INodeDefManager *nodedef, ClientMap *map, MapNode n)
287 const ContentFeatures &f = nodedef->get(n);
288 // locate possible neighboring nodes to connect to
289 if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) {
293 getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors);
297 getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors);
301 getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors);
305 getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors);
309 getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors);
313 getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors);
320 Find what the player is pointing at
322 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
323 const v3f &camera_direction, const v3f &camera_position,
324 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
325 bool look_for_object, const v3s16 &camera_offset,
326 ClientActiveObject *&selected_object)
330 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
331 selectionboxes->clear();
332 selected_object = NULL;
334 INodeDefManager *nodedef = client->getNodeDefManager();
335 ClientMap &map = client->getEnv().getClientMap();
337 f32 min_distance = BS * 1001;
339 // First try to find a pointed at active object
340 if (look_for_object) {
341 selected_object = client->getSelectedActiveObject(d * BS,
342 camera_position, shootline);
344 if (selected_object != NULL) {
345 if (selected_object->doShowSelectionBox()) {
346 aabb3f *selection_box = selected_object->getSelectionBox();
347 // Box should exist because object was
348 // returned in the first place
349 assert(selection_box);
351 v3f pos = selected_object->getPosition();
352 selectionboxes->push_back(aabb3f(
353 selection_box->MinEdge, selection_box->MaxEdge));
354 hud->setSelectionPos(pos, camera_offset);
357 min_distance = (selected_object->getPosition() - camera_position).getLength();
359 result.type = POINTEDTHING_OBJECT;
360 result.object_id = selected_object->getId();
364 // That didn't work, try to find a pointed at node
366 v3s16 pos_i = floatToInt(player_position, BS);
368 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
372 s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
373 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
374 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
375 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
376 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
377 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
379 // Prevent signed number overflow
389 v3s16 pointed_pos(0, 0, 0);
391 for (s16 y = ystart; y <= yend; y++) {
392 for (s16 z = zstart; z <= zend; z++) {
393 for (s16 x = xstart; x <= xend; x++) {
395 bool is_valid_position;
398 n = map.getNodeNoEx(p, &is_valid_position);
399 if (!is_valid_position) {
402 if (!isPointableNode(n, client, liquids_pointable)) {
406 std::vector<aabb3f> boxes;
407 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(p, nodedef, &map, n));
410 v3f npf = intToFloat(np, BS);
411 for (std::vector<aabb3f>::const_iterator
413 i != boxes.end(); ++i) {
418 v3f centerpoint = box.getCenter();
419 f32 distance = (centerpoint - camera_position).getLength();
420 if (distance >= min_distance) {
423 if (!box.intersectsWithLine(shootline)) {
426 result.type = POINTEDTHING_NODE;
427 min_distance = distance;
434 if (result.type == POINTEDTHING_NODE) {
436 MapNode n = map.getNodeNoEx(pointed_pos);
437 v3f npf = intToFloat(pointed_pos, BS);
438 std::vector<aabb3f> boxes;
439 n.getSelectionBoxes(nodedef, &boxes, getNeighbors(pointed_pos, nodedef, &map, n));
440 f32 face_min_distance = 1000 * BS;
441 for (std::vector<aabb3f>::const_iterator
443 i != boxes.end(); ++i) {
447 for (u16 j = 0; j < 6; j++) {
448 v3s16 facedir = g_6dirs[j];
449 aabb3f facebox = box;
451 facebox.MinEdge.X = facebox.MaxEdge.X - d;
452 } else if (facedir.X < 0) {
453 facebox.MaxEdge.X = facebox.MinEdge.X + d;
454 } else if (facedir.Y > 0) {
455 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
456 } else if (facedir.Y < 0) {
457 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
458 } else if (facedir.Z > 0) {
459 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
460 } else if (facedir.Z < 0) {
461 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
463 v3f centerpoint = facebox.getCenter();
464 f32 distance = (centerpoint - camera_position).getLength();
465 if (distance >= face_min_distance)
467 if (!facebox.intersectsWithLine(shootline))
469 result.node_abovesurface = pointed_pos + facedir;
470 face_min_distance = distance;
473 selectionboxes->clear();
474 for (std::vector<aabb3f>::const_iterator
476 i != boxes.end(); ++i) {
478 box.MinEdge += v3f(-d, -d, -d);
479 box.MaxEdge += v3f(d, d, d);
480 selectionboxes->push_back(box);
482 hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
483 result.node_undersurface = pointed_pos;
486 // Update selection mesh light level and vertex colors
487 if (selectionboxes->size() > 0) {
488 v3f pf = hud->getSelectionPos();
489 v3s16 p = floatToInt(pf, BS);
491 // Get selection mesh light level
492 MapNode n = map.getNodeNoEx(p);
493 u16 node_light = getInteriorLight(n, -1, nodedef);
494 u16 light_level = node_light;
496 for (u8 i = 0; i < 6; i++) {
497 n = map.getNodeNoEx(p + g_6dirs[i]);
498 node_light = getInteriorLight(n, -1, nodedef);
499 if (node_light > light_level)
500 light_level = node_light;
503 video::SColor c = MapBlock_LightColor(255, light_level, 0);
505 u8 night = c.getGreen();
506 u32 daynight_ratio = client->getEnv().getDayNightRatio();
507 finalColorBlend(c, day, night, daynight_ratio);
509 // Modify final color a bit with time
510 u32 timer = porting::getTimeMs() % 5000;
511 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
512 float sin_r = 0.08 * sin(timerf);
513 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
514 float sin_b = 0.08 * sin(timerf + irr::core::PI);
515 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
516 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
517 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
519 // Set mesh final color
520 hud->setSelectionMeshColor(c);
525 /* Profiler display */
527 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
528 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
530 if (show_profiler == 0) {
531 guitext_profiler->setVisible(false);
534 std::ostringstream os(std::ios_base::binary);
535 g_profiler->printPage(os, show_profiler, show_profiler_max);
536 std::wstring text = utf8_to_wide(os.str());
537 guitext_profiler->setText(text.c_str());
538 guitext_profiler->setVisible(true);
540 s32 w = fe->getTextWidth(text.c_str());
545 unsigned text_height = fe->getTextHeight();
547 core::position2di upper_left, lower_right;
550 upper_left.Y = (text_height + 5) * 2;
551 lower_right.X = 12 + w;
552 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
554 if (lower_right.Y > screen_height * 2 / 3)
555 lower_right.Y = screen_height * 2 / 3;
557 core::rect<s32> rect(upper_left, lower_right);
559 guitext_profiler->setRelativePosition(rect);
560 guitext_profiler->setVisible(true);
568 Profiler::GraphValues values;
574 Meta(float initial = 0,
575 video::SColor color = video::SColor(255, 255, 255, 255)):
581 std::deque<Piece> m_log;
589 void put(const Profiler::GraphValues &values)
592 piece.values = values;
593 m_log.push_back(piece);
595 while (m_log.size() > m_log_max_size)
596 m_log.erase(m_log.begin());
599 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
600 gui::IGUIFont *font) const
602 std::map<std::string, Meta> m_meta;
604 for (std::deque<Piece>::const_iterator k = m_log.begin();
605 k != m_log.end(); ++k) {
606 const Piece &piece = *k;
608 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
609 i != piece.values.end(); ++i) {
610 const std::string &id = i->first;
611 const float &value = i->second;
612 std::map<std::string, Meta>::iterator j =
615 if (j == m_meta.end()) {
616 m_meta[id] = Meta(value);
620 if (value < j->second.min)
621 j->second.min = value;
623 if (value > j->second.max)
624 j->second.max = value;
629 static const video::SColor usable_colors[] = {
630 video::SColor(255, 255, 100, 100),
631 video::SColor(255, 90, 225, 90),
632 video::SColor(255, 100, 100, 255),
633 video::SColor(255, 255, 150, 50),
634 video::SColor(255, 220, 220, 100)
636 static const u32 usable_colors_count =
637 sizeof(usable_colors) / sizeof(*usable_colors);
638 u32 next_color_i = 0;
640 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
641 i != m_meta.end(); ++i) {
642 Meta &meta = i->second;
643 video::SColor color(255, 200, 200, 200);
645 if (next_color_i < usable_colors_count)
646 color = usable_colors[next_color_i++];
652 s32 textx = x_left + m_log_max_size + 15;
653 s32 textx2 = textx + 200 - 15;
656 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
657 i != m_meta.end(); ++i) {
658 const std::string &id = i->first;
659 const Meta &meta = i->second;
661 s32 y = y_bottom - meta_i * 50;
662 float show_min = meta.min;
663 float show_max = meta.max;
665 if (show_min >= -0.0001 && show_max >= -0.0001) {
666 if (show_min <= show_max * 0.5)
672 snprintf(buf, 10, "%.3g", show_max);
673 font->draw(utf8_to_wide(buf).c_str(),
674 core::rect<s32>(textx, y - graphh,
675 textx2, y - graphh + texth),
677 snprintf(buf, 10, "%.3g", show_min);
678 font->draw(utf8_to_wide(buf).c_str(),
679 core::rect<s32>(textx, y - texth,
682 font->draw(utf8_to_wide(id).c_str(),
683 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
684 textx2, y - graphh / 2 + texth / 2),
687 s32 graph1h = graphh;
688 bool relativegraph = (show_min != 0 && show_min != show_max);
689 float lastscaledvalue = 0.0;
690 bool lastscaledvalue_exists = false;
692 for (std::deque<Piece>::const_iterator j = m_log.begin();
693 j != m_log.end(); ++j) {
694 const Piece &piece = *j;
696 bool value_exists = false;
697 Profiler::GraphValues::const_iterator k =
698 piece.values.find(id);
700 if (k != piece.values.end()) {
707 lastscaledvalue_exists = false;
711 float scaledvalue = 1.0;
713 if (show_max != show_min)
714 scaledvalue = (value - show_min) / (show_max - show_min);
716 if (scaledvalue == 1.0 && value == 0) {
718 lastscaledvalue_exists = false;
723 if (lastscaledvalue_exists) {
724 s32 ivalue1 = lastscaledvalue * graph1h;
725 s32 ivalue2 = scaledvalue * graph1h;
726 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
727 v2s32(x, graph1y - ivalue2), meta.color);
730 lastscaledvalue = scaledvalue;
731 lastscaledvalue_exists = true;
733 s32 ivalue = scaledvalue * graph1h;
734 driver->draw2DLine(v2s32(x, graph1y),
735 v2s32(x, graph1y - ivalue), meta.color);
746 class NodeDugEvent: public MtEvent
752 NodeDugEvent(v3s16 p, MapNode n):
756 const char *getType() const
764 ISoundManager *m_sound;
765 INodeDefManager *m_ndef;
767 float m_player_step_timer;
769 SimpleSoundSpec m_player_step_sound;
770 SimpleSoundSpec m_player_leftpunch_sound;
771 SimpleSoundSpec m_player_rightpunch_sound;
773 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
776 m_player_step_timer(0)
780 void playPlayerStep()
782 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
783 m_player_step_timer = 0.03;
784 m_sound->playSound(m_player_step_sound, false);
788 static void viewBobbingStep(MtEvent *e, void *data)
790 SoundMaker *sm = (SoundMaker *)data;
791 sm->playPlayerStep();
794 static void playerRegainGround(MtEvent *e, void *data)
796 SoundMaker *sm = (SoundMaker *)data;
797 sm->playPlayerStep();
800 static void playerJump(MtEvent *e, void *data)
802 //SoundMaker *sm = (SoundMaker*)data;
805 static void cameraPunchLeft(MtEvent *e, void *data)
807 SoundMaker *sm = (SoundMaker *)data;
808 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
811 static void cameraPunchRight(MtEvent *e, void *data)
813 SoundMaker *sm = (SoundMaker *)data;
814 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
817 static void nodeDug(MtEvent *e, void *data)
819 SoundMaker *sm = (SoundMaker *)data;
820 NodeDugEvent *nde = (NodeDugEvent *)e;
821 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
824 static void playerDamage(MtEvent *e, void *data)
826 SoundMaker *sm = (SoundMaker *)data;
827 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
830 static void playerFallingDamage(MtEvent *e, void *data)
832 SoundMaker *sm = (SoundMaker *)data;
833 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
836 void registerReceiver(MtEventManager *mgr)
838 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
839 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
840 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
841 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
842 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
843 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
844 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
845 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
848 void step(float dtime)
850 m_player_step_timer -= dtime;
854 // Locally stored sounds don't need to be preloaded because of this
855 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
857 std::set<std::string> m_fetched;
859 void fetchSounds(const std::string &name,
860 std::set<std::string> &dst_paths,
861 std::set<std::string> &dst_datas)
863 if (m_fetched.count(name))
866 m_fetched.insert(name);
867 std::string base = porting::path_share + DIR_DELIM + "testsounds";
868 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
869 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
870 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
871 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
872 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
873 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
874 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
875 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
876 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
877 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
878 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
882 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
885 bool *m_force_fog_off;
891 void onSettingsChange(const std::string &name)
893 if (name == "enable_fog")
894 m_fogEnabled = g_settings->getBool("enable_fog");
897 static void SettingsCallback(const std::string &name, void *userdata)
899 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
902 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
903 f32 *fog_range, Client *client) :
905 m_force_fog_off(force_fog_off),
906 m_fog_range(fog_range),
909 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
910 m_fogEnabled = g_settings->getBool("enable_fog");
913 ~GameGlobalShaderConstantSetter()
915 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
918 virtual void onSetConstants(video::IMaterialRendererServices *services,
925 video::SColor bgcolor = m_sky->getBgColor();
926 video::SColorf bgcolorf(bgcolor);
927 float bgcolorfa[4] = {
933 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
936 float fog_distance = 10000 * BS;
938 if (m_fogEnabled && !*m_force_fog_off)
939 fog_distance = *m_fog_range;
941 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
944 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
945 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
946 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
948 u32 animation_timer = porting::getTimeMs() % 100000;
949 float animation_timer_f = (float)animation_timer / 100000.0;
950 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
951 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
953 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
954 v3f eye_position = player->getEyePosition();
955 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
956 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
958 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
959 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
961 // Uniform sampler layers
962 // before 1.8 there isn't a "integer interface", only float
963 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
967 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
968 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
969 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
974 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
975 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
976 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
981 bool nodePlacementPrediction(Client &client,
982 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
984 std::string prediction = playeritem_def.node_placement_prediction;
985 INodeDefManager *nodedef = client.ndef();
986 ClientMap &map = client.getEnv().getClientMap();
988 bool is_valid_position;
990 node = map.getNodeNoEx(nodepos, &is_valid_position);
991 if (!is_valid_position)
994 if (prediction != "" && !nodedef->get(node).rightclickable) {
995 verbosestream << "Node placement prediction for "
996 << playeritem_def.name << " is "
997 << prediction << std::endl;
998 v3s16 p = neighbourpos;
1000 // Place inside node itself if buildable_to
1001 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
1002 if (is_valid_position)
1004 if (nodedef->get(n_under).buildable_to)
1007 node = map.getNodeNoEx(p, &is_valid_position);
1008 if (is_valid_position &&!nodedef->get(node).buildable_to)
1013 // Find id of predicted node
1015 bool found = nodedef->getId(prediction, id);
1018 errorstream << "Node placement prediction failed for "
1019 << playeritem_def.name << " (places "
1021 << ") - Name not known" << std::endl;
1025 // Predict param2 for facedir and wallmounted nodes
1028 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
1029 v3s16 dir = nodepos - neighbourpos;
1031 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
1032 param2 = dir.Y < 0 ? 1 : 0;
1033 } else if (abs(dir.X) > abs(dir.Z)) {
1034 param2 = dir.X < 0 ? 3 : 2;
1036 param2 = dir.Z < 0 ? 5 : 4;
1040 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
1041 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
1043 if (abs(dir.X) > abs(dir.Z)) {
1044 param2 = dir.X < 0 ? 3 : 1;
1046 param2 = dir.Z < 0 ? 2 : 0;
1050 assert(param2 <= 5);
1052 //Check attachment if node is in group attached_node
1053 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1054 static v3s16 wallmounted_dirs[8] = {
1064 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1065 pp = p + wallmounted_dirs[param2];
1067 pp = p + v3s16(0, -1, 0);
1069 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1073 // Add node to client map
1074 MapNode n(id, 0, param2);
1077 LocalPlayer *player = client.getEnv().getLocalPlayer();
1079 // Dont place node when player would be inside new node
1080 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1081 if (!nodedef->get(n).walkable ||
1082 g_settings->getBool("enable_build_where_you_stand") ||
1083 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1084 (nodedef->get(n).walkable &&
1085 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1086 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1088 // This triggers the required mesh update too
1089 client.addNode(p, n);
1092 } catch (InvalidPositionException &e) {
1093 errorstream << "Node placement prediction failed for "
1094 << playeritem_def.name << " (places "
1096 << ") - Position not loaded" << std::endl;
1103 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1104 InventoryManager *invmgr, IGameDef *gamedef,
1105 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1106 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1109 if (*cur_formspec == 0) {
1110 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1111 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1112 (*cur_formspec)->doPause = false;
1115 Caution: do not call (*cur_formspec)->drop() here --
1116 the reference might outlive the menu, so we will
1117 periodically check if *cur_formspec is the only
1118 remaining reference (i.e. the menu was removed)
1119 and delete it in that case.
1123 (*cur_formspec)->setFormSource(fs_src);
1124 (*cur_formspec)->setTextDest(txt_dest);
1129 #define SIZE_TAG "size[11,5.5]"
1131 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1134 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1135 InventoryManager *invmgr, IGameDef *gamedef,
1136 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1138 std::string formspec =
1139 std::string(FORMSPEC_VERSION_STRING) +
1141 "bgcolor[#320000b4;true]"
1142 "label[4.85,1.35;" + gettext("You died.") + "]"
1143 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1147 /* Note: FormspecFormSource and LocalFormspecHandler
1148 * are deleted by guiFormSpecMenu */
1149 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1150 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1152 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1155 /******************************************************************************/
1156 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1157 InventoryManager *invmgr, IGameDef *gamedef,
1158 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1159 bool singleplayermode)
1162 std::string control_text = strgettext("Default Controls:\n"
1163 "No menu visible:\n"
1164 "- single tap: button activate\n"
1165 "- double tap: place/use\n"
1166 "- slide finger: look around\n"
1167 "Menu/Inventory visible:\n"
1168 "- double tap (outside):\n"
1170 "- touch stack, touch slot:\n"
1172 "- touch&drag, tap 2nd finger\n"
1173 " --> place single item to slot\n"
1176 std::string control_text = strgettext("Default Controls:\n"
1178 "- Space: jump/climb\n"
1179 "- Shift: sneak/go down\n"
1182 "- Mouse: turn/look\n"
1183 "- Mouse left: dig/punch\n"
1184 "- Mouse right: place/use\n"
1185 "- Mouse wheel: select item\n"
1190 float ypos = singleplayermode ? 0.5 : 0.1;
1191 std::ostringstream os;
1193 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1194 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1195 << strgettext("Continue") << "]";
1197 if (!singleplayermode) {
1198 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1199 << strgettext("Change Password") << "]";
1203 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1204 << strgettext("Sound Volume") << "]";
1205 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1206 << strgettext("Change Keys") << "]";
1208 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1209 << strgettext("Exit to Menu") << "]";
1210 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1211 << strgettext("Exit to OS") << "]"
1212 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1213 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1214 << g_build_info << "\n"
1215 << "path_user = " << wrap_rows(porting::path_user, 20)
1219 /* Note: FormspecFormSource and LocalFormspecHandler *
1220 * are deleted by guiFormSpecMenu */
1221 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1222 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1224 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1225 std::string con("btn_continue");
1226 (*cur_formspec)->setFocus(con);
1227 (*cur_formspec)->doPause = true;
1230 /******************************************************************************/
1231 static void updateChat(Client &client, f32 dtime, bool show_debug,
1232 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1233 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1235 // Add chat log output for errors to be shown in chat
1236 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1238 // Get new messages from error log buffer
1239 while (!chat_log_error_buf.empty()) {
1240 chat_backend.addMessage(L"", utf8_to_wide(chat_log_error_buf.get()));
1243 // Get new messages from client
1244 std::wstring message;
1246 while (client.getChatMessage(message)) {
1247 chat_backend.addUnparsedMessage(message);
1250 // Remove old messages
1251 chat_backend.step(dtime);
1253 // Display all messages in a static text element
1254 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1255 std::wstring recent_chat = chat_backend.getRecentChat();
1256 unsigned int line_height = g_fontengine->getLineHeight();
1258 guitext_chat->setText(recent_chat.c_str());
1260 // Update gui element size and position
1261 s32 chat_y = 5 + line_height;
1264 chat_y += line_height;
1266 // first pass to calculate height of text to be set
1267 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1268 porting::getWindowSize().X - 20);
1269 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1270 guitext_chat->setRelativePosition(rect);
1272 //now use real height of text and adjust rect according to this size
1273 rect = core::rect<s32>(10, chat_y, width,
1274 chat_y + guitext_chat->getTextHeight());
1277 guitext_chat->setRelativePosition(rect);
1278 // Don't show chat if disabled or empty or profiler is enabled
1279 guitext_chat->setVisible(
1280 show_chat && recent_chat_count != 0 && !show_profiler);
1284 /****************************************************************************
1285 Fast key cache for main game loop
1286 ****************************************************************************/
1288 /* This is faster than using getKeySetting with the tradeoff that functions
1289 * using it must make sure that it's initialised before using it and there is
1290 * no error handling (for example bounds checking). This is really intended for
1291 * use only in the main running loop of the client (the_game()) where the faster
1292 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1293 * (e.g. formspecs) should continue using getKeySetting().
1297 KeyCache() { populate(); }
1312 KEYMAP_ID_INVENTORY,
1320 KEYMAP_ID_CINEMATIC,
1321 KEYMAP_ID_SCREENSHOT,
1322 KEYMAP_ID_TOGGLE_HUD,
1323 KEYMAP_ID_TOGGLE_CHAT,
1324 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1325 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1326 KEYMAP_ID_TOGGLE_DEBUG,
1327 KEYMAP_ID_TOGGLE_PROFILER,
1328 KEYMAP_ID_CAMERA_MODE,
1329 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1330 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1331 KEYMAP_ID_RANGESELECT,
1333 KEYMAP_ID_QUICKTUNE_NEXT,
1334 KEYMAP_ID_QUICKTUNE_PREV,
1335 KEYMAP_ID_QUICKTUNE_INC,
1336 KEYMAP_ID_QUICKTUNE_DEC,
1338 KEYMAP_ID_DEBUG_STACKS,
1340 // Fake keycode for array size and internal checks
1341 KEYMAP_INTERNAL_ENUM_COUNT
1348 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1351 void KeyCache::populate()
1353 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1354 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1355 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1356 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1357 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1358 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1359 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1361 key[KEYMAP_ID_AUTORUN] = getKeySetting("keymap_autorun");
1363 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1364 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1365 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1366 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1367 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1368 key[KEYMAP_ID_MINIMAP] = getKeySetting("keymap_minimap");
1369 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1370 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1371 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1372 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1373 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1374 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1375 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1376 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1377 = getKeySetting("keymap_toggle_force_fog_off");
1378 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1379 = getKeySetting("keymap_toggle_update_camera");
1380 key[KEYMAP_ID_TOGGLE_DEBUG]
1381 = getKeySetting("keymap_toggle_debug");
1382 key[KEYMAP_ID_TOGGLE_PROFILER]
1383 = getKeySetting("keymap_toggle_profiler");
1384 key[KEYMAP_ID_CAMERA_MODE]
1385 = getKeySetting("keymap_camera_mode");
1386 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1387 = getKeySetting("keymap_increase_viewing_range_min");
1388 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1389 = getKeySetting("keymap_decrease_viewing_range_min");
1390 key[KEYMAP_ID_RANGESELECT]
1391 = getKeySetting("keymap_rangeselect");
1393 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1394 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1395 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1396 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1398 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1402 /****************************************************************************
1404 ****************************************************************************/
1406 const float object_hit_delay = 0.2;
1409 u32 last_time, busy_time, sleep_time;
1413 /* The reason the following structs are not anonymous structs within the
1414 * class is that they are not used by the majority of member functions and
1415 * many functions that do require objects of thse types do not modify them
1416 * (so they can be passed as a const qualified parameter)
1418 struct CameraOrientation {
1419 f32 camera_yaw; // "right/left"
1420 f32 camera_pitch; // "up/down"
1423 struct GameRunData {
1426 PointedThing pointed_old;
1430 bool update_wielded_item_trigger;
1431 bool reset_jump_timer;
1432 float nodig_delay_timer;
1434 float dig_time_complete;
1435 float repeat_rightclick_timer;
1436 float object_hit_delay_timer;
1437 float time_from_last_punch;
1438 ClientActiveObject *selected_object;
1442 float update_draw_list_timer;
1443 float statustext_time;
1447 v3f update_draw_list_last_cam_dir;
1449 u32 profiler_current_page;
1450 u32 profiler_max_page; // Number of pages
1453 float time_of_day_smooth;
1457 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1465 Jitter dtime_jitter, busy_time_jitter;
1468 /* Flags that can, or may, change during main game loop
1470 struct VolatileRunFlags {
1477 bool show_profiler_graph;
1478 bool disable_camera_update;
1479 bool first_loop_after_window_activation;
1480 bool camera_offset_changed;
1484 /****************************************************************************
1486 ****************************************************************************/
1488 /* This is not intended to be a public class. If a public class becomes
1489 * desirable then it may be better to create another 'wrapper' class that
1490 * hides most of the stuff in this class (nothing in this class is required
1491 * by any other file) but exposes the public methods/data only.
1498 bool startup(bool *kill,
1500 InputHandler *input,
1501 IrrlichtDevice *device,
1502 const std::string &map_dir,
1503 const std::string &playername,
1504 const std::string &password,
1505 // If address is "", local server is used and address is updated
1506 std::string *address,
1508 std::string &error_message,
1510 ChatBackend *chat_backend,
1511 const SubgameSpec &gamespec, // Used for local game
1512 bool simple_singleplayer_mode);
1519 void extendedResourceCleanup();
1521 // Basic initialisation
1522 bool init(const std::string &map_dir, std::string *address,
1524 const SubgameSpec &gamespec);
1526 bool createSingleplayerServer(const std::string map_dir,
1527 const SubgameSpec &gamespec, u16 port, std::string *address);
1530 bool createClient(const std::string &playername,
1531 const std::string &password, std::string *address, u16 port);
1534 // Client connection
1535 bool connectToServer(const std::string &playername,
1536 const std::string &password, std::string *address, u16 port,
1537 bool *connect_ok, bool *aborted);
1538 bool getServerContent(bool *aborted);
1542 void updateInteractTimers(GameRunData *runData, f32 dtime);
1543 bool checkConnection();
1544 bool handleCallbacks();
1545 void processQueues();
1546 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1547 const FpsControl &draw_times, f32 dtime);
1548 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1550 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1552 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1554 void processKeyboardInput(VolatileRunFlags *flags,
1555 float *statustext_time,
1557 bool *reset_jump_timer,
1558 u32 *profiler_current_page,
1559 u32 profiler_max_page);
1560 void processItemSelection(u16 *new_playeritem);
1562 void dropSelectedItem();
1563 void openInventory();
1564 void openConsole(float height, const wchar_t *line=NULL);
1565 void toggleFreeMove(float *statustext_time);
1566 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1567 void toggleFast(float *statustext_time);
1568 void toggleNoClip(float *statustext_time);
1569 void toggleCinematic(float *statustext_time);
1570 void toggleAutorun(float *statustext_time);
1572 void toggleChat(float *statustext_time, bool *flag);
1573 void toggleHud(float *statustext_time, bool *flag);
1574 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1575 bool shift_pressed);
1576 void toggleFog(float *statustext_time, bool *flag);
1577 void toggleDebug(float *statustext_time, bool *show_debug,
1578 bool *show_profiler_graph);
1579 void toggleUpdateCamera(float *statustext_time, bool *flag);
1580 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1581 u32 profiler_max_page);
1583 void increaseViewRange(float *statustext_time);
1584 void decreaseViewRange(float *statustext_time);
1585 void toggleFullViewRange(float *statustext_time);
1587 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1588 void updateCameraOrientation(CameraOrientation *cam,
1589 const VolatileRunFlags &flags);
1590 void updatePlayerControl(const CameraOrientation &cam);
1591 void step(f32 *dtime);
1592 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1593 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1594 float time_from_last_punch);
1595 void updateSound(f32 dtime);
1596 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1598 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1599 void handlePointingAtNode(GameRunData *runData,
1600 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1601 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1602 void handlePointingAtObject(GameRunData *runData,
1603 const PointedThing &pointed, const ItemStack &playeritem,
1604 const v3f &player_position, bool show_debug);
1605 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1606 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1608 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1609 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1610 void updateGui(float *statustext_time, const RunStats &stats,
1611 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1612 const CameraOrientation &cam);
1613 void updateProfilerGraphs(ProfilerGraph *graph);
1616 void limitFps(FpsControl *fps_timings, f32 *dtime);
1618 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1619 bool draw_clouds = true);
1621 static void settingChangedCallback(const std::string &setting_name, void *data);
1622 void readSettings();
1625 void handleAndroidChatInput();
1629 InputHandler *input;
1634 IWritableTextureSource *texture_src;
1635 IWritableShaderSource *shader_src;
1637 // When created, these will be filled with data received from the server
1638 IWritableItemDefManager *itemdef_manager;
1639 IWritableNodeDefManager *nodedef_manager;
1641 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1642 ISoundManager *sound;
1643 bool sound_is_dummy;
1644 SoundMaker *soundmaker;
1646 ChatBackend *chat_backend;
1648 GUIFormSpecMenu *current_formspec;
1650 EventManager *eventmgr;
1651 QuicktuneShortcutter *quicktune;
1653 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1654 MapDrawControl *draw_control;
1656 Clouds *clouds; // Free using ->Drop()
1657 Sky *sky; // Free using ->Drop()
1658 Inventory *local_inventory;
1663 This class does take ownership/responsibily for cleaning up etc of any of
1664 these items (e.g. device)
1666 IrrlichtDevice *device;
1667 video::IVideoDriver *driver;
1668 scene::ISceneManager *smgr;
1670 std::string *error_message;
1671 bool *reconnect_requested;
1672 IGameDef *gamedef; // Convenience (same as *client)
1673 scene::ISceneNode *skybox;
1676 bool simple_singleplayer_mode;
1679 /* Pre-calculated values
1681 int crack_animation_length;
1685 gui::IGUIStaticText *guitext; // First line of debug text
1686 gui::IGUIStaticText *guitext2; // Second line of debug text
1687 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1688 gui::IGUIStaticText *guitext_status;
1689 gui::IGUIStaticText *guitext_chat; // Chat text
1690 gui::IGUIStaticText *guitext_profiler; // Profiler text
1692 std::wstring infotext;
1693 std::wstring statustext;
1697 IntervalLimiter profiler_interval;
1700 * TODO: Local caching of settings is not optimal and should at some stage
1701 * be updated to use a global settings object for getting thse values
1702 * (as opposed to the this local caching). This can be addressed in
1705 bool m_cache_doubletap_jump;
1706 bool m_cache_enable_clouds;
1707 bool m_cache_enable_particles;
1708 bool m_cache_enable_fog;
1709 f32 m_cache_mouse_sensitivity;
1710 f32 m_repeat_right_click_time;
1713 bool m_cache_hold_aux1;
1714 bool m_android_chat_open;
1723 itemdef_manager(NULL),
1724 nodedef_manager(NULL),
1726 sound_is_dummy(false),
1729 current_formspec(NULL),
1732 gui_chat_console(NULL),
1737 local_inventory(NULL),
1741 g_settings->registerChangedCallback("doubletap_jump",
1742 &settingChangedCallback, this);
1743 g_settings->registerChangedCallback("enable_clouds",
1744 &settingChangedCallback, this);
1745 g_settings->registerChangedCallback("enable_particles",
1746 &settingChangedCallback, this);
1747 g_settings->registerChangedCallback("enable_fog",
1748 &settingChangedCallback, this);
1749 g_settings->registerChangedCallback("mouse_sensitivity",
1750 &settingChangedCallback, this);
1751 g_settings->registerChangedCallback("repeat_rightclick_time",
1752 &settingChangedCallback, this);
1757 m_cache_hold_aux1 = false; // This is initialised properly later
1764 /****************************************************************************
1766 ****************************************************************************/
1772 if (!sound_is_dummy)
1775 delete server; // deleted first to stop all server threads
1778 delete local_inventory;
1784 delete nodedef_manager;
1785 delete itemdef_manager;
1786 delete draw_control;
1788 extendedResourceCleanup();
1790 g_settings->deregisterChangedCallback("doubletap_jump",
1791 &settingChangedCallback, this);
1792 g_settings->deregisterChangedCallback("enable_clouds",
1793 &settingChangedCallback, this);
1794 g_settings->deregisterChangedCallback("enable_particles",
1795 &settingChangedCallback, this);
1796 g_settings->deregisterChangedCallback("enable_fog",
1797 &settingChangedCallback, this);
1798 g_settings->deregisterChangedCallback("mouse_sensitivity",
1799 &settingChangedCallback, this);
1800 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1801 &settingChangedCallback, this);
1804 bool Game::startup(bool *kill,
1806 InputHandler *input,
1807 IrrlichtDevice *device,
1808 const std::string &map_dir,
1809 const std::string &playername,
1810 const std::string &password,
1811 std::string *address, // can change if simple_singleplayer_mode
1813 std::string &error_message,
1815 ChatBackend *chat_backend,
1816 const SubgameSpec &gamespec,
1817 bool simple_singleplayer_mode)
1820 this->device = device;
1822 this->error_message = &error_message;
1823 this->reconnect_requested = reconnect;
1824 this->random_input = random_input;
1825 this->input = input;
1826 this->chat_backend = chat_backend;
1827 this->simple_singleplayer_mode = simple_singleplayer_mode;
1829 driver = device->getVideoDriver();
1830 smgr = device->getSceneManager();
1832 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1834 if (!init(map_dir, address, port, gamespec))
1837 if (!createClient(playername, password, address, port))
1846 ProfilerGraph graph;
1847 RunStats stats = { 0 };
1848 CameraOrientation cam_view_target = { 0 };
1849 CameraOrientation cam_view = { 0 };
1850 GameRunData runData = { 0 };
1851 FpsControl draw_times = { 0 };
1852 VolatileRunFlags flags = { 0 };
1853 f32 dtime; // in seconds
1855 runData.time_from_last_punch = 10.0;
1856 runData.profiler_max_page = 3;
1857 runData.update_wielded_item_trigger = true;
1859 flags.show_chat = true;
1860 flags.show_hud = true;
1861 flags.show_minimap = g_settings->getBool("enable_minimap");
1862 flags.show_debug = g_settings->getBool("show_debug");
1863 flags.invert_mouse = g_settings->getBool("invert_mouse");
1864 flags.first_loop_after_window_activation = true;
1866 /* Clear the profiler */
1867 Profiler::GraphValues dummyvalues;
1868 g_profiler->graphGet(dummyvalues);
1870 draw_times.last_time = device->getTimer()->getTime();
1872 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1874 &flags.force_fog_off,
1878 set_light_table(g_settings->getFloat("display_gamma"));
1881 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1882 && client->checkPrivilege("fast");
1885 while (device->run()
1886 && !(*kill || g_gamecallback->shutdown_requested
1887 || (server && server->getShutdownRequested()))) {
1889 /* Must be called immediately after a device->run() call because it
1890 * uses device->getTimer()->getTime()
1892 limitFps(&draw_times, &dtime);
1894 updateStats(&stats, draw_times, dtime);
1895 updateInteractTimers(&runData, dtime);
1897 if (!checkConnection())
1899 if (!handleCallbacks())
1905 hud->resizeHotbar();
1907 updateProfilers(runData, stats, draw_times, dtime);
1908 processUserInput(&flags, &runData, dtime);
1909 // Update camera before player movement to avoid camera lag of one frame
1910 updateCameraDirection(&cam_view_target, &flags);
1911 float cam_smoothing = 0;
1912 if (g_settings->getBool("cinematic"))
1913 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1915 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1916 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1917 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1918 cam_view.camera_yaw) * cam_smoothing;
1919 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1920 cam_view.camera_pitch) * cam_smoothing;
1921 updatePlayerControl(cam_view);
1923 processClientEvents(&cam_view_target, &runData.damage_flash);
1924 updateCamera(&flags, draw_times.busy_time, dtime,
1925 runData.time_from_last_punch);
1927 processPlayerInteraction(&runData, dtime, flags.show_hud,
1929 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1930 updateProfilerGraphs(&graph);
1932 // Update if minimap has been disabled by the server
1933 flags.show_minimap &= !client->isMinimapDisabledByServer();
1938 void Game::shutdown()
1940 if (g_settings->get("3d_mode") == "pageflip") {
1941 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1944 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1949 if (gui_chat_console)
1950 gui_chat_console->drop();
1956 while (g_menumgr.menuCount() > 0) {
1957 g_menumgr.m_stack.front()->setVisible(false);
1958 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1961 if (current_formspec) {
1962 current_formspec->drop();
1963 current_formspec = NULL;
1966 chat_backend->addMessage(L"", L"# Disconnected.");
1967 chat_backend->addMessage(L"", L"");
1971 while (!client->isShutdown()) {
1972 assert(texture_src != NULL);
1973 assert(shader_src != NULL);
1974 texture_src->processQueue();
1975 shader_src->processQueue();
1982 /****************************************************************************/
1983 /****************************************************************************
1985 ****************************************************************************/
1986 /****************************************************************************/
1989 const std::string &map_dir,
1990 std::string *address,
1992 const SubgameSpec &gamespec)
1994 showOverlayMessage(wgettext("Loading..."), 0, 0);
1996 texture_src = createTextureSource(device);
1997 shader_src = createShaderSource(device);
1999 itemdef_manager = createItemDefManager();
2000 nodedef_manager = createNodeDefManager();
2002 eventmgr = new EventManager();
2003 quicktune = new QuicktuneShortcutter();
2005 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
2006 && eventmgr && quicktune))
2012 // Create a server if not connecting to an existing one
2013 if (*address == "") {
2014 if (!createSingleplayerServer(map_dir, gamespec, port, address))
2021 bool Game::initSound()
2024 if (g_settings->getBool("enable_sound")) {
2025 infostream << "Attempting to use OpenAL audio" << std::endl;
2026 sound = createOpenALSoundManager(&soundfetcher);
2028 infostream << "Failed to initialize OpenAL audio" << std::endl;
2030 infostream << "Sound disabled." << std::endl;
2034 infostream << "Using dummy audio." << std::endl;
2035 sound = &dummySoundManager;
2036 sound_is_dummy = true;
2039 soundmaker = new SoundMaker(sound, nodedef_manager);
2043 soundmaker->registerReceiver(eventmgr);
2048 bool Game::createSingleplayerServer(const std::string map_dir,
2049 const SubgameSpec &gamespec, u16 port, std::string *address)
2051 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2053 std::string bind_str = g_settings->get("bind_address");
2054 Address bind_addr(0, 0, 0, 0, port);
2056 if (g_settings->getBool("ipv6_server")) {
2057 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2061 bind_addr.Resolve(bind_str.c_str());
2062 } catch (ResolveError &e) {
2063 infostream << "Resolving bind address \"" << bind_str
2064 << "\" failed: " << e.what()
2065 << " -- Listening on all addresses." << std::endl;
2068 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2069 *error_message = "Unable to listen on " +
2070 bind_addr.serializeString() +
2071 " because IPv6 is disabled";
2072 errorstream << *error_message << std::endl;
2076 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2077 bind_addr.isIPv6());
2079 server->start(bind_addr);
2084 bool Game::createClient(const std::string &playername,
2085 const std::string &password, std::string *address, u16 port)
2087 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2089 draw_control = new MapDrawControl;
2093 bool could_connect, connect_aborted;
2095 if (!connectToServer(playername, password, address, port,
2096 &could_connect, &connect_aborted))
2099 if (!could_connect) {
2100 if (error_message->empty() && !connect_aborted) {
2101 // Should not happen if error messages are set properly
2102 *error_message = "Connection failed for unknown reason";
2103 errorstream << *error_message << std::endl;
2108 if (!getServerContent(&connect_aborted)) {
2109 if (error_message->empty() && !connect_aborted) {
2110 // Should not happen if error messages are set properly
2111 *error_message = "Connection failed for unknown reason";
2112 errorstream << *error_message << std::endl;
2117 // Update cached textures, meshes and materials
2118 client->afterContentReceived(device);
2122 camera = new Camera(smgr, *draw_control, gamedef);
2123 if (!camera || !camera->successfullyCreated(*error_message))
2125 client->setCamera(camera);
2129 if (m_cache_enable_clouds) {
2130 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2132 *error_message = "Memory allocation error (clouds)";
2133 errorstream << *error_message << std::endl;
2140 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2141 skybox = NULL; // This is used/set later on in the main run loop
2143 local_inventory = new Inventory(itemdef_manager);
2145 if (!(sky && local_inventory)) {
2146 *error_message = "Memory allocation error (sky or local inventory)";
2147 errorstream << *error_message << std::endl;
2151 /* Pre-calculated values
2153 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2155 v2u32 size = t->getOriginalSize();
2156 crack_animation_length = size.Y / size.X;
2158 crack_animation_length = 5;
2164 /* Set window caption
2166 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2168 str += driver->getName();
2170 device->setWindowCaption(str.c_str());
2172 LocalPlayer *player = client->getEnv().getLocalPlayer();
2173 player->hurt_tilt_timer = 0;
2174 player->hurt_tilt_strength = 0;
2176 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2179 *error_message = "Memory error: could not create HUD";
2180 errorstream << *error_message << std::endl;
2184 mapper = client->getMapper();
2185 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2190 bool Game::initGui()
2192 // First line of debug text
2193 guitext = guienv->addStaticText(
2194 utf8_to_wide(PROJECT_NAME_C).c_str(),
2195 core::rect<s32>(0, 0, 0, 0),
2196 false, false, guiroot);
2198 // Second line of debug text
2199 guitext2 = guienv->addStaticText(
2201 core::rect<s32>(0, 0, 0, 0),
2202 false, false, guiroot);
2204 // At the middle of the screen
2205 // Object infos are shown in this
2206 guitext_info = guienv->addStaticText(
2208 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2209 false, true, guiroot);
2211 // Status text (displays info when showing and hiding GUI stuff, etc.)
2212 guitext_status = guienv->addStaticText(
2214 core::rect<s32>(0, 0, 0, 0),
2215 false, false, guiroot);
2216 guitext_status->setVisible(false);
2219 guitext_chat = guienv->addStaticText(
2221 core::rect<s32>(0, 0, 0, 0),
2222 //false, false); // Disable word wrap as of now
2223 false, true, guiroot);
2224 // Remove stale "recent" chat messages from previous connections
2225 chat_backend->clearRecentChat();
2227 // Chat backend and console
2228 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2229 -1, chat_backend, client, &g_menumgr);
2230 if (!gui_chat_console) {
2231 *error_message = "Could not allocate memory for chat console";
2232 errorstream << *error_message << std::endl;
2236 // Profiler text (size is updated when text is updated)
2237 guitext_profiler = guienv->addStaticText(
2239 core::rect<s32>(0, 0, 0, 0),
2240 false, false, guiroot);
2241 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2242 guitext_profiler->setVisible(false);
2243 guitext_profiler->setWordWrap(true);
2245 #ifdef HAVE_TOUCHSCREENGUI
2247 if (g_touchscreengui)
2248 g_touchscreengui->init(texture_src);
2255 bool Game::connectToServer(const std::string &playername,
2256 const std::string &password, std::string *address, u16 port,
2257 bool *connect_ok, bool *aborted)
2259 *connect_ok = false; // Let's not be overly optimistic
2261 bool local_server_mode = false;
2263 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2265 Address connect_address(0, 0, 0, 0, port);
2268 connect_address.Resolve(address->c_str());
2270 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2271 //connect_address.Resolve("localhost");
2272 if (connect_address.isIPv6()) {
2273 IPv6AddressBytes addr_bytes;
2274 addr_bytes.bytes[15] = 1;
2275 connect_address.setAddress(&addr_bytes);
2277 connect_address.setAddress(127, 0, 0, 1);
2279 local_server_mode = true;
2281 } catch (ResolveError &e) {
2282 *error_message = std::string("Couldn't resolve address: ") + e.what();
2283 errorstream << *error_message << std::endl;
2287 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2288 *error_message = "Unable to connect to " +
2289 connect_address.serializeString() +
2290 " because IPv6 is disabled";
2291 errorstream << *error_message << std::endl;
2295 client = new Client(device,
2296 playername.c_str(), password,
2297 *draw_control, texture_src, shader_src,
2298 itemdef_manager, nodedef_manager, sound, eventmgr,
2299 connect_address.isIPv6());
2304 gamedef = client; // Client acts as our GameDef
2306 infostream << "Connecting to server at ";
2307 connect_address.print(&infostream);
2308 infostream << std::endl;
2310 client->connect(connect_address, *address,
2311 simple_singleplayer_mode || local_server_mode);
2314 Wait for server to accept connection
2320 FpsControl fps_control = { 0 };
2322 f32 wait_time = 0; // in seconds
2324 fps_control.last_time = device->getTimer()->getTime();
2326 while (device->run()) {
2328 limitFps(&fps_control, &dtime);
2330 // Update client and server
2331 client->step(dtime);
2334 server->step(dtime);
2337 if (client->getState() == LC_Init) {
2343 if (client->accessDenied()) {
2344 *error_message = "Access denied. Reason: "
2345 + client->accessDeniedReason();
2346 *reconnect_requested = client->reconnectRequested();
2347 errorstream << *error_message << std::endl;
2351 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2353 infostream << "Connect aborted [Escape]" << std::endl;
2358 // Only time out if we aren't waiting for the server we started
2359 if ((*address != "") && (wait_time > 10)) {
2360 *error_message = "Connection timed out.";
2361 errorstream << *error_message << std::endl;
2366 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2368 } catch (con::PeerNotFoundException &e) {
2369 // TODO: Should something be done here? At least an info/error
2377 bool Game::getServerContent(bool *aborted)
2381 FpsControl fps_control = { 0 };
2382 f32 dtime; // in seconds
2384 fps_control.last_time = device->getTimer()->getTime();
2386 while (device->run()) {
2388 limitFps(&fps_control, &dtime);
2390 // Update client and server
2391 client->step(dtime);
2394 server->step(dtime);
2397 if (client->mediaReceived() && client->itemdefReceived() &&
2398 client->nodedefReceived()) {
2403 if (!checkConnection())
2406 if (client->getState() < LC_Init) {
2407 *error_message = "Client disconnected";
2408 errorstream << *error_message << std::endl;
2412 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2414 infostream << "Connect aborted [Escape]" << std::endl;
2421 if (!client->itemdefReceived()) {
2422 const wchar_t *text = wgettext("Item definitions...");
2424 draw_load_screen(text, device, guienv, dtime, progress);
2426 } else if (!client->nodedefReceived()) {
2427 const wchar_t *text = wgettext("Node definitions...");
2429 draw_load_screen(text, device, guienv, dtime, progress);
2432 std::stringstream message;
2433 message.precision(3);
2434 message << gettext("Media...");
2436 if ((USE_CURL == 0) ||
2437 (!g_settings->getBool("enable_remote_media_server"))) {
2438 float cur = client->getCurRate();
2439 std::string cur_unit = gettext("KiB/s");
2443 cur_unit = gettext("MiB/s");
2446 message << " (" << cur << ' ' << cur_unit << ")";
2449 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2450 draw_load_screen(utf8_to_wide(message.str()), device,
2451 guienv, dtime, progress);
2459 /****************************************************************************/
2460 /****************************************************************************
2462 ****************************************************************************/
2463 /****************************************************************************/
2465 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2467 if (runData->nodig_delay_timer >= 0)
2468 runData->nodig_delay_timer -= dtime;
2470 if (runData->object_hit_delay_timer >= 0)
2471 runData->object_hit_delay_timer -= dtime;
2473 runData->time_from_last_punch += dtime;
2477 /* returns false if game should exit, otherwise true
2479 inline bool Game::checkConnection()
2481 if (client->accessDenied()) {
2482 *error_message = "Access denied. Reason: "
2483 + client->accessDeniedReason();
2484 *reconnect_requested = client->reconnectRequested();
2485 errorstream << *error_message << std::endl;
2493 /* returns false if game should exit, otherwise true
2495 inline bool Game::handleCallbacks()
2497 if (g_gamecallback->disconnect_requested) {
2498 g_gamecallback->disconnect_requested = false;
2502 if (g_gamecallback->changepassword_requested) {
2503 (new GUIPasswordChange(guienv, guiroot, -1,
2504 &g_menumgr, client))->drop();
2505 g_gamecallback->changepassword_requested = false;
2508 if (g_gamecallback->changevolume_requested) {
2509 (new GUIVolumeChange(guienv, guiroot, -1,
2510 &g_menumgr, client))->drop();
2511 g_gamecallback->changevolume_requested = false;
2514 if (g_gamecallback->keyconfig_requested) {
2515 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2516 &g_menumgr))->drop();
2517 g_gamecallback->keyconfig_requested = false;
2520 if (g_gamecallback->keyconfig_changed) {
2521 keycache.populate(); // update the cache with new settings
2522 g_gamecallback->keyconfig_changed = false;
2529 void Game::processQueues()
2531 texture_src->processQueue();
2532 itemdef_manager->processQueue(gamedef);
2533 shader_src->processQueue();
2537 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2538 const FpsControl &draw_times, f32 dtime)
2540 float profiler_print_interval =
2541 g_settings->getFloat("profiler_print_interval");
2542 bool print_to_log = true;
2544 if (profiler_print_interval == 0) {
2545 print_to_log = false;
2546 profiler_print_interval = 5;
2549 if (profiler_interval.step(dtime, profiler_print_interval)) {
2551 infostream << "Profiler:" << std::endl;
2552 g_profiler->print(infostream);
2555 update_profiler_gui(guitext_profiler, g_fontengine,
2556 runData.profiler_current_page, runData.profiler_max_page,
2557 driver->getScreenSize().Height);
2559 g_profiler->clear();
2562 addProfilerGraphs(stats, draw_times, dtime);
2566 void Game::addProfilerGraphs(const RunStats &stats,
2567 const FpsControl &draw_times, f32 dtime)
2569 g_profiler->graphAdd("mainloop_other",
2570 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2572 if (draw_times.sleep_time != 0)
2573 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2574 g_profiler->graphAdd("mainloop_dtime", dtime);
2576 g_profiler->add("Elapsed time", dtime);
2577 g_profiler->avg("FPS", 1. / dtime);
2581 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2588 /* Time average and jitter calculation
2590 jp = &stats->dtime_jitter;
2591 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2593 jitter = dtime - jp->avg;
2595 if (jitter > jp->max)
2598 jp->counter += dtime;
2600 if (jp->counter > 0.0) {
2602 jp->max_sample = jp->max;
2603 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2607 /* Busytime average and jitter calculation
2609 jp = &stats->busy_time_jitter;
2610 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2612 jitter = draw_times.busy_time - jp->avg;
2614 if (jitter > jp->max)
2616 if (jitter < jp->min)
2619 jp->counter += dtime;
2621 if (jp->counter > 0.0) {
2623 jp->max_sample = jp->max;
2624 jp->min_sample = jp->min;
2632 /****************************************************************************
2634 ****************************************************************************/
2636 void Game::processUserInput(VolatileRunFlags *flags,
2637 GameRunData *runData, f32 dtime)
2639 // Reset input if window not active or some menu is active
2640 if (device->isWindowActive() == false
2641 || noMenuActive() == false
2642 || guienv->hasFocus(gui_chat_console)) {
2644 #ifdef HAVE_TOUCHSCREENGUI
2645 g_touchscreengui->hide();
2648 #ifdef HAVE_TOUCHSCREENGUI
2649 else if (g_touchscreengui) {
2650 /* on touchscreengui step may generate own input events which ain't
2651 * what we want in case we just did clear them */
2652 g_touchscreengui->step(dtime);
2656 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2657 gui_chat_console->closeConsoleAtOnce();
2660 // Input handler step() (used by the random input generator)
2664 if (current_formspec != NULL)
2665 current_formspec->getAndroidUIInput();
2667 handleAndroidChatInput();
2670 // Increase timer for double tap of "keymap_jump"
2671 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2672 runData->jump_timer += dtime;
2674 processKeyboardInput(
2676 &runData->statustext_time,
2677 &runData->jump_timer,
2678 &runData->reset_jump_timer,
2679 &runData->profiler_current_page,
2680 runData->profiler_max_page);
2682 processItemSelection(&runData->new_playeritem);
2686 void Game::processKeyboardInput(VolatileRunFlags *flags,
2687 float *statustext_time,
2689 bool *reset_jump_timer,
2690 u32 *profiler_current_page,
2691 u32 profiler_max_page)
2694 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2696 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2698 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_AUTORUN])) {
2699 toggleAutorun(statustext_time);
2700 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2702 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2703 if (!gui_chat_console->isOpenInhibited()) {
2704 show_pause_menu(¤t_formspec, client, gamedef,
2705 texture_src, device, simple_singleplayer_mode);
2707 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2708 openConsole(0.2, L"");
2709 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2710 openConsole(0.2, L"/");
2711 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2713 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2714 toggleFreeMove(statustext_time);
2715 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2716 toggleFreeMoveAlt(statustext_time, jump_timer);
2717 *reset_jump_timer = true;
2718 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2719 toggleFast(statustext_time);
2720 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2721 toggleNoClip(statustext_time);
2722 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2723 toggleCinematic(statustext_time);
2724 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2725 client->makeScreenshot(device);
2726 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2727 toggleHud(statustext_time, &flags->show_hud);
2728 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_MINIMAP])) {
2729 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2730 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]));
2731 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2732 toggleChat(statustext_time, &flags->show_chat);
2733 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2734 toggleFog(statustext_time, &flags->force_fog_off);
2735 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2736 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2737 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2738 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2739 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2740 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2741 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2742 increaseViewRange(statustext_time);
2743 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2744 decreaseViewRange(statustext_time);
2745 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2746 toggleFullViewRange(statustext_time);
2747 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT])) {
2749 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV])) {
2751 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC])) {
2753 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC])) {
2755 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2756 // Print debug stacks
2757 dstream << "-----------------------------------------"
2759 dstream << "Printing debug stacks:" << std::endl;
2760 dstream << "-----------------------------------------"
2762 debug_stacks_print();
2765 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2766 *reset_jump_timer = false;
2772 if (quicktune->hasMessage()) {
2773 std::string msg = quicktune->getMessage();
2774 statustext = utf8_to_wide(msg);
2775 *statustext_time = 0;
2780 void Game::processItemSelection(u16 *new_playeritem)
2782 LocalPlayer *player = client->getEnv().getLocalPlayer();
2784 /* Item selection using mouse wheel
2786 *new_playeritem = client->getPlayerItem();
2788 s32 wheel = input->getMouseWheel();
2789 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2790 player->hud_hotbar_itemcount - 1);
2793 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2795 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2799 /* Item selection using keyboard
2801 for (u16 i = 0; i < 10; i++) {
2802 static const KeyPress *item_keys[10] = {
2803 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2804 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2805 NumberKey + 9, NumberKey + 0,
2808 if (input->wasKeyDown(*item_keys[i])) {
2809 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2810 *new_playeritem = i;
2811 infostream << "Selected item: " << new_playeritem << std::endl;
2819 void Game::dropSelectedItem()
2821 IDropAction *a = new IDropAction();
2823 a->from_inv.setCurrentPlayer();
2824 a->from_list = "main";
2825 a->from_i = client->getPlayerItem();
2826 client->inventoryAction(a);
2830 void Game::openInventory()
2833 * Don't permit to open inventory is CAO or player doesn't exists.
2834 * This prevent showing an empty inventory at player load
2837 LocalPlayer *player = client->getEnv().getLocalPlayer();
2838 if (player == NULL || player->getCAO() == NULL)
2841 infostream << "the_game: " << "Launching inventory" << std::endl;
2843 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2844 TextDest *txt_dst = new TextDestPlayerInventory(client);
2846 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2847 device, fs_src, txt_dst, client);
2849 InventoryLocation inventoryloc;
2850 inventoryloc.setCurrentPlayer();
2851 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2855 void Game::openConsole(float height, const wchar_t *line)
2858 porting::showInputDialog(gettext("ok"), "", "", 2);
2859 m_android_chat_open = true;
2861 if (gui_chat_console->isOpenInhibited())
2863 gui_chat_console->openConsole(height);
2865 gui_chat_console->setCloseOnEnter(true);
2866 gui_chat_console->replaceAndAddToHistory(line);
2872 void Game::handleAndroidChatInput()
2874 if (m_android_chat_open && porting::getInputDialogState() == 0) {
2875 std::string text = porting::getInputDialogValue();
2876 client->typeChatMessage(utf8_to_wide(text));
2882 void Game::toggleFreeMove(float *statustext_time)
2884 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2886 bool free_move = !g_settings->getBool("free_move");
2887 g_settings->set("free_move", bool_to_cstr(free_move));
2889 *statustext_time = 0;
2890 statustext = msg[free_move];
2891 if (free_move && !client->checkPrivilege("fly"))
2892 statustext += L" (note: no 'fly' privilege)";
2896 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2898 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2899 toggleFreeMove(statustext_time);
2903 void Game::toggleFast(float *statustext_time)
2905 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2906 bool fast_move = !g_settings->getBool("fast_move");
2907 g_settings->set("fast_move", bool_to_cstr(fast_move));
2909 *statustext_time = 0;
2910 statustext = msg[fast_move];
2912 bool has_fast_privs = client->checkPrivilege("fast");
2914 if (fast_move && !has_fast_privs)
2915 statustext += L" (note: no 'fast' privilege)";
2918 m_cache_hold_aux1 = fast_move && has_fast_privs;
2923 void Game::toggleNoClip(float *statustext_time)
2925 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2926 bool noclip = !g_settings->getBool("noclip");
2927 g_settings->set("noclip", bool_to_cstr(noclip));
2929 *statustext_time = 0;
2930 statustext = msg[noclip];
2932 if (noclip && !client->checkPrivilege("noclip"))
2933 statustext += L" (note: no 'noclip' privilege)";
2936 void Game::toggleCinematic(float *statustext_time)
2938 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2939 bool cinematic = !g_settings->getBool("cinematic");
2940 g_settings->set("cinematic", bool_to_cstr(cinematic));
2942 *statustext_time = 0;
2943 statustext = msg[cinematic];
2946 // Add WoW-style autorun by toggling continuous forward.
2947 void Game::toggleAutorun(float *statustext_time)
2949 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2950 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2951 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2953 *statustext_time = 0;
2954 statustext = msg[autorun_enabled ? 1 : 0];
2957 void Game::toggleChat(float *statustext_time, bool *flag)
2959 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2962 *statustext_time = 0;
2963 statustext = msg[*flag];
2967 void Game::toggleHud(float *statustext_time, bool *flag)
2969 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2972 *statustext_time = 0;
2973 statustext = msg[*flag];
2976 void Game::toggleMinimap(float *statustext_time, bool *flag,
2977 bool show_hud, bool shift_pressed)
2979 if (!show_hud || !g_settings->getBool("enable_minimap"))
2982 if (shift_pressed) {
2983 mapper->toggleMinimapShape();
2987 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2989 MinimapMode mode = MINIMAP_MODE_OFF;
2990 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2991 mode = mapper->getMinimapMode();
2992 mode = (MinimapMode)((int)mode + 1);
2997 case MINIMAP_MODE_SURFACEx1:
2998 statustext = L"Minimap in surface mode, Zoom x1";
3000 case MINIMAP_MODE_SURFACEx2:
3001 statustext = L"Minimap in surface mode, Zoom x2";
3003 case MINIMAP_MODE_SURFACEx4:
3004 statustext = L"Minimap in surface mode, Zoom x4";
3006 case MINIMAP_MODE_RADARx1:
3007 statustext = L"Minimap in radar mode, Zoom x1";
3009 case MINIMAP_MODE_RADARx2:
3010 statustext = L"Minimap in radar mode, Zoom x2";
3012 case MINIMAP_MODE_RADARx4:
3013 statustext = L"Minimap in radar mode, Zoom x4";
3016 mode = MINIMAP_MODE_OFF;
3018 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
3019 L"Minimap hidden" : L"Minimap disabled by server";
3022 *statustext_time = 0;
3023 mapper->setMinimapMode(mode);
3026 void Game::toggleFog(float *statustext_time, bool *flag)
3028 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
3031 *statustext_time = 0;
3032 statustext = msg[*flag];
3036 void Game::toggleDebug(float *statustext_time, bool *show_debug,
3037 bool *show_profiler_graph)
3039 // Initial / 3x toggle: Chat only
3040 // 1x toggle: Debug text with chat
3041 // 2x toggle: Debug text with profiler graph
3044 *show_profiler_graph = false;
3045 statustext = L"Debug info shown";
3046 } else if (*show_profiler_graph) {
3047 *show_debug = false;
3048 *show_profiler_graph = false;
3049 statustext = L"Debug info and profiler graph hidden";
3051 *show_profiler_graph = true;
3052 statustext = L"Profiler graph shown";
3054 *statustext_time = 0;
3058 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3060 static const wchar_t *msg[] = {
3061 L"Camera update enabled",
3062 L"Camera update disabled"
3066 *statustext_time = 0;
3067 statustext = msg[*flag];
3071 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3072 u32 profiler_max_page)
3074 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3076 // FIXME: This updates the profiler with incomplete values
3077 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3078 profiler_max_page, driver->getScreenSize().Height);
3080 if (*profiler_current_page != 0) {
3081 std::wstringstream sstr;
3082 sstr << "Profiler shown (page " << *profiler_current_page
3083 << " of " << profiler_max_page << ")";
3084 statustext = sstr.str();
3086 statustext = L"Profiler hidden";
3088 *statustext_time = 0;
3092 void Game::increaseViewRange(float *statustext_time)
3094 s16 range = g_settings->getS16("viewing_range");
3095 s16 range_new = range + 10;
3096 g_settings->set("viewing_range", itos(range_new));
3097 statustext = utf8_to_wide("Viewing range changed to "
3099 *statustext_time = 0;
3103 void Game::decreaseViewRange(float *statustext_time)
3105 s16 range = g_settings->getS16("viewing_range");
3106 s16 range_new = range - 10;
3111 g_settings->set("viewing_range", itos(range_new));
3112 statustext = utf8_to_wide("Viewing range changed to "
3114 *statustext_time = 0;
3118 void Game::toggleFullViewRange(float *statustext_time)
3120 static const wchar_t *msg[] = {
3121 L"Disabled full viewing range",
3122 L"Enabled full viewing range"
3125 draw_control->range_all = !draw_control->range_all;
3126 infostream << msg[draw_control->range_all] << std::endl;
3127 statustext = msg[draw_control->range_all];
3128 *statustext_time = 0;
3132 void Game::updateCameraDirection(CameraOrientation *cam,
3133 VolatileRunFlags *flags)
3135 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3138 if (!random_input) {
3139 // Mac OSX gets upset if this is set every frame
3140 if (device->getCursorControl()->isVisible())
3141 device->getCursorControl()->setVisible(false);
3145 if (flags->first_loop_after_window_activation)
3146 flags->first_loop_after_window_activation = false;
3148 updateCameraOrientation(cam, *flags);
3150 input->setMousePos((driver->getScreenSize().Width / 2),
3151 (driver->getScreenSize().Height / 2));
3155 // Mac OSX gets upset if this is set every frame
3156 if (device->getCursorControl()->isVisible() == false)
3157 device->getCursorControl()->setVisible(true);
3160 if (!flags->first_loop_after_window_activation)
3161 flags->first_loop_after_window_activation = true;
3167 void Game::updateCameraOrientation(CameraOrientation *cam,
3168 const VolatileRunFlags &flags)
3170 #ifdef HAVE_TOUCHSCREENGUI
3171 if (g_touchscreengui) {
3172 cam->camera_yaw = g_touchscreengui->getYaw();
3173 cam->camera_pitch = g_touchscreengui->getPitch();
3176 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3177 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3179 if (flags.invert_mouse
3180 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3184 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3185 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3187 #ifdef HAVE_TOUCHSCREENGUI
3191 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3195 void Game::updatePlayerControl(const CameraOrientation &cam)
3197 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3199 PlayerControl control(
3200 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
3201 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
3202 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3203 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3204 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3205 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3206 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3207 input->getLeftState(),
3208 input->getRightState(),
3214 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3215 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3216 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3217 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3218 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3219 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3220 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3221 ( (u32)(input->getLeftState() & 0x1) << 7) |
3222 ( (u32)(input->getRightState() & 0x1) << 8
3226 /* For Android, simulate holding down AUX1 (fast move) if the user has
3227 * the fast_move setting toggled on. If there is an aux1 key defined for
3228 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3231 if (m_cache_hold_aux1) {
3232 control.aux1 = control.aux1 ^ true;
3233 keypress_bits ^= ((u32)(1U << 5));
3237 client->setPlayerControl(control);
3238 LocalPlayer *player = client->getEnv().getLocalPlayer();
3239 player->keyPressed = keypress_bits;
3245 inline void Game::step(f32 *dtime)
3247 bool can_be_and_is_paused =
3248 (simple_singleplayer_mode && g_menumgr.pausesGame());
3250 if (can_be_and_is_paused) { // This is for a singleplayer server
3251 *dtime = 0; // No time passes
3253 if (server != NULL) {
3254 //TimeTaker timer("server->step(dtime)");
3255 server->step(*dtime);
3258 //TimeTaker timer("client.step(dtime)");
3259 client->step(*dtime);
3264 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3266 ClientEvent event = client->getClientEvent();
3268 LocalPlayer *player = client->getEnv().getLocalPlayer();
3270 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3272 if (event.type == CE_PLAYER_DAMAGE &&
3273 client->getHP() != 0) {
3274 //u16 damage = event.player_damage.amount;
3275 //infostream<<"Player damage: "<<damage<<std::endl;
3277 *damage_flash += 100.0;
3278 *damage_flash += 8.0 * event.player_damage.amount;
3280 player->hurt_tilt_timer = 1.5;
3281 player->hurt_tilt_strength = event.player_damage.amount / 4;
3282 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3284 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3285 gamedef->event()->put(e);
3286 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3287 cam->camera_yaw = event.player_force_move.yaw;
3288 cam->camera_pitch = event.player_force_move.pitch;
3289 } else if (event.type == CE_DEATHSCREEN) {
3290 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3293 chat_backend->addMessage(L"", L"You died.");
3295 /* Handle visualization */
3297 player->hurt_tilt_timer = 0;
3298 player->hurt_tilt_strength = 0;
3300 } else if (event.type == CE_SHOW_FORMSPEC) {
3301 FormspecFormSource *fs_src =
3302 new FormspecFormSource(*(event.show_formspec.formspec));
3303 TextDestPlayerInventory *txt_dst =
3304 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3306 create_formspec_menu(¤t_formspec, client, gamedef,
3307 texture_src, device, fs_src, txt_dst, client);
3309 delete(event.show_formspec.formspec);
3310 delete(event.show_formspec.formname);
3311 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3312 (event.type == CE_ADD_PARTICLESPAWNER) ||
3313 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3314 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3316 } else if (event.type == CE_HUDADD) {
3317 u32 id = event.hudadd.id;
3319 LocalPlayer *player = client->getEnv().getLocalPlayer();
3320 HudElement *e = player->getHud(id);
3323 delete event.hudadd.pos;
3324 delete event.hudadd.name;
3325 delete event.hudadd.scale;
3326 delete event.hudadd.text;
3327 delete event.hudadd.align;
3328 delete event.hudadd.offset;
3329 delete event.hudadd.world_pos;
3330 delete event.hudadd.size;
3335 e->type = (HudElementType)event.hudadd.type;
3336 e->pos = *event.hudadd.pos;
3337 e->name = *event.hudadd.name;
3338 e->scale = *event.hudadd.scale;
3339 e->text = *event.hudadd.text;
3340 e->number = event.hudadd.number;
3341 e->item = event.hudadd.item;
3342 e->dir = event.hudadd.dir;
3343 e->align = *event.hudadd.align;
3344 e->offset = *event.hudadd.offset;
3345 e->world_pos = *event.hudadd.world_pos;
3346 e->size = *event.hudadd.size;
3348 u32 new_id = player->addHud(e);
3349 //if this isn't true our huds aren't consistent
3350 sanity_check(new_id == id);
3352 delete event.hudadd.pos;
3353 delete event.hudadd.name;
3354 delete event.hudadd.scale;
3355 delete event.hudadd.text;
3356 delete event.hudadd.align;
3357 delete event.hudadd.offset;
3358 delete event.hudadd.world_pos;
3359 delete event.hudadd.size;
3360 } else if (event.type == CE_HUDRM) {
3361 HudElement *e = player->removeHud(event.hudrm.id);
3365 } else if (event.type == CE_HUDCHANGE) {
3366 u32 id = event.hudchange.id;
3367 HudElement *e = player->getHud(id);
3370 delete event.hudchange.v3fdata;
3371 delete event.hudchange.v2fdata;
3372 delete event.hudchange.sdata;
3373 delete event.hudchange.v2s32data;
3377 switch (event.hudchange.stat) {
3379 e->pos = *event.hudchange.v2fdata;
3383 e->name = *event.hudchange.sdata;
3386 case HUD_STAT_SCALE:
3387 e->scale = *event.hudchange.v2fdata;
3391 e->text = *event.hudchange.sdata;
3394 case HUD_STAT_NUMBER:
3395 e->number = event.hudchange.data;
3399 e->item = event.hudchange.data;
3403 e->dir = event.hudchange.data;
3406 case HUD_STAT_ALIGN:
3407 e->align = *event.hudchange.v2fdata;
3410 case HUD_STAT_OFFSET:
3411 e->offset = *event.hudchange.v2fdata;
3414 case HUD_STAT_WORLD_POS:
3415 e->world_pos = *event.hudchange.v3fdata;
3419 e->size = *event.hudchange.v2s32data;
3423 delete event.hudchange.v3fdata;
3424 delete event.hudchange.v2fdata;
3425 delete event.hudchange.sdata;
3426 delete event.hudchange.v2s32data;
3427 } else if (event.type == CE_SET_SKY) {
3428 sky->setVisible(false);
3435 // Handle according to type
3436 if (*event.set_sky.type == "regular") {
3437 sky->setVisible(true);
3438 } else if (*event.set_sky.type == "skybox" &&
3439 event.set_sky.params->size() == 6) {
3440 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3441 skybox = smgr->addSkyBoxSceneNode(
3442 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3443 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3444 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3445 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3446 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3447 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3449 // Handle everything else as plain color
3451 if (*event.set_sky.type != "plain")
3452 infostream << "Unknown sky type: "
3453 << (*event.set_sky.type) << std::endl;
3455 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3458 delete event.set_sky.bgcolor;
3459 delete event.set_sky.type;
3460 delete event.set_sky.params;
3461 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3462 bool enable = event.override_day_night_ratio.do_override;
3463 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3464 client->getEnv().setDayNightRatioOverride(enable, value);
3470 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3471 f32 dtime, float time_from_last_punch)
3473 LocalPlayer *player = client->getEnv().getLocalPlayer();
3476 For interaction purposes, get info about the held item
3478 - Is it a usable item?
3479 - Can it point to liquids?
3481 ItemStack playeritem;
3483 InventoryList *mlist = local_inventory->getList("main");
3485 if (mlist && client->getPlayerItem() < mlist->getSize())
3486 playeritem = mlist->getItem(client->getPlayerItem());
3489 ToolCapabilities playeritem_toolcap =
3490 playeritem.getToolCapabilities(itemdef_manager);
3492 v3s16 old_camera_offset = camera->getOffset();
3494 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3495 GenericCAO *playercao = player->getCAO();
3497 // If playercao not loaded, don't change camera
3498 if (playercao == NULL)
3501 camera->toggleCameraMode();
3503 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3504 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3507 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3508 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3510 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3511 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3513 camera->step(dtime);
3515 v3f camera_position = camera->getPosition();
3516 v3f camera_direction = camera->getDirection();
3517 f32 camera_fov = camera->getFovMax();
3518 v3s16 camera_offset = camera->getOffset();
3520 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3522 if (!flags->disable_camera_update) {
3523 client->getEnv().getClientMap().updateCamera(camera_position,
3524 camera_direction, camera_fov, camera_offset);
3526 if (flags->camera_offset_changed) {
3527 client->updateCameraOffset(camera_offset);
3528 client->getEnv().updateCameraOffset(camera_offset);
3531 clouds->updateCameraOffset(camera_offset);
3537 void Game::updateSound(f32 dtime)
3539 // Update sound listener
3540 v3s16 camera_offset = camera->getOffset();
3541 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3542 v3f(0, 0, 0), // velocity
3543 camera->getDirection(),
3544 camera->getCameraNode()->getUpVector());
3545 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3548 // Update sound maker
3549 soundmaker->step(dtime);
3551 LocalPlayer *player = client->getEnv().getLocalPlayer();
3553 ClientMap &map = client->getEnv().getClientMap();
3554 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3555 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3559 void Game::processPlayerInteraction(GameRunData *runData,
3560 f32 dtime, bool show_hud, bool show_debug)
3562 LocalPlayer *player = client->getEnv().getLocalPlayer();
3564 ItemStack playeritem;
3566 InventoryList *mlist = local_inventory->getList("main");
3568 if (mlist && client->getPlayerItem() < mlist->getSize())
3569 playeritem = mlist->getItem(client->getPlayerItem());
3572 const ItemDefinition &playeritem_def =
3573 playeritem.getDefinition(itemdef_manager);
3575 v3f player_position = player->getPosition();
3576 v3f camera_position = camera->getPosition();
3577 v3f camera_direction = camera->getDirection();
3578 v3s16 camera_offset = camera->getOffset();
3582 Calculate what block is the crosshair pointing to
3585 f32 d = playeritem_def.range; // max. distance
3586 f32 d_hand = itemdef_manager->get("").range;
3588 if (d < 0 && d_hand >= 0)
3593 core::line3d<f32> shootline;
3595 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3597 shootline = core::line3d<f32>(camera_position,
3598 camera_position + camera_direction * BS * (d + 1));
3601 // prevent player pointing anything in front-view
3602 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3603 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3606 #ifdef HAVE_TOUCHSCREENGUI
3608 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3609 shootline = g_touchscreengui->getShootline();
3610 shootline.start += intToFloat(camera_offset, BS);
3611 shootline.end += intToFloat(camera_offset, BS);
3616 PointedThing pointed = getPointedThing(
3618 client, hud, player_position, camera_direction,
3619 camera_position, shootline, d,
3620 playeritem_def.liquids_pointable,
3621 !runData->ldown_for_dig,
3624 runData->selected_object);
3626 if (pointed != runData->pointed_old) {
3627 infostream << "Pointing at " << pointed.dump() << std::endl;
3628 hud->updateSelectionMesh(camera_offset);
3633 - releasing left mouse button
3634 - pointing away from node
3636 if (runData->digging) {
3637 if (input->getLeftReleased()) {
3638 infostream << "Left button released"
3639 << " (stopped digging)" << std::endl;
3640 runData->digging = false;
3641 } else if (pointed != runData->pointed_old) {
3642 if (pointed.type == POINTEDTHING_NODE
3643 && runData->pointed_old.type == POINTEDTHING_NODE
3644 && pointed.node_undersurface
3645 == runData->pointed_old.node_undersurface) {
3646 // Still pointing to the same node, but a different face.
3649 infostream << "Pointing away from node"
3650 << " (stopped digging)" << std::endl;
3651 runData->digging = false;
3652 hud->updateSelectionMesh(camera_offset);
3656 if (!runData->digging) {
3657 client->interact(1, runData->pointed_old);
3658 client->setCrack(-1, v3s16(0, 0, 0));
3659 runData->dig_time = 0.0;
3663 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3664 runData->ldown_for_dig = false;
3667 runData->left_punch = false;
3669 soundmaker->m_player_leftpunch_sound.name = "";
3671 if (input->getRightState())
3672 runData->repeat_rightclick_timer += dtime;
3674 runData->repeat_rightclick_timer = 0;
3676 if (playeritem_def.usable && input->getLeftState()) {
3677 if (input->getLeftClicked())
3678 client->interact(4, pointed);
3679 } else if (pointed.type == POINTEDTHING_NODE) {
3680 ToolCapabilities playeritem_toolcap =
3681 playeritem.getToolCapabilities(itemdef_manager);
3682 handlePointingAtNode(runData, pointed, playeritem_def,
3683 playeritem_toolcap, dtime);
3684 } else if (pointed.type == POINTEDTHING_OBJECT) {
3685 handlePointingAtObject(runData, pointed, playeritem,
3686 player_position, show_debug);
3687 } else if (input->getLeftState()) {
3688 // When button is held down in air, show continuous animation
3689 runData->left_punch = true;
3690 } else if (input->getRightClicked()) {
3691 handlePointingAtNothing(runData, playeritem);
3694 runData->pointed_old = pointed;
3696 if (runData->left_punch || input->getLeftClicked())
3697 camera->setDigging(0); // left click animation
3699 input->resetLeftClicked();
3700 input->resetRightClicked();
3702 input->resetLeftReleased();
3703 input->resetRightReleased();
3707 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3709 infostream << "Right Clicked in Air" << std::endl;
3710 PointedThing fauxPointed;
3711 fauxPointed.type = POINTEDTHING_NOTHING;
3712 client->interact(5, fauxPointed);
3716 void Game::handlePointingAtNode(GameRunData *runData,
3717 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3718 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3720 v3s16 nodepos = pointed.node_undersurface;
3721 v3s16 neighbourpos = pointed.node_abovesurface;
3724 Check information text of node
3727 ClientMap &map = client->getEnv().getClientMap();
3728 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3731 infotext = utf8_to_wide(meta->getString("infotext"));
3733 MapNode n = map.getNodeNoEx(nodepos);
3735 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3736 infotext = L"Unknown node: ";
3737 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3741 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3742 && client->checkPrivilege("interact")) {
3743 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3746 if ((input->getRightClicked() ||
3747 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3748 client->checkPrivilege("interact")) {
3749 runData->repeat_rightclick_timer = 0;
3750 infostream << "Ground right-clicked" << std::endl;
3752 if (meta && meta->getString("formspec") != "" && !random_input
3753 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3754 infostream << "Launching custom inventory view" << std::endl;
3756 InventoryLocation inventoryloc;
3757 inventoryloc.setNodeMeta(nodepos);
3759 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3760 &client->getEnv().getClientMap(), nodepos);
3761 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3763 create_formspec_menu(¤t_formspec, client, gamedef,
3764 texture_src, device, fs_src, txt_dst, client);
3766 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3768 // Report right click to server
3770 camera->setDigging(1); // right click animation (always shown for feedback)
3772 // If the wielded item has node placement prediction,
3774 bool placed = nodePlacementPrediction(*client,
3776 nodepos, neighbourpos);
3780 client->interact(3, pointed);
3782 soundmaker->m_player_rightpunch_sound =
3783 playeritem_def.sound_place;
3785 soundmaker->m_player_rightpunch_sound =
3788 if (playeritem_def.node_placement_prediction == "" ||
3789 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3790 client->interact(3, pointed); // Report to server
3792 soundmaker->m_player_rightpunch_sound =
3793 playeritem_def.sound_place_failed;
3801 void Game::handlePointingAtObject(GameRunData *runData,
3802 const PointedThing &pointed,
3803 const ItemStack &playeritem,
3804 const v3f &player_position,
3807 infotext = utf8_to_wide(runData->selected_object->infoText());
3810 if (infotext != L"") {
3813 infotext += utf8_to_wide(runData->selected_object->debugInfoText());
3816 if (input->getLeftState()) {
3817 bool do_punch = false;
3818 bool do_punch_damage = false;
3820 if (runData->object_hit_delay_timer <= 0.0) {
3822 do_punch_damage = true;
3823 runData->object_hit_delay_timer = object_hit_delay;
3826 if (input->getLeftClicked())
3830 infostream << "Left-clicked object" << std::endl;
3831 runData->left_punch = true;
3834 if (do_punch_damage) {
3835 // Report direct punch
3836 v3f objpos = runData->selected_object->getPosition();
3837 v3f dir = (objpos - player_position).normalize();
3839 bool disable_send = runData->selected_object->directReportPunch(
3840 dir, &playeritem, runData->time_from_last_punch);
3841 runData->time_from_last_punch = 0;
3844 client->interact(0, pointed);
3846 } else if (input->getRightClicked()) {
3847 infostream << "Right-clicked object" << std::endl;
3848 client->interact(3, pointed); // place
3853 void Game::handleDigging(GameRunData *runData,
3854 const PointedThing &pointed, const v3s16 &nodepos,
3855 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3857 if (!runData->digging) {
3858 infostream << "Started digging" << std::endl;
3859 client->interact(0, pointed);
3860 runData->digging = true;
3861 runData->ldown_for_dig = true;
3864 LocalPlayer *player = client->getEnv().getLocalPlayer();
3865 ClientMap &map = client->getEnv().getClientMap();
3866 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3868 // NOTE: Similar piece of code exists on the server side for
3870 // Get digging parameters
3871 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3872 &playeritem_toolcap);
3874 // If can't dig, try hand
3875 if (!params.diggable) {
3876 const ItemDefinition &hand = itemdef_manager->get("");
3877 const ToolCapabilities *tp = hand.tool_capabilities;
3880 params = getDigParams(nodedef_manager->get(n).groups, tp);
3883 if (params.diggable == false) {
3884 // I guess nobody will wait for this long
3885 runData->dig_time_complete = 10000000.0;
3887 runData->dig_time_complete = params.time;
3889 if (m_cache_enable_particles) {
3890 const ContentFeatures &features =
3891 client->getNodeDefManager()->get(n);
3892 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3893 player, nodepos, features.tiles);
3897 if (runData->dig_time_complete >= 0.001) {
3898 runData->dig_index = (float)crack_animation_length
3900 / runData->dig_time_complete;
3902 // This is for torches
3903 runData->dig_index = crack_animation_length;
3906 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3908 if (sound_dig.exists() && params.diggable) {
3909 if (sound_dig.name == "__group") {
3910 if (params.main_group != "") {
3911 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3912 soundmaker->m_player_leftpunch_sound.name =
3913 std::string("default_dig_") +
3917 soundmaker->m_player_leftpunch_sound = sound_dig;
3921 // Don't show cracks if not diggable
3922 if (runData->dig_time_complete >= 100000.0) {
3923 } else if (runData->dig_index < crack_animation_length) {
3924 //TimeTaker timer("client.setTempMod");
3925 //infostream<<"dig_index="<<dig_index<<std::endl;
3926 client->setCrack(runData->dig_index, nodepos);
3928 infostream << "Digging completed" << std::endl;
3929 client->interact(2, pointed);
3930 client->setCrack(-1, v3s16(0, 0, 0));
3931 bool is_valid_position;
3932 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3933 if (is_valid_position)
3934 client->removeNode(nodepos);
3936 if (m_cache_enable_particles) {
3937 const ContentFeatures &features =
3938 client->getNodeDefManager()->get(wasnode);
3939 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3940 player, nodepos, features.tiles);
3943 runData->dig_time = 0;
3944 runData->digging = false;
3946 runData->nodig_delay_timer =
3947 runData->dig_time_complete / (float)crack_animation_length;
3949 // We don't want a corresponding delay to
3950 // very time consuming nodes
3951 if (runData->nodig_delay_timer > 0.3)
3952 runData->nodig_delay_timer = 0.3;
3954 // We want a slight delay to very little
3955 // time consuming nodes
3956 const float mindelay = 0.15;
3958 if (runData->nodig_delay_timer < mindelay)
3959 runData->nodig_delay_timer = mindelay;
3961 // Send event to trigger sound
3962 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3963 gamedef->event()->put(e);
3966 if (runData->dig_time_complete < 100000.0) {
3967 runData->dig_time += dtime;
3969 runData->dig_time = 0;
3970 client->setCrack(-1, nodepos);
3973 camera->setDigging(0); // left click animation
3977 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
3978 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
3979 const CameraOrientation &cam)
3981 LocalPlayer *player = client->getEnv().getLocalPlayer();
3987 if (draw_control->range_all) {
3988 runData->fog_range = 100000 * BS;
3990 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
3994 Calculate general brightness
3996 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3997 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3998 float direct_brightness;
4001 if (g_settings->getBool("free_move")) {
4002 direct_brightness = time_brightness;
4003 sunlight_seen = true;
4005 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
4006 float old_brightness = sky->getBrightness();
4007 direct_brightness = client->getEnv().getClientMap()
4008 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
4009 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
4013 float time_of_day = runData->time_of_day;
4014 float time_of_day_smooth = runData->time_of_day_smooth;
4016 time_of_day = client->getEnv().getTimeOfDayF();
4018 const float maxsm = 0.05;
4019 const float todsm = 0.05;
4021 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
4022 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
4023 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
4024 time_of_day_smooth = time_of_day;
4026 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
4027 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4028 + (time_of_day + 1.0) * todsm;
4030 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
4031 + time_of_day * todsm;
4033 runData->time_of_day = time_of_day;
4034 runData->time_of_day_smooth = time_of_day_smooth;
4036 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
4037 sunlight_seen, camera->getCameraMode(), player->getYaw(),
4038 player->getPitch());
4044 v3f player_position = player->getPosition();
4045 if (sky->getCloudsVisible()) {
4046 clouds->setVisible(true);
4047 clouds->step(dtime);
4048 clouds->update(v2f(player_position.X, player_position.Z),
4049 sky->getCloudColor());
4051 clouds->setVisible(false);
4058 client->getParticleManager()->step(dtime);
4064 if (m_cache_enable_fog && !flags.force_fog_off) {
4067 video::EFT_FOG_LINEAR,
4068 runData->fog_range * 0.4,
4069 runData->fog_range * 1.0,
4077 video::EFT_FOG_LINEAR,
4087 Get chat messages from client
4090 v2u32 screensize = driver->getScreenSize();
4092 updateChat(*client, dtime, flags.show_debug, screensize,
4093 flags.show_chat, runData->profiler_current_page,
4094 *chat_backend, guitext_chat);
4100 if (client->getPlayerItem() != runData->new_playeritem)
4101 client->selectPlayerItem(runData->new_playeritem);
4103 // Update local inventory if it has changed
4104 if (client->getLocalInventoryUpdated()) {
4105 //infostream<<"Updating local inventory"<<std::endl;
4106 client->getLocalInventory(*local_inventory);
4107 runData->update_wielded_item_trigger = true;
4110 if (runData->update_wielded_item_trigger) {
4111 // Update wielded tool
4112 InventoryList *mlist = local_inventory->getList("main");
4114 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4115 ItemStack item = mlist->getItem(client->getPlayerItem());
4116 camera->wield(item);
4118 runData->update_wielded_item_trigger = false;
4122 Update block draw list every 200ms or when camera direction has
4125 runData->update_draw_list_timer += dtime;
4127 v3f camera_direction = camera->getDirection();
4128 if (runData->update_draw_list_timer >= 0.2
4129 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4130 || flags.camera_offset_changed) {
4131 runData->update_draw_list_timer = 0;
4132 client->getEnv().getClientMap().updateDrawList(driver);
4133 runData->update_draw_list_last_cam_dir = camera_direction;
4136 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4139 make sure menu is on top
4140 1. Delete formspec menu reference if menu was removed
4141 2. Else, make sure formspec menu is on top
4143 if (current_formspec) {
4144 if (current_formspec->getReferenceCount() == 1) {
4145 current_formspec->drop();
4146 current_formspec = NULL;
4147 } else if (!noMenuActive()) {
4148 guiroot->bringToFront(current_formspec);
4156 video::SColor skycolor = sky->getSkyColor();
4158 TimeTaker tt_draw("mainloop: draw");
4160 TimeTaker timer("beginScene");
4161 driver->beginScene(true, true, skycolor);
4162 stats->beginscenetime = timer.stop(true);
4165 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4166 guienv, screensize, skycolor, flags.show_hud,
4167 flags.show_minimap);
4172 if (flags.show_profiler_graph)
4173 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4178 if (runData->damage_flash > 0.0) {
4179 video::SColor color(std::min(runData->damage_flash, 180.0f),
4183 driver->draw2DRectangle(color,
4184 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4187 runData->damage_flash -= 100.0 * dtime;
4193 if (player->hurt_tilt_timer > 0.0) {
4194 player->hurt_tilt_timer -= dtime * 5;
4196 if (player->hurt_tilt_timer < 0)
4197 player->hurt_tilt_strength = 0;
4201 Update minimap pos and rotation
4203 if (flags.show_minimap && flags.show_hud) {
4204 mapper->setPos(floatToInt(player->getPosition(), BS));
4205 mapper->setAngle(player->getYaw());
4212 TimeTaker timer("endScene");
4214 stats->endscenetime = timer.stop(true);
4217 stats->drawtime = tt_draw.stop(true);
4218 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4222 inline static const char *yawToDirectionString(int yaw)
4224 // NOTE: TODO: This can be done mathematically without the else/else-if
4227 const char *player_direction;
4229 yaw = wrapDegrees_0_360(yaw);
4231 if (yaw >= 45 && yaw < 135)
4232 player_direction = "West [-X]";
4233 else if (yaw >= 135 && yaw < 225)
4234 player_direction = "South [-Z]";
4235 else if (yaw >= 225 && yaw < 315)
4236 player_direction = "East [+X]";
4238 player_direction = "North [+Z]";
4240 return player_direction;
4244 void Game::updateGui(float *statustext_time, const RunStats &stats,
4245 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4246 const CameraOrientation &cam)
4248 v2u32 screensize = driver->getScreenSize();
4249 LocalPlayer *player = client->getEnv().getLocalPlayer();
4250 v3f player_position = player->getPosition();
4252 if (flags.show_debug) {
4253 static float drawtime_avg = 0;
4254 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4256 u16 fps = 1.0 / stats.dtime_jitter.avg;
4257 //s32 fps = driver->getFPS();
4259 std::ostringstream os(std::ios_base::binary);
4261 << PROJECT_NAME_C " " << g_version_hash
4263 << " (R: range_all=" << draw_control->range_all << ")"
4264 << std::setprecision(0)
4265 << " drawtime = " << drawtime_avg
4266 << std::setprecision(1)
4267 << ", dtime_jitter = "
4268 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4269 << std::setprecision(1)
4270 << ", v_range = " << draw_control->wanted_range
4271 << std::setprecision(3)
4272 << ", RTT = " << client->getRTT();
4273 guitext->setText(utf8_to_wide(os.str()).c_str());
4274 guitext->setVisible(true);
4275 } else if (flags.show_hud || flags.show_chat) {
4276 std::ostringstream os(std::ios_base::binary);
4277 os << PROJECT_NAME_C " " << g_version_hash;
4278 guitext->setText(utf8_to_wide(os.str()).c_str());
4279 guitext->setVisible(true);
4281 guitext->setVisible(false);
4284 if (guitext->isVisible()) {
4285 core::rect<s32> rect(
4287 screensize.X, 5 + g_fontengine->getTextHeight()
4289 guitext->setRelativePosition(rect);
4292 if (flags.show_debug) {
4293 std::ostringstream os(std::ios_base::binary);
4294 os << std::setprecision(1) << std::fixed
4295 << "(" << (player_position.X / BS)
4296 << ", " << (player_position.Y / BS)
4297 << ", " << (player_position.Z / BS)
4298 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4299 << " " << yawToDirectionString(cam.camera_yaw)
4300 << ") (seed = " << ((u64)client->getMapSeed())
4303 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4304 ClientMap &map = client->getEnv().getClientMap();
4305 const INodeDefManager *nodedef = client->getNodeDefManager();
4306 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4307 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4308 const ContentFeatures &features = nodedef->get(n);
4309 os << " (pointing_at = " << nodedef->get(n).name
4310 << " - " << features.tiledef[0].name.c_str()
4315 guitext2->setText(utf8_to_wide(os.str()).c_str());
4316 guitext2->setVisible(true);
4318 core::rect<s32> rect(
4319 5, 5 + g_fontengine->getTextHeight(),
4320 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4322 guitext2->setRelativePosition(rect);
4324 guitext2->setVisible(false);
4327 guitext_info->setText(infotext.c_str());
4328 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4330 float statustext_time_max = 1.5;
4332 if (!statustext.empty()) {
4333 *statustext_time += dtime;
4335 if (*statustext_time >= statustext_time_max) {
4337 *statustext_time = 0;
4341 guitext_status->setText(statustext.c_str());
4342 guitext_status->setVisible(!statustext.empty());
4344 if (!statustext.empty()) {
4345 s32 status_width = guitext_status->getTextWidth();
4346 s32 status_height = guitext_status->getTextHeight();
4347 s32 status_y = screensize.Y - 150;
4348 s32 status_x = (screensize.X - status_width) / 2;
4349 core::rect<s32> rect(
4350 status_x , status_y - status_height,
4351 status_x + status_width, status_y
4353 guitext_status->setRelativePosition(rect);
4356 video::SColor initial_color(255, 0, 0, 0);
4358 if (guienv->getSkin())
4359 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4361 video::SColor final_color = initial_color;
4362 final_color.setAlpha(0);
4363 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4364 initial_color, final_color,
4365 pow(*statustext_time / statustext_time_max, 2.0f));
4366 guitext_status->setOverrideColor(fade_color);
4367 guitext_status->enableOverrideColor(true);
4372 /* Log times and stuff for visualization */
4373 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4375 Profiler::GraphValues values;
4376 g_profiler->graphGet(values);
4382 /****************************************************************************
4384 ****************************************************************************/
4386 /* On some computers framerate doesn't seem to be automatically limited
4388 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4390 // not using getRealTime is necessary for wine
4391 device->getTimer()->tick(); // Maker sure device time is up-to-date
4392 u32 time = device->getTimer()->getTime();
4393 u32 last_time = fps_timings->last_time;
4395 if (time > last_time) // Make sure time hasn't overflowed
4396 fps_timings->busy_time = time - last_time;
4398 fps_timings->busy_time = 0;
4400 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4401 ? g_settings->getFloat("pause_fps_max")
4402 : g_settings->getFloat("fps_max"));
4404 if (fps_timings->busy_time < frametime_min) {
4405 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4406 device->sleep(fps_timings->sleep_time);
4408 fps_timings->sleep_time = 0;
4411 /* Get the new value of the device timer. Note that device->sleep() may
4412 * not sleep for the entire requested time as sleep may be interrupted and
4413 * therefore it is arguably more accurate to get the new time from the
4414 * device rather than calculating it by adding sleep_time to time.
4417 device->getTimer()->tick(); // Update device timer
4418 time = device->getTimer()->getTime();
4420 if (time > last_time) // Make sure last_time hasn't overflowed
4421 *dtime = (time - last_time) / 1000.0;
4425 fps_timings->last_time = time;
4428 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4429 // pass a copy of it to this function
4430 // Note: \p msg must be allocated using new (not malloc())
4431 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4432 int percent, bool draw_clouds)
4434 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4438 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4440 ((Game *)data)->readSettings();
4443 void Game::readSettings()
4445 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4446 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4447 m_cache_enable_particles = g_settings->getBool("enable_particles");
4448 m_cache_enable_fog = g_settings->getBool("enable_fog");
4449 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4450 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4452 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4455 /****************************************************************************/
4456 /****************************************************************************
4458 ****************************************************************************/
4459 /****************************************************************************/
4461 void Game::extendedResourceCleanup()
4463 // Extended resource accounting
4464 infostream << "Irrlicht resources after cleanup:" << std::endl;
4465 infostream << "\tRemaining meshes : "
4466 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4467 infostream << "\tRemaining textures : "
4468 << driver->getTextureCount() << std::endl;
4470 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4471 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4472 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4476 clearTextureNameCache();
4477 infostream << "\tRemaining materials: "
4478 << driver-> getMaterialRendererCount()
4479 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4483 /****************************************************************************/
4484 /****************************************************************************
4485 extern function for launching the game
4486 ****************************************************************************/
4487 /****************************************************************************/
4489 void the_game(bool *kill,
4491 InputHandler *input,
4492 IrrlichtDevice *device,
4494 const std::string &map_dir,
4495 const std::string &playername,
4496 const std::string &password,
4497 const std::string &address, // If empty local server is created
4500 std::string &error_message,
4501 ChatBackend &chat_backend,
4502 bool *reconnect_requested,
4503 const SubgameSpec &gamespec, // Used for local game
4504 bool simple_singleplayer_mode)
4508 /* Make a copy of the server address because if a local singleplayer server
4509 * is created then this is updated and we don't want to change the value
4510 * passed to us by the calling function
4512 std::string server_address = address;
4516 if (game.startup(kill, random_input, input, device, map_dir,
4517 playername, password, &server_address, port, error_message,
4518 reconnect_requested, &chat_backend, gamespec,
4519 simple_singleplayer_mode)) {
4524 } catch (SerializationError &e) {
4525 error_message = std::string("A serialization error occurred:\n")
4526 + e.what() + "\n\nThe server is probably "
4527 " running a different version of " PROJECT_NAME_C ".";
4528 errorstream << error_message << std::endl;
4529 } catch (ServerError &e) {
4530 error_message = e.what();
4531 errorstream << "ServerError: " << error_message << std::endl;
4532 } catch (ModError &e) {
4533 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4534 errorstream << "ModError: " << error_message << std::endl;