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());
277 Find what the player is pointing at
279 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
280 const v3f &camera_direction, const v3f &camera_position,
281 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
282 bool look_for_object, const v3s16 &camera_offset,
283 ClientActiveObject *&selected_object)
287 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
288 selectionboxes->clear();
289 selected_object = NULL;
291 INodeDefManager *nodedef = client->getNodeDefManager();
292 ClientMap &map = client->getEnv().getClientMap();
294 f32 min_distance = BS * 1001;
296 // First try to find a pointed at active object
297 if (look_for_object) {
298 selected_object = client->getSelectedActiveObject(d * BS,
299 camera_position, shootline);
301 if (selected_object != NULL) {
302 if (selected_object->doShowSelectionBox()) {
303 aabb3f *selection_box = selected_object->getSelectionBox();
304 // Box should exist because object was
305 // returned in the first place
306 assert(selection_box);
308 v3f pos = selected_object->getPosition();
309 selectionboxes->push_back(aabb3f(
310 selection_box->MinEdge, selection_box->MaxEdge));
311 hud->setSelectionPos(pos, camera_offset);
314 min_distance = (selected_object->getPosition() - camera_position).getLength();
316 result.type = POINTEDTHING_OBJECT;
317 result.object_id = selected_object->getId();
321 // That didn't work, try to find a pointed at node
323 v3s16 pos_i = floatToInt(player_position, BS);
325 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
329 s16 ystart = pos_i.Y - (camera_direction.Y < 0 ? a : 1);
330 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
331 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
332 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
333 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
334 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
336 // Prevent signed number overflow
346 v3s16 pointed_pos(0, 0, 0);
348 for (s16 y = ystart; y <= yend; y++) {
349 for (s16 z = zstart; z <= zend; z++) {
350 for (s16 x = xstart; x <= xend; x++) {
352 bool is_valid_position;
354 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
355 if (!is_valid_position) {
358 if (!isPointableNode(n, client, liquids_pointable)) {
361 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
364 v3f npf = intToFloat(np, BS);
365 for (std::vector<aabb3f>::const_iterator
367 i != boxes.end(); ++i) {
372 v3f centerpoint = box.getCenter();
373 f32 distance = (centerpoint - camera_position).getLength();
374 if (distance >= min_distance) {
377 if (!box.intersectsWithLine(shootline)) {
380 result.type = POINTEDTHING_NODE;
381 min_distance = distance;
388 if (result.type == POINTEDTHING_NODE) {
390 MapNode n = map.getNodeNoEx(pointed_pos);
391 v3f npf = intToFloat(pointed_pos, BS);
392 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
393 f32 face_min_distance = 1000 * BS;
394 for (std::vector<aabb3f>::const_iterator
396 i != boxes.end(); ++i) {
400 for (u16 j = 0; j < 6; j++) {
401 v3s16 facedir = g_6dirs[j];
402 aabb3f facebox = box;
404 facebox.MinEdge.X = facebox.MaxEdge.X - d;
405 } else if (facedir.X < 0) {
406 facebox.MaxEdge.X = facebox.MinEdge.X + d;
407 } else if (facedir.Y > 0) {
408 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
409 } else if (facedir.Y < 0) {
410 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
411 } else if (facedir.Z > 0) {
412 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
413 } else if (facedir.Z < 0) {
414 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
416 v3f centerpoint = facebox.getCenter();
417 f32 distance = (centerpoint - camera_position).getLength();
418 if (distance >= face_min_distance)
420 if (!facebox.intersectsWithLine(shootline))
422 result.node_abovesurface = pointed_pos + facedir;
423 face_min_distance = distance;
426 selectionboxes->clear();
427 for (std::vector<aabb3f>::const_iterator
429 i != boxes.end(); ++i) {
431 box.MinEdge += v3f(-d, -d, -d);
432 box.MaxEdge += v3f(d, d, d);
433 selectionboxes->push_back(box);
435 hud->setSelectionPos(intToFloat(pointed_pos, BS), camera_offset);
436 result.node_undersurface = pointed_pos;
439 // Update selection mesh light level and vertex colors
440 if (selectionboxes->size() > 0) {
441 v3f pf = hud->getSelectionPos();
442 v3s16 p = floatToInt(pf, BS);
444 // Get selection mesh light level
445 MapNode n = map.getNodeNoEx(p);
446 u16 node_light = getInteriorLight(n, -1, nodedef);
447 u16 light_level = node_light;
449 for (u8 i = 0; i < 6; i++) {
450 n = map.getNodeNoEx(p + g_6dirs[i]);
451 node_light = getInteriorLight(n, -1, nodedef);
452 if (node_light > light_level)
453 light_level = node_light;
456 video::SColor c = MapBlock_LightColor(255, light_level, 0);
458 u8 night = c.getGreen();
459 u32 daynight_ratio = client->getEnv().getDayNightRatio();
460 finalColorBlend(c, day, night, daynight_ratio);
462 // Modify final color a bit with time
463 u32 timer = porting::getTimeMs() % 5000;
464 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
465 float sin_r = 0.08 * sin(timerf);
466 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
467 float sin_b = 0.08 * sin(timerf + irr::core::PI);
468 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
469 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
470 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
472 // Set mesh final color
473 hud->setSelectionMeshColor(c);
478 /* Profiler display */
480 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
481 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
483 if (show_profiler == 0) {
484 guitext_profiler->setVisible(false);
487 std::ostringstream os(std::ios_base::binary);
488 g_profiler->printPage(os, show_profiler, show_profiler_max);
489 std::wstring text = utf8_to_wide(os.str());
490 guitext_profiler->setText(text.c_str());
491 guitext_profiler->setVisible(true);
493 s32 w = fe->getTextWidth(text.c_str());
498 unsigned text_height = fe->getTextHeight();
500 core::position2di upper_left, lower_right;
503 upper_left.Y = (text_height + 5) * 2;
504 lower_right.X = 12 + w;
505 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
507 if (lower_right.Y > screen_height * 2 / 3)
508 lower_right.Y = screen_height * 2 / 3;
510 core::rect<s32> rect(upper_left, lower_right);
512 guitext_profiler->setRelativePosition(rect);
513 guitext_profiler->setVisible(true);
521 Profiler::GraphValues values;
527 Meta(float initial = 0,
528 video::SColor color = video::SColor(255, 255, 255, 255)):
534 std::deque<Piece> m_log;
542 void put(const Profiler::GraphValues &values)
545 piece.values = values;
546 m_log.push_back(piece);
548 while (m_log.size() > m_log_max_size)
549 m_log.erase(m_log.begin());
552 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
553 gui::IGUIFont *font) const
555 std::map<std::string, Meta> m_meta;
557 for (std::deque<Piece>::const_iterator k = m_log.begin();
558 k != m_log.end(); ++k) {
559 const Piece &piece = *k;
561 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
562 i != piece.values.end(); ++i) {
563 const std::string &id = i->first;
564 const float &value = i->second;
565 std::map<std::string, Meta>::iterator j =
568 if (j == m_meta.end()) {
569 m_meta[id] = Meta(value);
573 if (value < j->second.min)
574 j->second.min = value;
576 if (value > j->second.max)
577 j->second.max = value;
582 static const video::SColor usable_colors[] = {
583 video::SColor(255, 255, 100, 100),
584 video::SColor(255, 90, 225, 90),
585 video::SColor(255, 100, 100, 255),
586 video::SColor(255, 255, 150, 50),
587 video::SColor(255, 220, 220, 100)
589 static const u32 usable_colors_count =
590 sizeof(usable_colors) / sizeof(*usable_colors);
591 u32 next_color_i = 0;
593 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
594 i != m_meta.end(); ++i) {
595 Meta &meta = i->second;
596 video::SColor color(255, 200, 200, 200);
598 if (next_color_i < usable_colors_count)
599 color = usable_colors[next_color_i++];
605 s32 textx = x_left + m_log_max_size + 15;
606 s32 textx2 = textx + 200 - 15;
609 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
610 i != m_meta.end(); ++i) {
611 const std::string &id = i->first;
612 const Meta &meta = i->second;
614 s32 y = y_bottom - meta_i * 50;
615 float show_min = meta.min;
616 float show_max = meta.max;
618 if (show_min >= -0.0001 && show_max >= -0.0001) {
619 if (show_min <= show_max * 0.5)
625 snprintf(buf, 10, "%.3g", show_max);
626 font->draw(utf8_to_wide(buf).c_str(),
627 core::rect<s32>(textx, y - graphh,
628 textx2, y - graphh + texth),
630 snprintf(buf, 10, "%.3g", show_min);
631 font->draw(utf8_to_wide(buf).c_str(),
632 core::rect<s32>(textx, y - texth,
635 font->draw(utf8_to_wide(id).c_str(),
636 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
637 textx2, y - graphh / 2 + texth / 2),
640 s32 graph1h = graphh;
641 bool relativegraph = (show_min != 0 && show_min != show_max);
642 float lastscaledvalue = 0.0;
643 bool lastscaledvalue_exists = false;
645 for (std::deque<Piece>::const_iterator j = m_log.begin();
646 j != m_log.end(); ++j) {
647 const Piece &piece = *j;
649 bool value_exists = false;
650 Profiler::GraphValues::const_iterator k =
651 piece.values.find(id);
653 if (k != piece.values.end()) {
660 lastscaledvalue_exists = false;
664 float scaledvalue = 1.0;
666 if (show_max != show_min)
667 scaledvalue = (value - show_min) / (show_max - show_min);
669 if (scaledvalue == 1.0 && value == 0) {
671 lastscaledvalue_exists = false;
676 if (lastscaledvalue_exists) {
677 s32 ivalue1 = lastscaledvalue * graph1h;
678 s32 ivalue2 = scaledvalue * graph1h;
679 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
680 v2s32(x, graph1y - ivalue2), meta.color);
683 lastscaledvalue = scaledvalue;
684 lastscaledvalue_exists = true;
686 s32 ivalue = scaledvalue * graph1h;
687 driver->draw2DLine(v2s32(x, graph1y),
688 v2s32(x, graph1y - ivalue), meta.color);
699 class NodeDugEvent: public MtEvent
705 NodeDugEvent(v3s16 p, MapNode n):
709 const char *getType() const
717 ISoundManager *m_sound;
718 INodeDefManager *m_ndef;
720 float m_player_step_timer;
722 SimpleSoundSpec m_player_step_sound;
723 SimpleSoundSpec m_player_leftpunch_sound;
724 SimpleSoundSpec m_player_rightpunch_sound;
726 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
729 m_player_step_timer(0)
733 void playPlayerStep()
735 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
736 m_player_step_timer = 0.03;
737 m_sound->playSound(m_player_step_sound, false);
741 static void viewBobbingStep(MtEvent *e, void *data)
743 SoundMaker *sm = (SoundMaker *)data;
744 sm->playPlayerStep();
747 static void playerRegainGround(MtEvent *e, void *data)
749 SoundMaker *sm = (SoundMaker *)data;
750 sm->playPlayerStep();
753 static void playerJump(MtEvent *e, void *data)
755 //SoundMaker *sm = (SoundMaker*)data;
758 static void cameraPunchLeft(MtEvent *e, void *data)
760 SoundMaker *sm = (SoundMaker *)data;
761 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
764 static void cameraPunchRight(MtEvent *e, void *data)
766 SoundMaker *sm = (SoundMaker *)data;
767 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
770 static void nodeDug(MtEvent *e, void *data)
772 SoundMaker *sm = (SoundMaker *)data;
773 NodeDugEvent *nde = (NodeDugEvent *)e;
774 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
777 static void playerDamage(MtEvent *e, void *data)
779 SoundMaker *sm = (SoundMaker *)data;
780 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
783 static void playerFallingDamage(MtEvent *e, void *data)
785 SoundMaker *sm = (SoundMaker *)data;
786 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
789 void registerReceiver(MtEventManager *mgr)
791 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
792 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
793 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
794 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
795 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
796 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
797 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
798 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
801 void step(float dtime)
803 m_player_step_timer -= dtime;
807 // Locally stored sounds don't need to be preloaded because of this
808 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
810 std::set<std::string> m_fetched;
812 void fetchSounds(const std::string &name,
813 std::set<std::string> &dst_paths,
814 std::set<std::string> &dst_datas)
816 if (m_fetched.count(name))
819 m_fetched.insert(name);
820 std::string base = porting::path_share + DIR_DELIM + "testsounds";
821 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
822 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
823 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
824 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
825 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
826 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
827 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
828 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
829 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
830 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
831 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
835 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
838 bool *m_force_fog_off;
844 void onSettingsChange(const std::string &name)
846 if (name == "enable_fog")
847 m_fogEnabled = g_settings->getBool("enable_fog");
850 static void SettingsCallback(const std::string &name, void *userdata)
852 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
855 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
856 f32 *fog_range, Client *client) :
858 m_force_fog_off(force_fog_off),
859 m_fog_range(fog_range),
862 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
863 m_fogEnabled = g_settings->getBool("enable_fog");
866 ~GameGlobalShaderConstantSetter()
868 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
871 virtual void onSetConstants(video::IMaterialRendererServices *services,
878 video::SColor bgcolor = m_sky->getBgColor();
879 video::SColorf bgcolorf(bgcolor);
880 float bgcolorfa[4] = {
886 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
889 float fog_distance = 10000 * BS;
891 if (m_fogEnabled && !*m_force_fog_off)
892 fog_distance = *m_fog_range;
894 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
897 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
898 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
899 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
901 u32 animation_timer = porting::getTimeMs() % 100000;
902 float animation_timer_f = (float)animation_timer / 100000.0;
903 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
904 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
906 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
907 v3f eye_position = player->getEyePosition();
908 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
909 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
911 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
912 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
914 // Uniform sampler layers
915 // before 1.8 there isn't a "integer interface", only float
916 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
920 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
921 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
922 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
927 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
928 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
929 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
934 bool nodePlacementPrediction(Client &client,
935 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
937 std::string prediction = playeritem_def.node_placement_prediction;
938 INodeDefManager *nodedef = client.ndef();
939 ClientMap &map = client.getEnv().getClientMap();
941 bool is_valid_position;
943 node = map.getNodeNoEx(nodepos, &is_valid_position);
944 if (!is_valid_position)
947 if (prediction != "" && !nodedef->get(node).rightclickable) {
948 verbosestream << "Node placement prediction for "
949 << playeritem_def.name << " is "
950 << prediction << std::endl;
951 v3s16 p = neighbourpos;
953 // Place inside node itself if buildable_to
954 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
955 if (is_valid_position)
957 if (nodedef->get(n_under).buildable_to)
960 node = map.getNodeNoEx(p, &is_valid_position);
961 if (is_valid_position &&!nodedef->get(node).buildable_to)
966 // Find id of predicted node
968 bool found = nodedef->getId(prediction, id);
971 errorstream << "Node placement prediction failed for "
972 << playeritem_def.name << " (places "
974 << ") - Name not known" << std::endl;
978 // Predict param2 for facedir and wallmounted nodes
981 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
982 v3s16 dir = nodepos - neighbourpos;
984 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
985 param2 = dir.Y < 0 ? 1 : 0;
986 } else if (abs(dir.X) > abs(dir.Z)) {
987 param2 = dir.X < 0 ? 3 : 2;
989 param2 = dir.Z < 0 ? 5 : 4;
993 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
994 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
996 if (abs(dir.X) > abs(dir.Z)) {
997 param2 = dir.X < 0 ? 3 : 1;
999 param2 = dir.Z < 0 ? 2 : 0;
1003 assert(param2 <= 5);
1005 //Check attachment if node is in group attached_node
1006 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
1007 static v3s16 wallmounted_dirs[8] = {
1017 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1018 pp = p + wallmounted_dirs[param2];
1020 pp = p + v3s16(0, -1, 0);
1022 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1026 // Add node to client map
1027 MapNode n(id, 0, param2);
1030 LocalPlayer *player = client.getEnv().getLocalPlayer();
1032 // Dont place node when player would be inside new node
1033 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1034 if (!nodedef->get(n).walkable ||
1035 g_settings->getBool("enable_build_where_you_stand") ||
1036 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1037 (nodedef->get(n).walkable &&
1038 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1039 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1041 // This triggers the required mesh update too
1042 client.addNode(p, n);
1045 } catch (InvalidPositionException &e) {
1046 errorstream << "Node placement prediction failed for "
1047 << playeritem_def.name << " (places "
1049 << ") - Position not loaded" << std::endl;
1056 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1057 InventoryManager *invmgr, IGameDef *gamedef,
1058 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1059 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1062 if (*cur_formspec == 0) {
1063 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1064 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1065 (*cur_formspec)->doPause = false;
1068 Caution: do not call (*cur_formspec)->drop() here --
1069 the reference might outlive the menu, so we will
1070 periodically check if *cur_formspec is the only
1071 remaining reference (i.e. the menu was removed)
1072 and delete it in that case.
1076 (*cur_formspec)->setFormSource(fs_src);
1077 (*cur_formspec)->setTextDest(txt_dest);
1082 #define SIZE_TAG "size[11,5.5]"
1084 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1087 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1088 InventoryManager *invmgr, IGameDef *gamedef,
1089 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1091 std::string formspec =
1092 std::string(FORMSPEC_VERSION_STRING) +
1094 "bgcolor[#320000b4;true]"
1095 "label[4.85,1.35;" + gettext("You died.") + "]"
1096 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1100 /* Note: FormspecFormSource and LocalFormspecHandler
1101 * are deleted by guiFormSpecMenu */
1102 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1103 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1105 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1108 /******************************************************************************/
1109 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1110 InventoryManager *invmgr, IGameDef *gamedef,
1111 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1112 bool singleplayermode)
1115 std::string control_text = strgettext("Default Controls:\n"
1116 "No menu visible:\n"
1117 "- single tap: button activate\n"
1118 "- double tap: place/use\n"
1119 "- slide finger: look around\n"
1120 "Menu/Inventory visible:\n"
1121 "- double tap (outside):\n"
1123 "- touch stack, touch slot:\n"
1125 "- touch&drag, tap 2nd finger\n"
1126 " --> place single item to slot\n"
1129 std::string control_text = strgettext("Default Controls:\n"
1131 "- Space: jump/climb\n"
1132 "- Shift: sneak/go down\n"
1135 "- Mouse: turn/look\n"
1136 "- Mouse left: dig/punch\n"
1137 "- Mouse right: place/use\n"
1138 "- Mouse wheel: select item\n"
1143 float ypos = singleplayermode ? 0.5 : 0.1;
1144 std::ostringstream os;
1146 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1147 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1148 << strgettext("Continue") << "]";
1150 if (!singleplayermode) {
1151 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1152 << strgettext("Change Password") << "]";
1156 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1157 << strgettext("Sound Volume") << "]";
1158 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1159 << strgettext("Change Keys") << "]";
1161 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1162 << strgettext("Exit to Menu") << "]";
1163 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1164 << strgettext("Exit to OS") << "]"
1165 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1166 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1167 << g_build_info << "\n"
1168 << "path_user = " << wrap_rows(porting::path_user, 20)
1172 /* Note: FormspecFormSource and LocalFormspecHandler *
1173 * are deleted by guiFormSpecMenu */
1174 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1175 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1177 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1178 std::string con("btn_continue");
1179 (*cur_formspec)->setFocus(con);
1180 (*cur_formspec)->doPause = true;
1183 /******************************************************************************/
1184 static void updateChat(Client &client, f32 dtime, bool show_debug,
1185 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1186 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1188 // Add chat log output for errors to be shown in chat
1189 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1191 // Get new messages from error log buffer
1192 while (!chat_log_error_buf.empty()) {
1193 chat_backend.addMessage(L"", utf8_to_wide(chat_log_error_buf.get()));
1196 // Get new messages from client
1197 std::wstring message;
1199 while (client.getChatMessage(message)) {
1200 chat_backend.addUnparsedMessage(message);
1203 // Remove old messages
1204 chat_backend.step(dtime);
1206 // Display all messages in a static text element
1207 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1208 std::wstring recent_chat = chat_backend.getRecentChat();
1209 unsigned int line_height = g_fontengine->getLineHeight();
1211 guitext_chat->setText(recent_chat.c_str());
1213 // Update gui element size and position
1214 s32 chat_y = 5 + line_height;
1217 chat_y += line_height;
1219 // first pass to calculate height of text to be set
1220 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1221 porting::getWindowSize().X - 20);
1222 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1223 guitext_chat->setRelativePosition(rect);
1225 //now use real height of text and adjust rect according to this size
1226 rect = core::rect<s32>(10, chat_y, width,
1227 chat_y + guitext_chat->getTextHeight());
1230 guitext_chat->setRelativePosition(rect);
1231 // Don't show chat if disabled or empty or profiler is enabled
1232 guitext_chat->setVisible(
1233 show_chat && recent_chat_count != 0 && !show_profiler);
1237 /****************************************************************************
1238 Fast key cache for main game loop
1239 ****************************************************************************/
1241 /* This is faster than using getKeySetting with the tradeoff that functions
1242 * using it must make sure that it's initialised before using it and there is
1243 * no error handling (for example bounds checking). This is really intended for
1244 * use only in the main running loop of the client (the_game()) where the faster
1245 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1246 * (e.g. formspecs) should continue using getKeySetting().
1250 KeyCache() { populate(); }
1265 KEYMAP_ID_INVENTORY,
1273 KEYMAP_ID_CINEMATIC,
1274 KEYMAP_ID_SCREENSHOT,
1275 KEYMAP_ID_TOGGLE_HUD,
1276 KEYMAP_ID_TOGGLE_CHAT,
1277 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1278 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1279 KEYMAP_ID_TOGGLE_DEBUG,
1280 KEYMAP_ID_TOGGLE_PROFILER,
1281 KEYMAP_ID_CAMERA_MODE,
1282 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1283 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1284 KEYMAP_ID_RANGESELECT,
1286 KEYMAP_ID_QUICKTUNE_NEXT,
1287 KEYMAP_ID_QUICKTUNE_PREV,
1288 KEYMAP_ID_QUICKTUNE_INC,
1289 KEYMAP_ID_QUICKTUNE_DEC,
1291 KEYMAP_ID_DEBUG_STACKS,
1293 // Fake keycode for array size and internal checks
1294 KEYMAP_INTERNAL_ENUM_COUNT
1301 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1304 void KeyCache::populate()
1306 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1307 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1308 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1309 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1310 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1311 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1312 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1314 key[KEYMAP_ID_AUTORUN] = getKeySetting("keymap_autorun");
1316 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1317 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1318 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1319 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1320 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1321 key[KEYMAP_ID_MINIMAP] = getKeySetting("keymap_minimap");
1322 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1323 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1324 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1325 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1326 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1327 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1328 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1329 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1330 = getKeySetting("keymap_toggle_force_fog_off");
1331 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1332 = getKeySetting("keymap_toggle_update_camera");
1333 key[KEYMAP_ID_TOGGLE_DEBUG]
1334 = getKeySetting("keymap_toggle_debug");
1335 key[KEYMAP_ID_TOGGLE_PROFILER]
1336 = getKeySetting("keymap_toggle_profiler");
1337 key[KEYMAP_ID_CAMERA_MODE]
1338 = getKeySetting("keymap_camera_mode");
1339 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1340 = getKeySetting("keymap_increase_viewing_range_min");
1341 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1342 = getKeySetting("keymap_decrease_viewing_range_min");
1343 key[KEYMAP_ID_RANGESELECT]
1344 = getKeySetting("keymap_rangeselect");
1346 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1347 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1348 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1349 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1351 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1355 /****************************************************************************
1357 ****************************************************************************/
1359 const float object_hit_delay = 0.2;
1362 u32 last_time, busy_time, sleep_time;
1366 /* The reason the following structs are not anonymous structs within the
1367 * class is that they are not used by the majority of member functions and
1368 * many functions that do require objects of thse types do not modify them
1369 * (so they can be passed as a const qualified parameter)
1371 struct CameraOrientation {
1372 f32 camera_yaw; // "right/left"
1373 f32 camera_pitch; // "up/down"
1376 struct GameRunData {
1379 PointedThing pointed_old;
1383 bool update_wielded_item_trigger;
1384 bool reset_jump_timer;
1385 float nodig_delay_timer;
1387 float dig_time_complete;
1388 float repeat_rightclick_timer;
1389 float object_hit_delay_timer;
1390 float time_from_last_punch;
1391 ClientActiveObject *selected_object;
1395 float update_draw_list_timer;
1396 float statustext_time;
1400 v3f update_draw_list_last_cam_dir;
1402 u32 profiler_current_page;
1403 u32 profiler_max_page; // Number of pages
1406 float time_of_day_smooth;
1410 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1418 Jitter dtime_jitter, busy_time_jitter;
1421 /* Flags that can, or may, change during main game loop
1423 struct VolatileRunFlags {
1430 bool show_profiler_graph;
1431 bool disable_camera_update;
1432 bool first_loop_after_window_activation;
1433 bool camera_offset_changed;
1437 /****************************************************************************
1439 ****************************************************************************/
1441 /* This is not intended to be a public class. If a public class becomes
1442 * desirable then it may be better to create another 'wrapper' class that
1443 * hides most of the stuff in this class (nothing in this class is required
1444 * by any other file) but exposes the public methods/data only.
1451 bool startup(bool *kill,
1453 InputHandler *input,
1454 IrrlichtDevice *device,
1455 const std::string &map_dir,
1456 const std::string &playername,
1457 const std::string &password,
1458 // If address is "", local server is used and address is updated
1459 std::string *address,
1461 std::string &error_message,
1463 ChatBackend *chat_backend,
1464 const SubgameSpec &gamespec, // Used for local game
1465 bool simple_singleplayer_mode);
1472 void extendedResourceCleanup();
1474 // Basic initialisation
1475 bool init(const std::string &map_dir, std::string *address,
1477 const SubgameSpec &gamespec);
1479 bool createSingleplayerServer(const std::string map_dir,
1480 const SubgameSpec &gamespec, u16 port, std::string *address);
1483 bool createClient(const std::string &playername,
1484 const std::string &password, std::string *address, u16 port);
1487 // Client connection
1488 bool connectToServer(const std::string &playername,
1489 const std::string &password, std::string *address, u16 port,
1490 bool *connect_ok, bool *aborted);
1491 bool getServerContent(bool *aborted);
1495 void updateInteractTimers(GameRunData *runData, f32 dtime);
1496 bool checkConnection();
1497 bool handleCallbacks();
1498 void processQueues();
1499 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1500 const FpsControl &draw_times, f32 dtime);
1501 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1503 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1505 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1507 void processKeyboardInput(VolatileRunFlags *flags,
1508 float *statustext_time,
1510 bool *reset_jump_timer,
1511 u32 *profiler_current_page,
1512 u32 profiler_max_page);
1513 void processItemSelection(u16 *new_playeritem);
1515 void dropSelectedItem();
1516 void openInventory();
1517 void openConsole(float height, const wchar_t *line=NULL);
1518 void toggleFreeMove(float *statustext_time);
1519 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1520 void toggleFast(float *statustext_time);
1521 void toggleNoClip(float *statustext_time);
1522 void toggleCinematic(float *statustext_time);
1523 void toggleAutorun(float *statustext_time);
1525 void toggleChat(float *statustext_time, bool *flag);
1526 void toggleHud(float *statustext_time, bool *flag);
1527 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1528 bool shift_pressed);
1529 void toggleFog(float *statustext_time, bool *flag);
1530 void toggleDebug(float *statustext_time, bool *show_debug,
1531 bool *show_profiler_graph);
1532 void toggleUpdateCamera(float *statustext_time, bool *flag);
1533 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1534 u32 profiler_max_page);
1536 void increaseViewRange(float *statustext_time);
1537 void decreaseViewRange(float *statustext_time);
1538 void toggleFullViewRange(float *statustext_time);
1540 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1541 void updateCameraOrientation(CameraOrientation *cam,
1542 const VolatileRunFlags &flags);
1543 void updatePlayerControl(const CameraOrientation &cam);
1544 void step(f32 *dtime);
1545 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1546 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1547 float time_from_last_punch);
1548 void updateSound(f32 dtime);
1549 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1551 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1552 void handlePointingAtNode(GameRunData *runData,
1553 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1554 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1555 void handlePointingAtObject(GameRunData *runData,
1556 const PointedThing &pointed, const ItemStack &playeritem,
1557 const v3f &player_position, bool show_debug);
1558 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1559 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1561 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1562 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1563 void updateGui(float *statustext_time, const RunStats &stats,
1564 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1565 const CameraOrientation &cam);
1566 void updateProfilerGraphs(ProfilerGraph *graph);
1569 void limitFps(FpsControl *fps_timings, f32 *dtime);
1571 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1572 bool draw_clouds = true);
1574 static void settingChangedCallback(const std::string &setting_name, void *data);
1575 void readSettings();
1578 InputHandler *input;
1583 IWritableTextureSource *texture_src;
1584 IWritableShaderSource *shader_src;
1586 // When created, these will be filled with data received from the server
1587 IWritableItemDefManager *itemdef_manager;
1588 IWritableNodeDefManager *nodedef_manager;
1590 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1591 ISoundManager *sound;
1592 bool sound_is_dummy;
1593 SoundMaker *soundmaker;
1595 ChatBackend *chat_backend;
1597 GUIFormSpecMenu *current_formspec;
1599 EventManager *eventmgr;
1600 QuicktuneShortcutter *quicktune;
1602 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1603 MapDrawControl *draw_control;
1605 Clouds *clouds; // Free using ->Drop()
1606 Sky *sky; // Free using ->Drop()
1607 Inventory *local_inventory;
1612 This class does take ownership/responsibily for cleaning up etc of any of
1613 these items (e.g. device)
1615 IrrlichtDevice *device;
1616 video::IVideoDriver *driver;
1617 scene::ISceneManager *smgr;
1619 std::string *error_message;
1620 bool *reconnect_requested;
1621 IGameDef *gamedef; // Convenience (same as *client)
1622 scene::ISceneNode *skybox;
1625 bool simple_singleplayer_mode;
1628 /* Pre-calculated values
1630 int crack_animation_length;
1634 gui::IGUIStaticText *guitext; // First line of debug text
1635 gui::IGUIStaticText *guitext2; // Second line of debug text
1636 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1637 gui::IGUIStaticText *guitext_status;
1638 gui::IGUIStaticText *guitext_chat; // Chat text
1639 gui::IGUIStaticText *guitext_profiler; // Profiler text
1641 std::wstring infotext;
1642 std::wstring statustext;
1646 IntervalLimiter profiler_interval;
1649 * TODO: Local caching of settings is not optimal and should at some stage
1650 * be updated to use a global settings object for getting thse values
1651 * (as opposed to the this local caching). This can be addressed in
1654 bool m_cache_doubletap_jump;
1655 bool m_cache_enable_clouds;
1656 bool m_cache_enable_particles;
1657 bool m_cache_enable_fog;
1658 f32 m_cache_mouse_sensitivity;
1659 f32 m_repeat_right_click_time;
1662 bool m_cache_hold_aux1;
1672 itemdef_manager(NULL),
1673 nodedef_manager(NULL),
1675 sound_is_dummy(false),
1678 current_formspec(NULL),
1681 gui_chat_console(NULL),
1686 local_inventory(NULL),
1690 g_settings->registerChangedCallback("doubletap_jump",
1691 &settingChangedCallback, this);
1692 g_settings->registerChangedCallback("enable_clouds",
1693 &settingChangedCallback, this);
1694 g_settings->registerChangedCallback("enable_particles",
1695 &settingChangedCallback, this);
1696 g_settings->registerChangedCallback("enable_fog",
1697 &settingChangedCallback, this);
1698 g_settings->registerChangedCallback("mouse_sensitivity",
1699 &settingChangedCallback, this);
1700 g_settings->registerChangedCallback("repeat_rightclick_time",
1701 &settingChangedCallback, this);
1706 m_cache_hold_aux1 = false; // This is initialised properly later
1713 /****************************************************************************
1715 ****************************************************************************/
1721 if (!sound_is_dummy)
1724 delete server; // deleted first to stop all server threads
1727 delete local_inventory;
1733 delete nodedef_manager;
1734 delete itemdef_manager;
1735 delete draw_control;
1737 extendedResourceCleanup();
1739 g_settings->deregisterChangedCallback("doubletap_jump",
1740 &settingChangedCallback, this);
1741 g_settings->deregisterChangedCallback("enable_clouds",
1742 &settingChangedCallback, this);
1743 g_settings->deregisterChangedCallback("enable_particles",
1744 &settingChangedCallback, this);
1745 g_settings->deregisterChangedCallback("enable_fog",
1746 &settingChangedCallback, this);
1747 g_settings->deregisterChangedCallback("mouse_sensitivity",
1748 &settingChangedCallback, this);
1749 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1750 &settingChangedCallback, this);
1753 bool Game::startup(bool *kill,
1755 InputHandler *input,
1756 IrrlichtDevice *device,
1757 const std::string &map_dir,
1758 const std::string &playername,
1759 const std::string &password,
1760 std::string *address, // can change if simple_singleplayer_mode
1762 std::string &error_message,
1764 ChatBackend *chat_backend,
1765 const SubgameSpec &gamespec,
1766 bool simple_singleplayer_mode)
1769 this->device = device;
1771 this->error_message = &error_message;
1772 this->reconnect_requested = reconnect;
1773 this->random_input = random_input;
1774 this->input = input;
1775 this->chat_backend = chat_backend;
1776 this->simple_singleplayer_mode = simple_singleplayer_mode;
1778 driver = device->getVideoDriver();
1779 smgr = device->getSceneManager();
1781 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1783 if (!init(map_dir, address, port, gamespec))
1786 if (!createClient(playername, password, address, port))
1795 ProfilerGraph graph;
1796 RunStats stats = { 0 };
1797 CameraOrientation cam_view_target = { 0 };
1798 CameraOrientation cam_view = { 0 };
1799 GameRunData runData = { 0 };
1800 FpsControl draw_times = { 0 };
1801 VolatileRunFlags flags = { 0 };
1802 f32 dtime; // in seconds
1804 runData.time_from_last_punch = 10.0;
1805 runData.profiler_max_page = 3;
1806 runData.update_wielded_item_trigger = true;
1808 flags.show_chat = true;
1809 flags.show_hud = true;
1810 flags.show_minimap = g_settings->getBool("enable_minimap");
1811 flags.show_debug = g_settings->getBool("show_debug");
1812 flags.invert_mouse = g_settings->getBool("invert_mouse");
1813 flags.first_loop_after_window_activation = true;
1815 /* Clear the profiler */
1816 Profiler::GraphValues dummyvalues;
1817 g_profiler->graphGet(dummyvalues);
1819 draw_times.last_time = device->getTimer()->getTime();
1821 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1823 &flags.force_fog_off,
1827 set_light_table(g_settings->getFloat("display_gamma"));
1830 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1831 && client->checkPrivilege("fast");
1834 while (device->run()
1835 && !(*kill || g_gamecallback->shutdown_requested
1836 || (server && server->getShutdownRequested()))) {
1838 /* Must be called immediately after a device->run() call because it
1839 * uses device->getTimer()->getTime()
1841 limitFps(&draw_times, &dtime);
1843 updateStats(&stats, draw_times, dtime);
1844 updateInteractTimers(&runData, dtime);
1846 if (!checkConnection())
1848 if (!handleCallbacks())
1854 hud->resizeHotbar();
1856 updateProfilers(runData, stats, draw_times, dtime);
1857 processUserInput(&flags, &runData, dtime);
1858 // Update camera before player movement to avoid camera lag of one frame
1859 updateCameraDirection(&cam_view_target, &flags);
1860 float cam_smoothing = 0;
1861 if (g_settings->getBool("cinematic"))
1862 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1864 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1865 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1866 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1867 cam_view.camera_yaw) * cam_smoothing;
1868 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1869 cam_view.camera_pitch) * cam_smoothing;
1870 updatePlayerControl(cam_view);
1872 processClientEvents(&cam_view_target, &runData.damage_flash);
1873 updateCamera(&flags, draw_times.busy_time, dtime,
1874 runData.time_from_last_punch);
1876 processPlayerInteraction(&runData, dtime, flags.show_hud,
1878 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1879 updateProfilerGraphs(&graph);
1881 // Update if minimap has been disabled by the server
1882 flags.show_minimap &= !client->isMinimapDisabledByServer();
1887 void Game::shutdown()
1889 if (g_settings->get("3d_mode") == "pageflip") {
1890 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1893 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1898 if (gui_chat_console)
1899 gui_chat_console->drop();
1905 while (g_menumgr.menuCount() > 0) {
1906 g_menumgr.m_stack.front()->setVisible(false);
1907 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1910 if (current_formspec) {
1911 current_formspec->drop();
1912 current_formspec = NULL;
1915 chat_backend->addMessage(L"", L"# Disconnected.");
1916 chat_backend->addMessage(L"", L"");
1920 while (!client->isShutdown()) {
1921 assert(texture_src != NULL);
1922 assert(shader_src != NULL);
1923 texture_src->processQueue();
1924 shader_src->processQueue();
1931 /****************************************************************************/
1932 /****************************************************************************
1934 ****************************************************************************/
1935 /****************************************************************************/
1938 const std::string &map_dir,
1939 std::string *address,
1941 const SubgameSpec &gamespec)
1943 showOverlayMessage(wgettext("Loading..."), 0, 0);
1945 texture_src = createTextureSource(device);
1946 shader_src = createShaderSource(device);
1948 itemdef_manager = createItemDefManager();
1949 nodedef_manager = createNodeDefManager();
1951 eventmgr = new EventManager();
1952 quicktune = new QuicktuneShortcutter();
1954 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1955 && eventmgr && quicktune))
1961 // Create a server if not connecting to an existing one
1962 if (*address == "") {
1963 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1970 bool Game::initSound()
1973 if (g_settings->getBool("enable_sound")) {
1974 infostream << "Attempting to use OpenAL audio" << std::endl;
1975 sound = createOpenALSoundManager(&soundfetcher);
1977 infostream << "Failed to initialize OpenAL audio" << std::endl;
1979 infostream << "Sound disabled." << std::endl;
1983 infostream << "Using dummy audio." << std::endl;
1984 sound = &dummySoundManager;
1985 sound_is_dummy = true;
1988 soundmaker = new SoundMaker(sound, nodedef_manager);
1992 soundmaker->registerReceiver(eventmgr);
1997 bool Game::createSingleplayerServer(const std::string map_dir,
1998 const SubgameSpec &gamespec, u16 port, std::string *address)
2000 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2002 std::string bind_str = g_settings->get("bind_address");
2003 Address bind_addr(0, 0, 0, 0, port);
2005 if (g_settings->getBool("ipv6_server")) {
2006 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2010 bind_addr.Resolve(bind_str.c_str());
2011 } catch (ResolveError &e) {
2012 infostream << "Resolving bind address \"" << bind_str
2013 << "\" failed: " << e.what()
2014 << " -- Listening on all addresses." << std::endl;
2017 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2018 *error_message = "Unable to listen on " +
2019 bind_addr.serializeString() +
2020 " because IPv6 is disabled";
2021 errorstream << *error_message << std::endl;
2025 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2026 bind_addr.isIPv6());
2028 server->start(bind_addr);
2033 bool Game::createClient(const std::string &playername,
2034 const std::string &password, std::string *address, u16 port)
2036 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2038 draw_control = new MapDrawControl;
2042 bool could_connect, connect_aborted;
2044 if (!connectToServer(playername, password, address, port,
2045 &could_connect, &connect_aborted))
2048 if (!could_connect) {
2049 if (error_message->empty() && !connect_aborted) {
2050 // Should not happen if error messages are set properly
2051 *error_message = "Connection failed for unknown reason";
2052 errorstream << *error_message << std::endl;
2057 if (!getServerContent(&connect_aborted)) {
2058 if (error_message->empty() && !connect_aborted) {
2059 // Should not happen if error messages are set properly
2060 *error_message = "Connection failed for unknown reason";
2061 errorstream << *error_message << std::endl;
2066 // Update cached textures, meshes and materials
2067 client->afterContentReceived(device);
2071 camera = new Camera(smgr, *draw_control, gamedef);
2072 if (!camera || !camera->successfullyCreated(*error_message))
2074 client->setCamera(camera);
2078 if (m_cache_enable_clouds) {
2079 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2081 *error_message = "Memory allocation error (clouds)";
2082 errorstream << *error_message << std::endl;
2089 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2090 skybox = NULL; // This is used/set later on in the main run loop
2092 local_inventory = new Inventory(itemdef_manager);
2094 if (!(sky && local_inventory)) {
2095 *error_message = "Memory allocation error (sky or local inventory)";
2096 errorstream << *error_message << std::endl;
2100 /* Pre-calculated values
2102 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2104 v2u32 size = t->getOriginalSize();
2105 crack_animation_length = size.Y / size.X;
2107 crack_animation_length = 5;
2113 /* Set window caption
2115 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2117 str += driver->getName();
2119 device->setWindowCaption(str.c_str());
2121 LocalPlayer *player = client->getEnv().getLocalPlayer();
2122 player->hurt_tilt_timer = 0;
2123 player->hurt_tilt_strength = 0;
2125 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2128 *error_message = "Memory error: could not create HUD";
2129 errorstream << *error_message << std::endl;
2133 mapper = client->getMapper();
2134 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2139 bool Game::initGui()
2141 // First line of debug text
2142 guitext = guienv->addStaticText(
2143 utf8_to_wide(PROJECT_NAME_C).c_str(),
2144 core::rect<s32>(0, 0, 0, 0),
2145 false, false, guiroot);
2147 // Second line of debug text
2148 guitext2 = guienv->addStaticText(
2150 core::rect<s32>(0, 0, 0, 0),
2151 false, false, guiroot);
2153 // At the middle of the screen
2154 // Object infos are shown in this
2155 guitext_info = guienv->addStaticText(
2157 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2158 false, true, guiroot);
2160 // Status text (displays info when showing and hiding GUI stuff, etc.)
2161 guitext_status = guienv->addStaticText(
2163 core::rect<s32>(0, 0, 0, 0),
2164 false, false, guiroot);
2165 guitext_status->setVisible(false);
2168 guitext_chat = guienv->addStaticText(
2170 core::rect<s32>(0, 0, 0, 0),
2171 //false, false); // Disable word wrap as of now
2172 false, true, guiroot);
2173 // Remove stale "recent" chat messages from previous connections
2174 chat_backend->clearRecentChat();
2176 // Chat backend and console
2177 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2178 -1, chat_backend, client);
2179 if (!gui_chat_console) {
2180 *error_message = "Could not allocate memory for chat console";
2181 errorstream << *error_message << std::endl;
2185 // Profiler text (size is updated when text is updated)
2186 guitext_profiler = guienv->addStaticText(
2188 core::rect<s32>(0, 0, 0, 0),
2189 false, false, guiroot);
2190 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2191 guitext_profiler->setVisible(false);
2192 guitext_profiler->setWordWrap(true);
2194 #ifdef HAVE_TOUCHSCREENGUI
2196 if (g_touchscreengui)
2197 g_touchscreengui->init(texture_src);
2204 bool Game::connectToServer(const std::string &playername,
2205 const std::string &password, std::string *address, u16 port,
2206 bool *connect_ok, bool *aborted)
2208 *connect_ok = false; // Let's not be overly optimistic
2210 bool local_server_mode = false;
2212 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2214 Address connect_address(0, 0, 0, 0, port);
2217 connect_address.Resolve(address->c_str());
2219 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2220 //connect_address.Resolve("localhost");
2221 if (connect_address.isIPv6()) {
2222 IPv6AddressBytes addr_bytes;
2223 addr_bytes.bytes[15] = 1;
2224 connect_address.setAddress(&addr_bytes);
2226 connect_address.setAddress(127, 0, 0, 1);
2228 local_server_mode = true;
2230 } catch (ResolveError &e) {
2231 *error_message = std::string("Couldn't resolve address: ") + e.what();
2232 errorstream << *error_message << std::endl;
2236 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2237 *error_message = "Unable to connect to " +
2238 connect_address.serializeString() +
2239 " because IPv6 is disabled";
2240 errorstream << *error_message << std::endl;
2244 client = new Client(device,
2245 playername.c_str(), password,
2246 *draw_control, texture_src, shader_src,
2247 itemdef_manager, nodedef_manager, sound, eventmgr,
2248 connect_address.isIPv6());
2253 gamedef = client; // Client acts as our GameDef
2255 infostream << "Connecting to server at ";
2256 connect_address.print(&infostream);
2257 infostream << std::endl;
2259 client->connect(connect_address, *address,
2260 simple_singleplayer_mode || local_server_mode);
2263 Wait for server to accept connection
2269 FpsControl fps_control = { 0 };
2271 f32 wait_time = 0; // in seconds
2273 fps_control.last_time = device->getTimer()->getTime();
2275 while (device->run()) {
2277 limitFps(&fps_control, &dtime);
2279 // Update client and server
2280 client->step(dtime);
2283 server->step(dtime);
2286 if (client->getState() == LC_Init) {
2292 if (client->accessDenied()) {
2293 *error_message = "Access denied. Reason: "
2294 + client->accessDeniedReason();
2295 *reconnect_requested = client->reconnectRequested();
2296 errorstream << *error_message << std::endl;
2300 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2302 infostream << "Connect aborted [Escape]" << std::endl;
2307 // Only time out if we aren't waiting for the server we started
2308 if ((*address != "") && (wait_time > 10)) {
2309 *error_message = "Connection timed out.";
2310 errorstream << *error_message << std::endl;
2315 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2317 } catch (con::PeerNotFoundException &e) {
2318 // TODO: Should something be done here? At least an info/error
2326 bool Game::getServerContent(bool *aborted)
2330 FpsControl fps_control = { 0 };
2331 f32 dtime; // in seconds
2333 fps_control.last_time = device->getTimer()->getTime();
2335 while (device->run()) {
2337 limitFps(&fps_control, &dtime);
2339 // Update client and server
2340 client->step(dtime);
2343 server->step(dtime);
2346 if (client->mediaReceived() && client->itemdefReceived() &&
2347 client->nodedefReceived()) {
2352 if (!checkConnection())
2355 if (client->getState() < LC_Init) {
2356 *error_message = "Client disconnected";
2357 errorstream << *error_message << std::endl;
2361 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2363 infostream << "Connect aborted [Escape]" << std::endl;
2370 if (!client->itemdefReceived()) {
2371 const wchar_t *text = wgettext("Item definitions...");
2373 draw_load_screen(text, device, guienv, dtime, progress);
2375 } else if (!client->nodedefReceived()) {
2376 const wchar_t *text = wgettext("Node definitions...");
2378 draw_load_screen(text, device, guienv, dtime, progress);
2381 std::stringstream message;
2382 message.precision(3);
2383 message << gettext("Media...");
2385 if ((USE_CURL == 0) ||
2386 (!g_settings->getBool("enable_remote_media_server"))) {
2387 float cur = client->getCurRate();
2388 std::string cur_unit = gettext("KiB/s");
2392 cur_unit = gettext("MiB/s");
2395 message << " (" << cur << ' ' << cur_unit << ")";
2398 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2399 draw_load_screen(utf8_to_wide(message.str()), device,
2400 guienv, dtime, progress);
2408 /****************************************************************************/
2409 /****************************************************************************
2411 ****************************************************************************/
2412 /****************************************************************************/
2414 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2416 if (runData->nodig_delay_timer >= 0)
2417 runData->nodig_delay_timer -= dtime;
2419 if (runData->object_hit_delay_timer >= 0)
2420 runData->object_hit_delay_timer -= dtime;
2422 runData->time_from_last_punch += dtime;
2426 /* returns false if game should exit, otherwise true
2428 inline bool Game::checkConnection()
2430 if (client->accessDenied()) {
2431 *error_message = "Access denied. Reason: "
2432 + client->accessDeniedReason();
2433 *reconnect_requested = client->reconnectRequested();
2434 errorstream << *error_message << std::endl;
2442 /* returns false if game should exit, otherwise true
2444 inline bool Game::handleCallbacks()
2446 if (g_gamecallback->disconnect_requested) {
2447 g_gamecallback->disconnect_requested = false;
2451 if (g_gamecallback->changepassword_requested) {
2452 (new GUIPasswordChange(guienv, guiroot, -1,
2453 &g_menumgr, client))->drop();
2454 g_gamecallback->changepassword_requested = false;
2457 if (g_gamecallback->changevolume_requested) {
2458 (new GUIVolumeChange(guienv, guiroot, -1,
2459 &g_menumgr, client))->drop();
2460 g_gamecallback->changevolume_requested = false;
2463 if (g_gamecallback->keyconfig_requested) {
2464 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2465 &g_menumgr))->drop();
2466 g_gamecallback->keyconfig_requested = false;
2469 if (g_gamecallback->keyconfig_changed) {
2470 keycache.populate(); // update the cache with new settings
2471 g_gamecallback->keyconfig_changed = false;
2478 void Game::processQueues()
2480 texture_src->processQueue();
2481 itemdef_manager->processQueue(gamedef);
2482 shader_src->processQueue();
2486 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2487 const FpsControl &draw_times, f32 dtime)
2489 float profiler_print_interval =
2490 g_settings->getFloat("profiler_print_interval");
2491 bool print_to_log = true;
2493 if (profiler_print_interval == 0) {
2494 print_to_log = false;
2495 profiler_print_interval = 5;
2498 if (profiler_interval.step(dtime, profiler_print_interval)) {
2500 infostream << "Profiler:" << std::endl;
2501 g_profiler->print(infostream);
2504 update_profiler_gui(guitext_profiler, g_fontengine,
2505 runData.profiler_current_page, runData.profiler_max_page,
2506 driver->getScreenSize().Height);
2508 g_profiler->clear();
2511 addProfilerGraphs(stats, draw_times, dtime);
2515 void Game::addProfilerGraphs(const RunStats &stats,
2516 const FpsControl &draw_times, f32 dtime)
2518 g_profiler->graphAdd("mainloop_other",
2519 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2521 if (draw_times.sleep_time != 0)
2522 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2523 g_profiler->graphAdd("mainloop_dtime", dtime);
2525 g_profiler->add("Elapsed time", dtime);
2526 g_profiler->avg("FPS", 1. / dtime);
2530 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2537 /* Time average and jitter calculation
2539 jp = &stats->dtime_jitter;
2540 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2542 jitter = dtime - jp->avg;
2544 if (jitter > jp->max)
2547 jp->counter += dtime;
2549 if (jp->counter > 0.0) {
2551 jp->max_sample = jp->max;
2552 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2556 /* Busytime average and jitter calculation
2558 jp = &stats->busy_time_jitter;
2559 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2561 jitter = draw_times.busy_time - jp->avg;
2563 if (jitter > jp->max)
2565 if (jitter < jp->min)
2568 jp->counter += dtime;
2570 if (jp->counter > 0.0) {
2572 jp->max_sample = jp->max;
2573 jp->min_sample = jp->min;
2581 /****************************************************************************
2583 ****************************************************************************/
2585 void Game::processUserInput(VolatileRunFlags *flags,
2586 GameRunData *runData, f32 dtime)
2588 // Reset input if window not active or some menu is active
2589 if (device->isWindowActive() == false
2590 || noMenuActive() == false
2591 || guienv->hasFocus(gui_chat_console)) {
2593 #ifdef HAVE_TOUCHSCREENGUI
2594 g_touchscreengui->hide();
2597 #ifdef HAVE_TOUCHSCREENGUI
2598 else if (g_touchscreengui) {
2599 /* on touchscreengui step may generate own input events which ain't
2600 * what we want in case we just did clear them */
2601 g_touchscreengui->step(dtime);
2605 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2606 gui_chat_console->closeConsoleAtOnce();
2609 // Input handler step() (used by the random input generator)
2614 if (current_formspec != 0)
2615 current_formspec->getAndroidUIInput();
2619 // Increase timer for double tap of "keymap_jump"
2620 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2621 runData->jump_timer += dtime;
2623 processKeyboardInput(
2625 &runData->statustext_time,
2626 &runData->jump_timer,
2627 &runData->reset_jump_timer,
2628 &runData->profiler_current_page,
2629 runData->profiler_max_page);
2631 processItemSelection(&runData->new_playeritem);
2635 void Game::processKeyboardInput(VolatileRunFlags *flags,
2636 float *statustext_time,
2638 bool *reset_jump_timer,
2639 u32 *profiler_current_page,
2640 u32 profiler_max_page)
2643 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2645 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2647 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_AUTORUN])) {
2648 toggleAutorun(statustext_time);
2649 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2651 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2652 if (!gui_chat_console->isOpenInhibited()) {
2653 show_pause_menu(¤t_formspec, client, gamedef,
2654 texture_src, device, simple_singleplayer_mode);
2656 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2657 openConsole(0.2, L"");
2658 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2659 openConsole(0.2, L"/");
2660 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2662 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2663 toggleFreeMove(statustext_time);
2664 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2665 toggleFreeMoveAlt(statustext_time, jump_timer);
2666 *reset_jump_timer = true;
2667 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2668 toggleFast(statustext_time);
2669 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2670 toggleNoClip(statustext_time);
2671 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2672 toggleCinematic(statustext_time);
2673 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2674 client->makeScreenshot(device);
2675 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2676 toggleHud(statustext_time, &flags->show_hud);
2677 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_MINIMAP])) {
2678 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2679 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]));
2680 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2681 toggleChat(statustext_time, &flags->show_chat);
2682 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2683 toggleFog(statustext_time, &flags->force_fog_off);
2684 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2685 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2686 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2687 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2688 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2689 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2690 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2691 increaseViewRange(statustext_time);
2692 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2693 decreaseViewRange(statustext_time);
2694 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2695 toggleFullViewRange(statustext_time);
2696 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT])) {
2698 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV])) {
2700 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC])) {
2702 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC])) {
2704 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2705 // Print debug stacks
2706 dstream << "-----------------------------------------"
2708 dstream << "Printing debug stacks:" << std::endl;
2709 dstream << "-----------------------------------------"
2711 debug_stacks_print();
2714 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2715 *reset_jump_timer = false;
2721 if (quicktune->hasMessage()) {
2722 std::string msg = quicktune->getMessage();
2723 statustext = utf8_to_wide(msg);
2724 *statustext_time = 0;
2729 void Game::processItemSelection(u16 *new_playeritem)
2731 LocalPlayer *player = client->getEnv().getLocalPlayer();
2733 /* Item selection using mouse wheel
2735 *new_playeritem = client->getPlayerItem();
2737 s32 wheel = input->getMouseWheel();
2738 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2739 player->hud_hotbar_itemcount - 1);
2742 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2744 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2748 /* Item selection using keyboard
2750 for (u16 i = 0; i < 10; i++) {
2751 static const KeyPress *item_keys[10] = {
2752 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2753 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2754 NumberKey + 9, NumberKey + 0,
2757 if (input->wasKeyDown(*item_keys[i])) {
2758 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2759 *new_playeritem = i;
2760 infostream << "Selected item: " << new_playeritem << std::endl;
2768 void Game::dropSelectedItem()
2770 IDropAction *a = new IDropAction();
2772 a->from_inv.setCurrentPlayer();
2773 a->from_list = "main";
2774 a->from_i = client->getPlayerItem();
2775 client->inventoryAction(a);
2779 void Game::openInventory()
2782 * Don't permit to open inventory is CAO or player doesn't exists.
2783 * This prevent showing an empty inventory at player load
2786 LocalPlayer *player = client->getEnv().getLocalPlayer();
2787 if (player == NULL || player->getCAO() == NULL)
2790 infostream << "the_game: " << "Launching inventory" << std::endl;
2792 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2793 TextDest *txt_dst = new TextDestPlayerInventory(client);
2795 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2796 device, fs_src, txt_dst, client);
2798 InventoryLocation inventoryloc;
2799 inventoryloc.setCurrentPlayer();
2800 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2804 void Game::openConsole(float height, const wchar_t *line)
2806 if (!gui_chat_console->isOpenInhibited()) {
2807 gui_chat_console->openConsole(height);
2809 gui_chat_console->setCloseOnEnter(true);
2810 gui_chat_console->replaceAndAddToHistory(line);
2812 guienv->setFocus(gui_chat_console);
2817 void Game::toggleFreeMove(float *statustext_time)
2819 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2821 bool free_move = !g_settings->getBool("free_move");
2822 g_settings->set("free_move", bool_to_cstr(free_move));
2824 *statustext_time = 0;
2825 statustext = msg[free_move];
2826 if (free_move && !client->checkPrivilege("fly"))
2827 statustext += L" (note: no 'fly' privilege)";
2831 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2833 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2834 toggleFreeMove(statustext_time);
2838 void Game::toggleFast(float *statustext_time)
2840 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2841 bool fast_move = !g_settings->getBool("fast_move");
2842 g_settings->set("fast_move", bool_to_cstr(fast_move));
2844 *statustext_time = 0;
2845 statustext = msg[fast_move];
2847 bool has_fast_privs = client->checkPrivilege("fast");
2849 if (fast_move && !has_fast_privs)
2850 statustext += L" (note: no 'fast' privilege)";
2853 m_cache_hold_aux1 = fast_move && has_fast_privs;
2858 void Game::toggleNoClip(float *statustext_time)
2860 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2861 bool noclip = !g_settings->getBool("noclip");
2862 g_settings->set("noclip", bool_to_cstr(noclip));
2864 *statustext_time = 0;
2865 statustext = msg[noclip];
2867 if (noclip && !client->checkPrivilege("noclip"))
2868 statustext += L" (note: no 'noclip' privilege)";
2871 void Game::toggleCinematic(float *statustext_time)
2873 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2874 bool cinematic = !g_settings->getBool("cinematic");
2875 g_settings->set("cinematic", bool_to_cstr(cinematic));
2877 *statustext_time = 0;
2878 statustext = msg[cinematic];
2881 // Add WoW-style autorun by toggling continuous forward.
2882 void Game::toggleAutorun(float *statustext_time)
2884 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2885 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2886 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2888 *statustext_time = 0;
2889 statustext = msg[autorun_enabled ? 1 : 0];
2892 void Game::toggleChat(float *statustext_time, bool *flag)
2894 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2897 *statustext_time = 0;
2898 statustext = msg[*flag];
2902 void Game::toggleHud(float *statustext_time, bool *flag)
2904 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2907 *statustext_time = 0;
2908 statustext = msg[*flag];
2911 void Game::toggleMinimap(float *statustext_time, bool *flag,
2912 bool show_hud, bool shift_pressed)
2914 if (!show_hud || !g_settings->getBool("enable_minimap"))
2917 if (shift_pressed) {
2918 mapper->toggleMinimapShape();
2922 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2924 MinimapMode mode = MINIMAP_MODE_OFF;
2925 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2926 mode = mapper->getMinimapMode();
2927 mode = (MinimapMode)((int)mode + 1);
2932 case MINIMAP_MODE_SURFACEx1:
2933 statustext = L"Minimap in surface mode, Zoom x1";
2935 case MINIMAP_MODE_SURFACEx2:
2936 statustext = L"Minimap in surface mode, Zoom x2";
2938 case MINIMAP_MODE_SURFACEx4:
2939 statustext = L"Minimap in surface mode, Zoom x4";
2941 case MINIMAP_MODE_RADARx1:
2942 statustext = L"Minimap in radar mode, Zoom x1";
2944 case MINIMAP_MODE_RADARx2:
2945 statustext = L"Minimap in radar mode, Zoom x2";
2947 case MINIMAP_MODE_RADARx4:
2948 statustext = L"Minimap in radar mode, Zoom x4";
2951 mode = MINIMAP_MODE_OFF;
2953 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2954 L"Minimap hidden" : L"Minimap disabled by server";
2957 *statustext_time = 0;
2958 mapper->setMinimapMode(mode);
2961 void Game::toggleFog(float *statustext_time, bool *flag)
2963 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2966 *statustext_time = 0;
2967 statustext = msg[*flag];
2971 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2972 bool *show_profiler_graph)
2974 // Initial / 3x toggle: Chat only
2975 // 1x toggle: Debug text with chat
2976 // 2x toggle: Debug text with profiler graph
2979 *show_profiler_graph = false;
2980 statustext = L"Debug info shown";
2981 } else if (*show_profiler_graph) {
2982 *show_debug = false;
2983 *show_profiler_graph = false;
2984 statustext = L"Debug info and profiler graph hidden";
2986 *show_profiler_graph = true;
2987 statustext = L"Profiler graph shown";
2989 *statustext_time = 0;
2993 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2995 static const wchar_t *msg[] = {
2996 L"Camera update enabled",
2997 L"Camera update disabled"
3001 *statustext_time = 0;
3002 statustext = msg[*flag];
3006 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3007 u32 profiler_max_page)
3009 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3011 // FIXME: This updates the profiler with incomplete values
3012 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3013 profiler_max_page, driver->getScreenSize().Height);
3015 if (*profiler_current_page != 0) {
3016 std::wstringstream sstr;
3017 sstr << "Profiler shown (page " << *profiler_current_page
3018 << " of " << profiler_max_page << ")";
3019 statustext = sstr.str();
3021 statustext = L"Profiler hidden";
3023 *statustext_time = 0;
3027 void Game::increaseViewRange(float *statustext_time)
3029 s16 range = g_settings->getS16("viewing_range");
3030 s16 range_new = range + 10;
3031 g_settings->set("viewing_range", itos(range_new));
3032 statustext = utf8_to_wide("Viewing range changed to "
3034 *statustext_time = 0;
3038 void Game::decreaseViewRange(float *statustext_time)
3040 s16 range = g_settings->getS16("viewing_range");
3041 s16 range_new = range - 10;
3046 g_settings->set("viewing_range", itos(range_new));
3047 statustext = utf8_to_wide("Viewing range changed to "
3049 *statustext_time = 0;
3053 void Game::toggleFullViewRange(float *statustext_time)
3055 static const wchar_t *msg[] = {
3056 L"Disabled full viewing range",
3057 L"Enabled full viewing range"
3060 draw_control->range_all = !draw_control->range_all;
3061 infostream << msg[draw_control->range_all] << std::endl;
3062 statustext = msg[draw_control->range_all];
3063 *statustext_time = 0;
3067 void Game::updateCameraDirection(CameraOrientation *cam,
3068 VolatileRunFlags *flags)
3070 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3073 if (!random_input) {
3074 // Mac OSX gets upset if this is set every frame
3075 if (device->getCursorControl()->isVisible())
3076 device->getCursorControl()->setVisible(false);
3080 if (flags->first_loop_after_window_activation)
3081 flags->first_loop_after_window_activation = false;
3083 updateCameraOrientation(cam, *flags);
3085 input->setMousePos((driver->getScreenSize().Width / 2),
3086 (driver->getScreenSize().Height / 2));
3090 // Mac OSX gets upset if this is set every frame
3091 if (device->getCursorControl()->isVisible() == false)
3092 device->getCursorControl()->setVisible(true);
3095 if (!flags->first_loop_after_window_activation)
3096 flags->first_loop_after_window_activation = true;
3102 void Game::updateCameraOrientation(CameraOrientation *cam,
3103 const VolatileRunFlags &flags)
3105 #ifdef HAVE_TOUCHSCREENGUI
3106 if (g_touchscreengui) {
3107 cam->camera_yaw = g_touchscreengui->getYaw();
3108 cam->camera_pitch = g_touchscreengui->getPitch();
3111 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3112 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3114 if (flags.invert_mouse
3115 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3119 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3120 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3122 #ifdef HAVE_TOUCHSCREENGUI
3126 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3130 void Game::updatePlayerControl(const CameraOrientation &cam)
3132 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3134 PlayerControl control(
3135 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
3136 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
3137 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3138 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3139 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3140 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3141 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3142 input->getLeftState(),
3143 input->getRightState(),
3149 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3150 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3151 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3152 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3153 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3154 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3155 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3156 ( (u32)(input->getLeftState() & 0x1) << 7) |
3157 ( (u32)(input->getRightState() & 0x1) << 8
3161 /* For Android, simulate holding down AUX1 (fast move) if the user has
3162 * the fast_move setting toggled on. If there is an aux1 key defined for
3163 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3166 if (m_cache_hold_aux1) {
3167 control.aux1 = control.aux1 ^ true;
3168 keypress_bits ^= ((u32)(1U << 5));
3172 client->setPlayerControl(control);
3173 LocalPlayer *player = client->getEnv().getLocalPlayer();
3174 player->keyPressed = keypress_bits;
3180 inline void Game::step(f32 *dtime)
3182 bool can_be_and_is_paused =
3183 (simple_singleplayer_mode && g_menumgr.pausesGame());
3185 if (can_be_and_is_paused) { // This is for a singleplayer server
3186 *dtime = 0; // No time passes
3188 if (server != NULL) {
3189 //TimeTaker timer("server->step(dtime)");
3190 server->step(*dtime);
3193 //TimeTaker timer("client.step(dtime)");
3194 client->step(*dtime);
3199 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3201 ClientEvent event = client->getClientEvent();
3203 LocalPlayer *player = client->getEnv().getLocalPlayer();
3205 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3207 if (event.type == CE_PLAYER_DAMAGE &&
3208 client->getHP() != 0) {
3209 //u16 damage = event.player_damage.amount;
3210 //infostream<<"Player damage: "<<damage<<std::endl;
3212 *damage_flash += 100.0;
3213 *damage_flash += 8.0 * event.player_damage.amount;
3215 player->hurt_tilt_timer = 1.5;
3216 player->hurt_tilt_strength = event.player_damage.amount / 4;
3217 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3219 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3220 gamedef->event()->put(e);
3221 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3222 cam->camera_yaw = event.player_force_move.yaw;
3223 cam->camera_pitch = event.player_force_move.pitch;
3224 } else if (event.type == CE_DEATHSCREEN) {
3225 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3228 chat_backend->addMessage(L"", L"You died.");
3230 /* Handle visualization */
3232 player->hurt_tilt_timer = 0;
3233 player->hurt_tilt_strength = 0;
3235 } else if (event.type == CE_SHOW_FORMSPEC) {
3236 FormspecFormSource *fs_src =
3237 new FormspecFormSource(*(event.show_formspec.formspec));
3238 TextDestPlayerInventory *txt_dst =
3239 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3241 create_formspec_menu(¤t_formspec, client, gamedef,
3242 texture_src, device, fs_src, txt_dst, client);
3244 delete(event.show_formspec.formspec);
3245 delete(event.show_formspec.formname);
3246 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3247 (event.type == CE_ADD_PARTICLESPAWNER) ||
3248 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3249 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3251 } else if (event.type == CE_HUDADD) {
3252 u32 id = event.hudadd.id;
3254 LocalPlayer *player = client->getEnv().getLocalPlayer();
3255 HudElement *e = player->getHud(id);
3258 delete event.hudadd.pos;
3259 delete event.hudadd.name;
3260 delete event.hudadd.scale;
3261 delete event.hudadd.text;
3262 delete event.hudadd.align;
3263 delete event.hudadd.offset;
3264 delete event.hudadd.world_pos;
3265 delete event.hudadd.size;
3270 e->type = (HudElementType)event.hudadd.type;
3271 e->pos = *event.hudadd.pos;
3272 e->name = *event.hudadd.name;
3273 e->scale = *event.hudadd.scale;
3274 e->text = *event.hudadd.text;
3275 e->number = event.hudadd.number;
3276 e->item = event.hudadd.item;
3277 e->dir = event.hudadd.dir;
3278 e->align = *event.hudadd.align;
3279 e->offset = *event.hudadd.offset;
3280 e->world_pos = *event.hudadd.world_pos;
3281 e->size = *event.hudadd.size;
3283 u32 new_id = player->addHud(e);
3284 //if this isn't true our huds aren't consistent
3285 sanity_check(new_id == id);
3287 delete event.hudadd.pos;
3288 delete event.hudadd.name;
3289 delete event.hudadd.scale;
3290 delete event.hudadd.text;
3291 delete event.hudadd.align;
3292 delete event.hudadd.offset;
3293 delete event.hudadd.world_pos;
3294 delete event.hudadd.size;
3295 } else if (event.type == CE_HUDRM) {
3296 HudElement *e = player->removeHud(event.hudrm.id);
3300 } else if (event.type == CE_HUDCHANGE) {
3301 u32 id = event.hudchange.id;
3302 HudElement *e = player->getHud(id);
3305 delete event.hudchange.v3fdata;
3306 delete event.hudchange.v2fdata;
3307 delete event.hudchange.sdata;
3308 delete event.hudchange.v2s32data;
3312 switch (event.hudchange.stat) {
3314 e->pos = *event.hudchange.v2fdata;
3318 e->name = *event.hudchange.sdata;
3321 case HUD_STAT_SCALE:
3322 e->scale = *event.hudchange.v2fdata;
3326 e->text = *event.hudchange.sdata;
3329 case HUD_STAT_NUMBER:
3330 e->number = event.hudchange.data;
3334 e->item = event.hudchange.data;
3338 e->dir = event.hudchange.data;
3341 case HUD_STAT_ALIGN:
3342 e->align = *event.hudchange.v2fdata;
3345 case HUD_STAT_OFFSET:
3346 e->offset = *event.hudchange.v2fdata;
3349 case HUD_STAT_WORLD_POS:
3350 e->world_pos = *event.hudchange.v3fdata;
3354 e->size = *event.hudchange.v2s32data;
3358 delete event.hudchange.v3fdata;
3359 delete event.hudchange.v2fdata;
3360 delete event.hudchange.sdata;
3361 delete event.hudchange.v2s32data;
3362 } else if (event.type == CE_SET_SKY) {
3363 sky->setVisible(false);
3370 // Handle according to type
3371 if (*event.set_sky.type == "regular") {
3372 sky->setVisible(true);
3373 } else if (*event.set_sky.type == "skybox" &&
3374 event.set_sky.params->size() == 6) {
3375 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3376 skybox = smgr->addSkyBoxSceneNode(
3377 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3378 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3379 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3380 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3381 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3382 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3384 // Handle everything else as plain color
3386 if (*event.set_sky.type != "plain")
3387 infostream << "Unknown sky type: "
3388 << (*event.set_sky.type) << std::endl;
3390 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3393 delete event.set_sky.bgcolor;
3394 delete event.set_sky.type;
3395 delete event.set_sky.params;
3396 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3397 bool enable = event.override_day_night_ratio.do_override;
3398 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3399 client->getEnv().setDayNightRatioOverride(enable, value);
3405 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3406 f32 dtime, float time_from_last_punch)
3408 LocalPlayer *player = client->getEnv().getLocalPlayer();
3411 For interaction purposes, get info about the held item
3413 - Is it a usable item?
3414 - Can it point to liquids?
3416 ItemStack playeritem;
3418 InventoryList *mlist = local_inventory->getList("main");
3420 if (mlist && client->getPlayerItem() < mlist->getSize())
3421 playeritem = mlist->getItem(client->getPlayerItem());
3424 ToolCapabilities playeritem_toolcap =
3425 playeritem.getToolCapabilities(itemdef_manager);
3427 v3s16 old_camera_offset = camera->getOffset();
3429 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3430 GenericCAO *playercao = player->getCAO();
3432 // If playercao not loaded, don't change camera
3433 if (playercao == NULL)
3436 camera->toggleCameraMode();
3438 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3439 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3442 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3443 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3445 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3446 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3448 camera->step(dtime);
3450 v3f camera_position = camera->getPosition();
3451 v3f camera_direction = camera->getDirection();
3452 f32 camera_fov = camera->getFovMax();
3453 v3s16 camera_offset = camera->getOffset();
3455 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3457 if (!flags->disable_camera_update) {
3458 client->getEnv().getClientMap().updateCamera(camera_position,
3459 camera_direction, camera_fov, camera_offset);
3461 if (flags->camera_offset_changed) {
3462 client->updateCameraOffset(camera_offset);
3463 client->getEnv().updateCameraOffset(camera_offset);
3466 clouds->updateCameraOffset(camera_offset);
3472 void Game::updateSound(f32 dtime)
3474 // Update sound listener
3475 v3s16 camera_offset = camera->getOffset();
3476 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3477 v3f(0, 0, 0), // velocity
3478 camera->getDirection(),
3479 camera->getCameraNode()->getUpVector());
3480 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3483 // Update sound maker
3484 soundmaker->step(dtime);
3486 LocalPlayer *player = client->getEnv().getLocalPlayer();
3488 ClientMap &map = client->getEnv().getClientMap();
3489 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3490 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3494 void Game::processPlayerInteraction(GameRunData *runData,
3495 f32 dtime, bool show_hud, bool show_debug)
3497 LocalPlayer *player = client->getEnv().getLocalPlayer();
3499 ItemStack playeritem;
3501 InventoryList *mlist = local_inventory->getList("main");
3503 if (mlist && client->getPlayerItem() < mlist->getSize())
3504 playeritem = mlist->getItem(client->getPlayerItem());
3507 const ItemDefinition &playeritem_def =
3508 playeritem.getDefinition(itemdef_manager);
3510 v3f player_position = player->getPosition();
3511 v3f camera_position = camera->getPosition();
3512 v3f camera_direction = camera->getDirection();
3513 v3s16 camera_offset = camera->getOffset();
3517 Calculate what block is the crosshair pointing to
3520 f32 d = playeritem_def.range; // max. distance
3521 f32 d_hand = itemdef_manager->get("").range;
3523 if (d < 0 && d_hand >= 0)
3528 core::line3d<f32> shootline;
3530 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3532 shootline = core::line3d<f32>(camera_position,
3533 camera_position + camera_direction * BS * (d + 1));
3536 // prevent player pointing anything in front-view
3537 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3538 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3541 #ifdef HAVE_TOUCHSCREENGUI
3543 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3544 shootline = g_touchscreengui->getShootline();
3545 shootline.start += intToFloat(camera_offset, BS);
3546 shootline.end += intToFloat(camera_offset, BS);
3551 PointedThing pointed = getPointedThing(
3553 client, hud, player_position, camera_direction,
3554 camera_position, shootline, d,
3555 playeritem_def.liquids_pointable,
3556 !runData->ldown_for_dig,
3559 runData->selected_object);
3561 if (pointed != runData->pointed_old) {
3562 infostream << "Pointing at " << pointed.dump() << std::endl;
3563 hud->updateSelectionMesh(camera_offset);
3568 - releasing left mouse button
3569 - pointing away from node
3571 if (runData->digging) {
3572 if (input->getLeftReleased()) {
3573 infostream << "Left button released"
3574 << " (stopped digging)" << std::endl;
3575 runData->digging = false;
3576 } else if (pointed != runData->pointed_old) {
3577 if (pointed.type == POINTEDTHING_NODE
3578 && runData->pointed_old.type == POINTEDTHING_NODE
3579 && pointed.node_undersurface
3580 == runData->pointed_old.node_undersurface) {
3581 // Still pointing to the same node, but a different face.
3584 infostream << "Pointing away from node"
3585 << " (stopped digging)" << std::endl;
3586 runData->digging = false;
3587 hud->updateSelectionMesh(camera_offset);
3591 if (!runData->digging) {
3592 client->interact(1, runData->pointed_old);
3593 client->setCrack(-1, v3s16(0, 0, 0));
3594 runData->dig_time = 0.0;
3598 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3599 runData->ldown_for_dig = false;
3602 runData->left_punch = false;
3604 soundmaker->m_player_leftpunch_sound.name = "";
3606 if (input->getRightState())
3607 runData->repeat_rightclick_timer += dtime;
3609 runData->repeat_rightclick_timer = 0;
3611 if (playeritem_def.usable && input->getLeftState()) {
3612 if (input->getLeftClicked())
3613 client->interact(4, pointed);
3614 } else if (pointed.type == POINTEDTHING_NODE) {
3615 ToolCapabilities playeritem_toolcap =
3616 playeritem.getToolCapabilities(itemdef_manager);
3617 handlePointingAtNode(runData, pointed, playeritem_def,
3618 playeritem_toolcap, dtime);
3619 } else if (pointed.type == POINTEDTHING_OBJECT) {
3620 handlePointingAtObject(runData, pointed, playeritem,
3621 player_position, show_debug);
3622 } else if (input->getLeftState()) {
3623 // When button is held down in air, show continuous animation
3624 runData->left_punch = true;
3625 } else if (input->getRightClicked()) {
3626 handlePointingAtNothing(runData, playeritem);
3629 runData->pointed_old = pointed;
3631 if (runData->left_punch || input->getLeftClicked())
3632 camera->setDigging(0); // left click animation
3634 input->resetLeftClicked();
3635 input->resetRightClicked();
3637 input->resetLeftReleased();
3638 input->resetRightReleased();
3642 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3644 infostream << "Right Clicked in Air" << std::endl;
3645 PointedThing fauxPointed;
3646 fauxPointed.type = POINTEDTHING_NOTHING;
3647 client->interact(5, fauxPointed);
3651 void Game::handlePointingAtNode(GameRunData *runData,
3652 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3653 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3655 v3s16 nodepos = pointed.node_undersurface;
3656 v3s16 neighbourpos = pointed.node_abovesurface;
3659 Check information text of node
3662 ClientMap &map = client->getEnv().getClientMap();
3663 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3666 infotext = utf8_to_wide(meta->getString("infotext"));
3668 MapNode n = map.getNodeNoEx(nodepos);
3670 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3671 infotext = L"Unknown node: ";
3672 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3676 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3677 && client->checkPrivilege("interact")) {
3678 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3681 if ((input->getRightClicked() ||
3682 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3683 client->checkPrivilege("interact")) {
3684 runData->repeat_rightclick_timer = 0;
3685 infostream << "Ground right-clicked" << std::endl;
3687 if (meta && meta->getString("formspec") != "" && !random_input
3688 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3689 infostream << "Launching custom inventory view" << std::endl;
3691 InventoryLocation inventoryloc;
3692 inventoryloc.setNodeMeta(nodepos);
3694 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3695 &client->getEnv().getClientMap(), nodepos);
3696 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3698 create_formspec_menu(¤t_formspec, client, gamedef,
3699 texture_src, device, fs_src, txt_dst, client);
3701 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3703 // Report right click to server
3705 camera->setDigging(1); // right click animation (always shown for feedback)
3707 // If the wielded item has node placement prediction,
3709 bool placed = nodePlacementPrediction(*client,
3711 nodepos, neighbourpos);
3715 client->interact(3, pointed);
3717 soundmaker->m_player_rightpunch_sound =
3718 playeritem_def.sound_place;
3720 soundmaker->m_player_rightpunch_sound =
3723 if (playeritem_def.node_placement_prediction == "" ||
3724 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3725 client->interact(3, pointed); // Report to server
3727 soundmaker->m_player_rightpunch_sound =
3728 playeritem_def.sound_place_failed;
3736 void Game::handlePointingAtObject(GameRunData *runData,
3737 const PointedThing &pointed,
3738 const ItemStack &playeritem,
3739 const v3f &player_position,
3742 infotext = utf8_to_wide(runData->selected_object->infoText());
3745 if (infotext != L"") {
3748 infotext += utf8_to_wide(runData->selected_object->debugInfoText());
3751 if (input->getLeftState()) {
3752 bool do_punch = false;
3753 bool do_punch_damage = false;
3755 if (runData->object_hit_delay_timer <= 0.0) {
3757 do_punch_damage = true;
3758 runData->object_hit_delay_timer = object_hit_delay;
3761 if (input->getLeftClicked())
3765 infostream << "Left-clicked object" << std::endl;
3766 runData->left_punch = true;
3769 if (do_punch_damage) {
3770 // Report direct punch
3771 v3f objpos = runData->selected_object->getPosition();
3772 v3f dir = (objpos - player_position).normalize();
3774 bool disable_send = runData->selected_object->directReportPunch(
3775 dir, &playeritem, runData->time_from_last_punch);
3776 runData->time_from_last_punch = 0;
3779 client->interact(0, pointed);
3781 } else if (input->getRightClicked()) {
3782 infostream << "Right-clicked object" << std::endl;
3783 client->interact(3, pointed); // place
3788 void Game::handleDigging(GameRunData *runData,
3789 const PointedThing &pointed, const v3s16 &nodepos,
3790 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3792 if (!runData->digging) {
3793 infostream << "Started digging" << std::endl;
3794 client->interact(0, pointed);
3795 runData->digging = true;
3796 runData->ldown_for_dig = true;
3799 LocalPlayer *player = client->getEnv().getLocalPlayer();
3800 ClientMap &map = client->getEnv().getClientMap();
3801 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3803 // NOTE: Similar piece of code exists on the server side for
3805 // Get digging parameters
3806 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3807 &playeritem_toolcap);
3809 // If can't dig, try hand
3810 if (!params.diggable) {
3811 const ItemDefinition &hand = itemdef_manager->get("");
3812 const ToolCapabilities *tp = hand.tool_capabilities;
3815 params = getDigParams(nodedef_manager->get(n).groups, tp);
3818 if (params.diggable == false) {
3819 // I guess nobody will wait for this long
3820 runData->dig_time_complete = 10000000.0;
3822 runData->dig_time_complete = params.time;
3824 if (m_cache_enable_particles) {
3825 const ContentFeatures &features =
3826 client->getNodeDefManager()->get(n);
3827 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3828 player, nodepos, features.tiles);
3832 if (runData->dig_time_complete >= 0.001) {
3833 runData->dig_index = (float)crack_animation_length
3835 / runData->dig_time_complete;
3837 // This is for torches
3838 runData->dig_index = crack_animation_length;
3841 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3843 if (sound_dig.exists() && params.diggable) {
3844 if (sound_dig.name == "__group") {
3845 if (params.main_group != "") {
3846 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3847 soundmaker->m_player_leftpunch_sound.name =
3848 std::string("default_dig_") +
3852 soundmaker->m_player_leftpunch_sound = sound_dig;
3856 // Don't show cracks if not diggable
3857 if (runData->dig_time_complete >= 100000.0) {
3858 } else if (runData->dig_index < crack_animation_length) {
3859 //TimeTaker timer("client.setTempMod");
3860 //infostream<<"dig_index="<<dig_index<<std::endl;
3861 client->setCrack(runData->dig_index, nodepos);
3863 infostream << "Digging completed" << std::endl;
3864 client->interact(2, pointed);
3865 client->setCrack(-1, v3s16(0, 0, 0));
3866 bool is_valid_position;
3867 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3868 if (is_valid_position)
3869 client->removeNode(nodepos);
3871 if (m_cache_enable_particles) {
3872 const ContentFeatures &features =
3873 client->getNodeDefManager()->get(wasnode);
3874 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3875 player, nodepos, features.tiles);
3878 runData->dig_time = 0;
3879 runData->digging = false;
3881 runData->nodig_delay_timer =
3882 runData->dig_time_complete / (float)crack_animation_length;
3884 // We don't want a corresponding delay to
3885 // very time consuming nodes
3886 if (runData->nodig_delay_timer > 0.3)
3887 runData->nodig_delay_timer = 0.3;
3889 // We want a slight delay to very little
3890 // time consuming nodes
3891 const float mindelay = 0.15;
3893 if (runData->nodig_delay_timer < mindelay)
3894 runData->nodig_delay_timer = mindelay;
3896 // Send event to trigger sound
3897 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3898 gamedef->event()->put(e);
3901 if (runData->dig_time_complete < 100000.0) {
3902 runData->dig_time += dtime;
3904 runData->dig_time = 0;
3905 client->setCrack(-1, nodepos);
3908 camera->setDigging(0); // left click animation
3912 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
3913 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
3914 const CameraOrientation &cam)
3916 LocalPlayer *player = client->getEnv().getLocalPlayer();
3922 if (draw_control->range_all) {
3923 runData->fog_range = 100000 * BS;
3925 runData->fog_range = 0.9 * draw_control->wanted_range * BS;
3929 Calculate general brightness
3931 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3932 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3933 float direct_brightness;
3936 if (g_settings->getBool("free_move")) {
3937 direct_brightness = time_brightness;
3938 sunlight_seen = true;
3940 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3941 float old_brightness = sky->getBrightness();
3942 direct_brightness = client->getEnv().getClientMap()
3943 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3944 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3948 float time_of_day = runData->time_of_day;
3949 float time_of_day_smooth = runData->time_of_day_smooth;
3951 time_of_day = client->getEnv().getTimeOfDayF();
3953 const float maxsm = 0.05;
3954 const float todsm = 0.05;
3956 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3957 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3958 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3959 time_of_day_smooth = time_of_day;
3961 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3962 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3963 + (time_of_day + 1.0) * todsm;
3965 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3966 + time_of_day * todsm;
3968 runData->time_of_day = time_of_day;
3969 runData->time_of_day_smooth = time_of_day_smooth;
3971 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3972 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3973 player->getPitch());
3979 v3f player_position = player->getPosition();
3980 if (sky->getCloudsVisible()) {
3981 clouds->setVisible(true);
3982 clouds->step(dtime);
3983 clouds->update(v2f(player_position.X, player_position.Z),
3984 sky->getCloudColor());
3986 clouds->setVisible(false);
3993 client->getParticleManager()->step(dtime);
3999 if (m_cache_enable_fog && !flags.force_fog_off) {
4002 video::EFT_FOG_LINEAR,
4003 runData->fog_range * 0.4,
4004 runData->fog_range * 1.0,
4012 video::EFT_FOG_LINEAR,
4022 Get chat messages from client
4025 v2u32 screensize = driver->getScreenSize();
4027 updateChat(*client, dtime, flags.show_debug, screensize,
4028 flags.show_chat, runData->profiler_current_page,
4029 *chat_backend, guitext_chat);
4035 if (client->getPlayerItem() != runData->new_playeritem)
4036 client->selectPlayerItem(runData->new_playeritem);
4038 // Update local inventory if it has changed
4039 if (client->getLocalInventoryUpdated()) {
4040 //infostream<<"Updating local inventory"<<std::endl;
4041 client->getLocalInventory(*local_inventory);
4042 runData->update_wielded_item_trigger = true;
4045 if (runData->update_wielded_item_trigger) {
4046 // Update wielded tool
4047 InventoryList *mlist = local_inventory->getList("main");
4049 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4050 ItemStack item = mlist->getItem(client->getPlayerItem());
4051 camera->wield(item);
4053 runData->update_wielded_item_trigger = false;
4057 Update block draw list every 200ms or when camera direction has
4060 runData->update_draw_list_timer += dtime;
4062 v3f camera_direction = camera->getDirection();
4063 if (runData->update_draw_list_timer >= 0.2
4064 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4065 || flags.camera_offset_changed) {
4066 runData->update_draw_list_timer = 0;
4067 client->getEnv().getClientMap().updateDrawList(driver);
4068 runData->update_draw_list_last_cam_dir = camera_direction;
4071 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4074 make sure menu is on top
4075 1. Delete formspec menu reference if menu was removed
4076 2. Else, make sure formspec menu is on top
4078 if (current_formspec) {
4079 if (current_formspec->getReferenceCount() == 1) {
4080 current_formspec->drop();
4081 current_formspec = NULL;
4082 } else if (!noMenuActive()) {
4083 guiroot->bringToFront(current_formspec);
4091 video::SColor skycolor = sky->getSkyColor();
4093 TimeTaker tt_draw("mainloop: draw");
4095 TimeTaker timer("beginScene");
4096 driver->beginScene(true, true, skycolor);
4097 stats->beginscenetime = timer.stop(true);
4100 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4101 guienv, screensize, skycolor, flags.show_hud,
4102 flags.show_minimap);
4107 if (flags.show_profiler_graph)
4108 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4113 if (runData->damage_flash > 0.0) {
4114 video::SColor color(std::min(runData->damage_flash, 180.0f),
4118 driver->draw2DRectangle(color,
4119 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4122 runData->damage_flash -= 100.0 * dtime;
4128 if (player->hurt_tilt_timer > 0.0) {
4129 player->hurt_tilt_timer -= dtime * 5;
4131 if (player->hurt_tilt_timer < 0)
4132 player->hurt_tilt_strength = 0;
4136 Update minimap pos and rotation
4138 if (flags.show_minimap && flags.show_hud) {
4139 mapper->setPos(floatToInt(player->getPosition(), BS));
4140 mapper->setAngle(player->getYaw());
4147 TimeTaker timer("endScene");
4149 stats->endscenetime = timer.stop(true);
4152 stats->drawtime = tt_draw.stop(true);
4153 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4157 inline static const char *yawToDirectionString(int yaw)
4159 // NOTE: TODO: This can be done mathematically without the else/else-if
4162 const char *player_direction;
4164 yaw = wrapDegrees_0_360(yaw);
4166 if (yaw >= 45 && yaw < 135)
4167 player_direction = "West [-X]";
4168 else if (yaw >= 135 && yaw < 225)
4169 player_direction = "South [-Z]";
4170 else if (yaw >= 225 && yaw < 315)
4171 player_direction = "East [+X]";
4173 player_direction = "North [+Z]";
4175 return player_direction;
4179 void Game::updateGui(float *statustext_time, const RunStats &stats,
4180 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4181 const CameraOrientation &cam)
4183 v2u32 screensize = driver->getScreenSize();
4184 LocalPlayer *player = client->getEnv().getLocalPlayer();
4185 v3f player_position = player->getPosition();
4187 if (flags.show_debug) {
4188 static float drawtime_avg = 0;
4189 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4191 u16 fps = 1.0 / stats.dtime_jitter.avg;
4192 //s32 fps = driver->getFPS();
4194 std::ostringstream os(std::ios_base::binary);
4196 << PROJECT_NAME_C " " << g_version_hash
4198 << " (R: range_all=" << draw_control->range_all << ")"
4199 << std::setprecision(0)
4200 << " drawtime = " << drawtime_avg
4201 << std::setprecision(1)
4202 << ", dtime_jitter = "
4203 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4204 << std::setprecision(1)
4205 << ", v_range = " << draw_control->wanted_range
4206 << std::setprecision(3)
4207 << ", RTT = " << client->getRTT();
4208 guitext->setText(utf8_to_wide(os.str()).c_str());
4209 guitext->setVisible(true);
4210 } else if (flags.show_hud || flags.show_chat) {
4211 std::ostringstream os(std::ios_base::binary);
4212 os << PROJECT_NAME_C " " << g_version_hash;
4213 guitext->setText(utf8_to_wide(os.str()).c_str());
4214 guitext->setVisible(true);
4216 guitext->setVisible(false);
4219 if (guitext->isVisible()) {
4220 core::rect<s32> rect(
4222 screensize.X, 5 + g_fontengine->getTextHeight()
4224 guitext->setRelativePosition(rect);
4227 if (flags.show_debug) {
4228 std::ostringstream os(std::ios_base::binary);
4229 os << std::setprecision(1) << std::fixed
4230 << "(" << (player_position.X / BS)
4231 << ", " << (player_position.Y / BS)
4232 << ", " << (player_position.Z / BS)
4233 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4234 << " " << yawToDirectionString(cam.camera_yaw)
4235 << ") (seed = " << ((u64)client->getMapSeed())
4238 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4239 ClientMap &map = client->getEnv().getClientMap();
4240 const INodeDefManager *nodedef = client->getNodeDefManager();
4241 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4242 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4243 const ContentFeatures &features = nodedef->get(n);
4244 os << " (pointing_at = " << nodedef->get(n).name
4245 << " - " << features.tiledef[0].name.c_str()
4250 guitext2->setText(utf8_to_wide(os.str()).c_str());
4251 guitext2->setVisible(true);
4253 core::rect<s32> rect(
4254 5, 5 + g_fontengine->getTextHeight(),
4255 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4257 guitext2->setRelativePosition(rect);
4259 guitext2->setVisible(false);
4262 guitext_info->setText(infotext.c_str());
4263 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4265 float statustext_time_max = 1.5;
4267 if (!statustext.empty()) {
4268 *statustext_time += dtime;
4270 if (*statustext_time >= statustext_time_max) {
4272 *statustext_time = 0;
4276 guitext_status->setText(statustext.c_str());
4277 guitext_status->setVisible(!statustext.empty());
4279 if (!statustext.empty()) {
4280 s32 status_width = guitext_status->getTextWidth();
4281 s32 status_height = guitext_status->getTextHeight();
4282 s32 status_y = screensize.Y - 150;
4283 s32 status_x = (screensize.X - status_width) / 2;
4284 core::rect<s32> rect(
4285 status_x , status_y - status_height,
4286 status_x + status_width, status_y
4288 guitext_status->setRelativePosition(rect);
4291 video::SColor initial_color(255, 0, 0, 0);
4293 if (guienv->getSkin())
4294 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4296 video::SColor final_color = initial_color;
4297 final_color.setAlpha(0);
4298 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4299 initial_color, final_color,
4300 pow(*statustext_time / statustext_time_max, 2.0f));
4301 guitext_status->setOverrideColor(fade_color);
4302 guitext_status->enableOverrideColor(true);
4307 /* Log times and stuff for visualization */
4308 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4310 Profiler::GraphValues values;
4311 g_profiler->graphGet(values);
4317 /****************************************************************************
4319 ****************************************************************************/
4321 /* On some computers framerate doesn't seem to be automatically limited
4323 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4325 // not using getRealTime is necessary for wine
4326 device->getTimer()->tick(); // Maker sure device time is up-to-date
4327 u32 time = device->getTimer()->getTime();
4328 u32 last_time = fps_timings->last_time;
4330 if (time > last_time) // Make sure time hasn't overflowed
4331 fps_timings->busy_time = time - last_time;
4333 fps_timings->busy_time = 0;
4335 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4336 ? g_settings->getFloat("pause_fps_max")
4337 : g_settings->getFloat("fps_max"));
4339 if (fps_timings->busy_time < frametime_min) {
4340 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4341 device->sleep(fps_timings->sleep_time);
4343 fps_timings->sleep_time = 0;
4346 /* Get the new value of the device timer. Note that device->sleep() may
4347 * not sleep for the entire requested time as sleep may be interrupted and
4348 * therefore it is arguably more accurate to get the new time from the
4349 * device rather than calculating it by adding sleep_time to time.
4352 device->getTimer()->tick(); // Update device timer
4353 time = device->getTimer()->getTime();
4355 if (time > last_time) // Make sure last_time hasn't overflowed
4356 *dtime = (time - last_time) / 1000.0;
4360 fps_timings->last_time = time;
4363 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4364 // pass a copy of it to this function
4365 // Note: \p msg must be allocated using new (not malloc())
4366 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4367 int percent, bool draw_clouds)
4369 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4373 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4375 ((Game *)data)->readSettings();
4378 void Game::readSettings()
4380 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4381 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4382 m_cache_enable_particles = g_settings->getBool("enable_particles");
4383 m_cache_enable_fog = g_settings->getBool("enable_fog");
4384 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4385 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4387 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4390 /****************************************************************************/
4391 /****************************************************************************
4393 ****************************************************************************/
4394 /****************************************************************************/
4396 void Game::extendedResourceCleanup()
4398 // Extended resource accounting
4399 infostream << "Irrlicht resources after cleanup:" << std::endl;
4400 infostream << "\tRemaining meshes : "
4401 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4402 infostream << "\tRemaining textures : "
4403 << driver->getTextureCount() << std::endl;
4405 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4406 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4407 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4411 clearTextureNameCache();
4412 infostream << "\tRemaining materials: "
4413 << driver-> getMaterialRendererCount()
4414 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4418 /****************************************************************************/
4419 /****************************************************************************
4420 extern function for launching the game
4421 ****************************************************************************/
4422 /****************************************************************************/
4424 void the_game(bool *kill,
4426 InputHandler *input,
4427 IrrlichtDevice *device,
4429 const std::string &map_dir,
4430 const std::string &playername,
4431 const std::string &password,
4432 const std::string &address, // If empty local server is created
4435 std::string &error_message,
4436 ChatBackend &chat_backend,
4437 bool *reconnect_requested,
4438 const SubgameSpec &gamespec, // Used for local game
4439 bool simple_singleplayer_mode)
4443 /* Make a copy of the server address because if a local singleplayer server
4444 * is created then this is updated and we don't want to change the value
4445 * passed to us by the calling function
4447 std::string server_address = address;
4451 if (game.startup(kill, random_input, input, device, map_dir,
4452 playername, password, &server_address, port, error_message,
4453 reconnect_requested, &chat_backend, gamespec,
4454 simple_singleplayer_mode)) {
4459 } catch (SerializationError &e) {
4460 error_message = std::string("A serialization error occurred:\n")
4461 + e.what() + "\n\nThe server is probably "
4462 " running a different version of " PROJECT_NAME_C ".";
4463 errorstream << error_message << std::endl;
4464 } catch (ServerError &e) {
4465 error_message = e.what();
4466 errorstream << "ServerError: " << error_message << std::endl;
4467 } catch (ModError &e) {
4468 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4469 errorstream << "ModError: " << error_message << std::endl;