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_CHAT_MENU") {
180 assert(m_client != 0);
182 if ((fields.find("btn_send") != fields.end()) ||
183 (fields.find("quit") != fields.end())) {
184 StringMap::const_iterator it = fields.find("f_text");
185 if (it != fields.end())
186 m_client->typeChatMessage(utf8_to_wide(it->second));
192 if (m_formname == "MT_DEATH_SCREEN") {
193 assert(m_client != 0);
195 if ((fields.find("btn_respawn") != fields.end())) {
196 m_client->sendRespawn();
200 if (fields.find("quit") != fields.end()) {
201 m_client->sendRespawn();
206 // don't show error message for unhandled cursor keys
207 if ((fields.find("key_up") != fields.end()) ||
208 (fields.find("key_down") != fields.end()) ||
209 (fields.find("key_left") != fields.end()) ||
210 (fields.find("key_right") != fields.end())) {
214 errorstream << "LocalFormspecHandler::gotText unhandled >"
215 << m_formname << "< event" << std::endl;
218 StringMap::const_iterator it;
219 for (it = fields.begin(); it != fields.end(); ++it) {
220 errorstream << "\t" << i << ": " << it->first
221 << "=" << it->second << std::endl;
229 /* Form update callback */
231 class NodeMetadataFormSource: public IFormSource
234 NodeMetadataFormSource(ClientMap *map, v3s16 p):
239 std::string getForm()
241 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
246 return meta->getString("formspec");
248 std::string resolveText(std::string str)
250 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
255 return meta->resolveString(str);
262 class PlayerInventoryFormSource: public IFormSource
265 PlayerInventoryFormSource(Client *client):
269 std::string getForm()
271 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
272 return player->inventory_formspec;
279 Check if a node is pointable
281 inline bool isPointableNode(const MapNode &n,
282 Client *client, bool liquids_pointable)
284 const ContentFeatures &features = client->getNodeDefManager()->get(n);
285 return features.pointable ||
286 (liquids_pointable && features.isLiquid());
290 Find what the player is pointing at
292 PointedThing getPointedThing(Client *client, Hud *hud, const v3f &player_position,
293 const v3f &camera_direction, const v3f &camera_position,
294 core::line3d<f32> shootline, f32 d, bool liquids_pointable,
295 bool look_for_object, const v3s16 &camera_offset,
296 ClientActiveObject *&selected_object)
300 std::vector<aabb3f> *selectionboxes = hud->getSelectionBoxes();
301 selectionboxes->clear();
302 selected_object = NULL;
304 INodeDefManager *nodedef = client->getNodeDefManager();
305 ClientMap &map = client->getEnv().getClientMap();
307 f32 mindistance = BS * 1001;
309 // First try to find a pointed at active object
310 if (look_for_object) {
311 selected_object = client->getSelectedActiveObject(d * BS,
312 camera_position, shootline);
314 if (selected_object != NULL) {
315 if (selected_object->doShowSelectionBox()) {
316 aabb3f *selection_box = selected_object->getSelectionBox();
317 // Box should exist because object was
318 // returned in the first place
319 assert(selection_box);
321 v3f pos = selected_object->getPosition();
322 selectionboxes->push_back(aabb3f(
323 selection_box->MinEdge, selection_box->MaxEdge));
324 hud->setSelectionPos(pos, camera_offset);
327 mindistance = (selected_object->getPosition() - camera_position).getLength();
329 result.type = POINTEDTHING_OBJECT;
330 result.object_id = selected_object->getId();
334 // That didn't work, try to find a pointed at node
337 v3s16 pos_i = floatToInt(player_position, BS);
339 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
343 s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
344 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
345 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
346 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
347 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
348 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
350 // Prevent signed number overflow
360 for (s16 y = ystart; y <= yend; y++)
361 for (s16 z = zstart; z <= zend; z++)
362 for (s16 x = xstart; x <= xend; x++) {
364 bool is_valid_position;
366 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
367 if (!is_valid_position)
370 if (!isPointableNode(n, client, liquids_pointable))
373 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
376 v3f npf = intToFloat(np, BS);
378 for (std::vector<aabb3f>::const_iterator
380 i != boxes.end(); ++i) {
385 for (u16 j = 0; j < 6; j++) {
386 v3s16 facedir = g_6dirs[j];
387 aabb3f facebox = box;
392 facebox.MinEdge.X = facebox.MaxEdge.X - d;
393 else if (facedir.X < 0)
394 facebox.MaxEdge.X = facebox.MinEdge.X + d;
395 else if (facedir.Y > 0)
396 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
397 else if (facedir.Y < 0)
398 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
399 else if (facedir.Z > 0)
400 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
401 else if (facedir.Z < 0)
402 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
404 v3f centerpoint = facebox.getCenter();
405 f32 distance = (centerpoint - camera_position).getLength();
407 if (distance >= mindistance)
410 if (!facebox.intersectsWithLine(shootline))
413 v3s16 np_above = np + facedir;
415 result.type = POINTEDTHING_NODE;
416 result.node_undersurface = np;
417 result.node_abovesurface = np_above;
418 mindistance = distance;
420 selectionboxes->clear();
421 for (std::vector<aabb3f>::const_iterator
423 i2 != boxes.end(); ++i2) {
425 box.MinEdge += v3f(-d, -d, -d);
426 box.MaxEdge += v3f(d, d, d);
427 selectionboxes->push_back(box);
429 hud->setSelectionPos(npf, camera_offset);
434 // Update selection mesh light level and vertex colors
435 if (selectionboxes->size() > 0) {
436 v3f pf = hud->getSelectionPos();
437 v3s16 p = floatToInt(pf, BS);
439 // Get selection mesh light level
440 MapNode n = map.getNodeNoEx(p);
441 u16 node_light = getInteriorLight(n, -1, nodedef);
442 u16 light_level = node_light;
444 for (u8 i = 0; i < 6; i++) {
445 n = map.getNodeNoEx(p + g_6dirs[i]);
446 node_light = getInteriorLight(n, -1, nodedef);
447 if (node_light > light_level)
448 light_level = node_light;
451 video::SColor c = MapBlock_LightColor(255, light_level, 0);
453 u8 night = c.getGreen();
454 u32 daynight_ratio = client->getEnv().getDayNightRatio();
455 finalColorBlend(c, day, night, daynight_ratio);
457 // Modify final color a bit with time
458 u32 timer = porting::getTimeMs() % 5000;
459 float timerf = (float)(irr::core::PI * ((timer / 2500.0) - 0.5));
460 float sin_r = 0.08 * sin(timerf);
461 float sin_g = 0.08 * sin(timerf + irr::core::PI * 0.5);
462 float sin_b = 0.08 * sin(timerf + irr::core::PI);
463 c.setRed(core::clamp(core::round32(c.getRed() * (0.8 + sin_r)), 0, 255));
464 c.setGreen(core::clamp(core::round32(c.getGreen() * (0.8 + sin_g)), 0, 255));
465 c.setBlue(core::clamp(core::round32(c.getBlue() * (0.8 + sin_b)), 0, 255));
467 // Set mesh final color
468 hud->setSelectionMeshColor(c);
473 /* Profiler display */
475 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
476 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
478 if (show_profiler == 0) {
479 guitext_profiler->setVisible(false);
482 std::ostringstream os(std::ios_base::binary);
483 g_profiler->printPage(os, show_profiler, show_profiler_max);
484 std::wstring text = utf8_to_wide(os.str());
485 guitext_profiler->setText(text.c_str());
486 guitext_profiler->setVisible(true);
488 s32 w = fe->getTextWidth(text.c_str());
493 unsigned text_height = fe->getTextHeight();
495 core::position2di upper_left, lower_right;
498 upper_left.Y = (text_height + 5) * 2;
499 lower_right.X = 12 + w;
500 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
502 if (lower_right.Y > screen_height * 2 / 3)
503 lower_right.Y = screen_height * 2 / 3;
505 core::rect<s32> rect(upper_left, lower_right);
507 guitext_profiler->setRelativePosition(rect);
508 guitext_profiler->setVisible(true);
516 Profiler::GraphValues values;
522 Meta(float initial = 0,
523 video::SColor color = video::SColor(255, 255, 255, 255)):
529 std::deque<Piece> m_log;
537 void put(const Profiler::GraphValues &values)
540 piece.values = values;
541 m_log.push_back(piece);
543 while (m_log.size() > m_log_max_size)
544 m_log.erase(m_log.begin());
547 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
548 gui::IGUIFont *font) const
550 std::map<std::string, Meta> m_meta;
552 for (std::deque<Piece>::const_iterator k = m_log.begin();
553 k != m_log.end(); ++k) {
554 const Piece &piece = *k;
556 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
557 i != piece.values.end(); ++i) {
558 const std::string &id = i->first;
559 const float &value = i->second;
560 std::map<std::string, Meta>::iterator j =
563 if (j == m_meta.end()) {
564 m_meta[id] = Meta(value);
568 if (value < j->second.min)
569 j->second.min = value;
571 if (value > j->second.max)
572 j->second.max = value;
577 static const video::SColor usable_colors[] = {
578 video::SColor(255, 255, 100, 100),
579 video::SColor(255, 90, 225, 90),
580 video::SColor(255, 100, 100, 255),
581 video::SColor(255, 255, 150, 50),
582 video::SColor(255, 220, 220, 100)
584 static const u32 usable_colors_count =
585 sizeof(usable_colors) / sizeof(*usable_colors);
586 u32 next_color_i = 0;
588 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
589 i != m_meta.end(); ++i) {
590 Meta &meta = i->second;
591 video::SColor color(255, 200, 200, 200);
593 if (next_color_i < usable_colors_count)
594 color = usable_colors[next_color_i++];
600 s32 textx = x_left + m_log_max_size + 15;
601 s32 textx2 = textx + 200 - 15;
604 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
605 i != m_meta.end(); ++i) {
606 const std::string &id = i->first;
607 const Meta &meta = i->second;
609 s32 y = y_bottom - meta_i * 50;
610 float show_min = meta.min;
611 float show_max = meta.max;
613 if (show_min >= -0.0001 && show_max >= -0.0001) {
614 if (show_min <= show_max * 0.5)
620 snprintf(buf, 10, "%.3g", show_max);
621 font->draw(utf8_to_wide(buf).c_str(),
622 core::rect<s32>(textx, y - graphh,
623 textx2, y - graphh + texth),
625 snprintf(buf, 10, "%.3g", show_min);
626 font->draw(utf8_to_wide(buf).c_str(),
627 core::rect<s32>(textx, y - texth,
630 font->draw(utf8_to_wide(id).c_str(),
631 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
632 textx2, y - graphh / 2 + texth / 2),
635 s32 graph1h = graphh;
636 bool relativegraph = (show_min != 0 && show_min != show_max);
637 float lastscaledvalue = 0.0;
638 bool lastscaledvalue_exists = false;
640 for (std::deque<Piece>::const_iterator j = m_log.begin();
641 j != m_log.end(); ++j) {
642 const Piece &piece = *j;
644 bool value_exists = false;
645 Profiler::GraphValues::const_iterator k =
646 piece.values.find(id);
648 if (k != piece.values.end()) {
655 lastscaledvalue_exists = false;
659 float scaledvalue = 1.0;
661 if (show_max != show_min)
662 scaledvalue = (value - show_min) / (show_max - show_min);
664 if (scaledvalue == 1.0 && value == 0) {
666 lastscaledvalue_exists = false;
671 if (lastscaledvalue_exists) {
672 s32 ivalue1 = lastscaledvalue * graph1h;
673 s32 ivalue2 = scaledvalue * graph1h;
674 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
675 v2s32(x, graph1y - ivalue2), meta.color);
678 lastscaledvalue = scaledvalue;
679 lastscaledvalue_exists = true;
681 s32 ivalue = scaledvalue * graph1h;
682 driver->draw2DLine(v2s32(x, graph1y),
683 v2s32(x, graph1y - ivalue), meta.color);
694 class NodeDugEvent: public MtEvent
700 NodeDugEvent(v3s16 p, MapNode n):
704 const char *getType() const
712 ISoundManager *m_sound;
713 INodeDefManager *m_ndef;
715 float m_player_step_timer;
717 SimpleSoundSpec m_player_step_sound;
718 SimpleSoundSpec m_player_leftpunch_sound;
719 SimpleSoundSpec m_player_rightpunch_sound;
721 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
724 m_player_step_timer(0)
728 void playPlayerStep()
730 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
731 m_player_step_timer = 0.03;
732 m_sound->playSound(m_player_step_sound, false);
736 static void viewBobbingStep(MtEvent *e, void *data)
738 SoundMaker *sm = (SoundMaker *)data;
739 sm->playPlayerStep();
742 static void playerRegainGround(MtEvent *e, void *data)
744 SoundMaker *sm = (SoundMaker *)data;
745 sm->playPlayerStep();
748 static void playerJump(MtEvent *e, void *data)
750 //SoundMaker *sm = (SoundMaker*)data;
753 static void cameraPunchLeft(MtEvent *e, void *data)
755 SoundMaker *sm = (SoundMaker *)data;
756 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
759 static void cameraPunchRight(MtEvent *e, void *data)
761 SoundMaker *sm = (SoundMaker *)data;
762 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
765 static void nodeDug(MtEvent *e, void *data)
767 SoundMaker *sm = (SoundMaker *)data;
768 NodeDugEvent *nde = (NodeDugEvent *)e;
769 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
772 static void playerDamage(MtEvent *e, void *data)
774 SoundMaker *sm = (SoundMaker *)data;
775 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
778 static void playerFallingDamage(MtEvent *e, void *data)
780 SoundMaker *sm = (SoundMaker *)data;
781 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
784 void registerReceiver(MtEventManager *mgr)
786 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
787 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
788 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
789 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
790 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
791 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
792 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
793 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
796 void step(float dtime)
798 m_player_step_timer -= dtime;
802 // Locally stored sounds don't need to be preloaded because of this
803 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
805 std::set<std::string> m_fetched;
807 void fetchSounds(const std::string &name,
808 std::set<std::string> &dst_paths,
809 std::set<std::string> &dst_datas)
811 if (m_fetched.count(name))
814 m_fetched.insert(name);
815 std::string base = porting::path_share + DIR_DELIM + "testsounds";
816 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
817 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
818 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
819 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
820 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
821 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
822 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
823 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
824 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
825 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
826 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
830 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
833 bool *m_force_fog_off;
839 void onSettingsChange(const std::string &name)
841 if (name == "enable_fog")
842 m_fogEnabled = g_settings->getBool("enable_fog");
845 static void SettingsCallback(const std::string &name, void *userdata)
847 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
850 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
851 f32 *fog_range, Client *client) :
853 m_force_fog_off(force_fog_off),
854 m_fog_range(fog_range),
857 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
858 m_fogEnabled = g_settings->getBool("enable_fog");
861 ~GameGlobalShaderConstantSetter()
863 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
866 virtual void onSetConstants(video::IMaterialRendererServices *services,
873 video::SColor bgcolor = m_sky->getBgColor();
874 video::SColorf bgcolorf(bgcolor);
875 float bgcolorfa[4] = {
881 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
884 float fog_distance = 10000 * BS;
886 if (m_fogEnabled && !*m_force_fog_off)
887 fog_distance = *m_fog_range;
889 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
892 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
893 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
894 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
896 u32 animation_timer = porting::getTimeMs() % 100000;
897 float animation_timer_f = (float)animation_timer / 100000.0;
898 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
899 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
901 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
902 v3f eye_position = player->getEyePosition();
903 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
904 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
906 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
907 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
909 // Uniform sampler layers
913 // before 1.8 there isn't a "integer interface", only float
914 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
915 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
916 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
917 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
919 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
920 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
921 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
926 bool nodePlacementPrediction(Client &client,
927 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
929 std::string prediction = playeritem_def.node_placement_prediction;
930 INodeDefManager *nodedef = client.ndef();
931 ClientMap &map = client.getEnv().getClientMap();
933 bool is_valid_position;
935 node = map.getNodeNoEx(nodepos, &is_valid_position);
936 if (!is_valid_position)
939 if (prediction != "" && !nodedef->get(node).rightclickable) {
940 verbosestream << "Node placement prediction for "
941 << playeritem_def.name << " is "
942 << prediction << std::endl;
943 v3s16 p = neighbourpos;
945 // Place inside node itself if buildable_to
946 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
947 if (is_valid_position)
949 if (nodedef->get(n_under).buildable_to)
952 node = map.getNodeNoEx(p, &is_valid_position);
953 if (is_valid_position &&!nodedef->get(node).buildable_to)
958 // Find id of predicted node
960 bool found = nodedef->getId(prediction, id);
963 errorstream << "Node placement prediction failed for "
964 << playeritem_def.name << " (places "
966 << ") - Name not known" << std::endl;
970 // Predict param2 for facedir and wallmounted nodes
973 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
974 v3s16 dir = nodepos - neighbourpos;
976 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
977 param2 = dir.Y < 0 ? 1 : 0;
978 } else if (abs(dir.X) > abs(dir.Z)) {
979 param2 = dir.X < 0 ? 3 : 2;
981 param2 = dir.Z < 0 ? 5 : 4;
985 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
986 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
988 if (abs(dir.X) > abs(dir.Z)) {
989 param2 = dir.X < 0 ? 3 : 1;
991 param2 = dir.Z < 0 ? 2 : 0;
997 //Check attachment if node is in group attached_node
998 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
999 static v3s16 wallmounted_dirs[8] = {
1009 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
1010 pp = p + wallmounted_dirs[param2];
1012 pp = p + v3s16(0, -1, 0);
1014 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
1018 // Add node to client map
1019 MapNode n(id, 0, param2);
1022 LocalPlayer *player = client.getEnv().getLocalPlayer();
1024 // Dont place node when player would be inside new node
1025 // NOTE: This is to be eventually implemented by a mod as client-side Lua
1026 if (!nodedef->get(n).walkable ||
1027 g_settings->getBool("enable_build_where_you_stand") ||
1028 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
1029 (nodedef->get(n).walkable &&
1030 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
1031 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
1033 // This triggers the required mesh update too
1034 client.addNode(p, n);
1037 } catch (InvalidPositionException &e) {
1038 errorstream << "Node placement prediction failed for "
1039 << playeritem_def.name << " (places "
1041 << ") - Position not loaded" << std::endl;
1048 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1049 InventoryManager *invmgr, IGameDef *gamedef,
1050 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1051 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1054 if (*cur_formspec == 0) {
1055 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1056 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1057 (*cur_formspec)->doPause = false;
1060 Caution: do not call (*cur_formspec)->drop() here --
1061 the reference might outlive the menu, so we will
1062 periodically check if *cur_formspec is the only
1063 remaining reference (i.e. the menu was removed)
1064 and delete it in that case.
1068 (*cur_formspec)->setFormSource(fs_src);
1069 (*cur_formspec)->setTextDest(txt_dest);
1074 #define SIZE_TAG "size[11,5.5]"
1076 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1079 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1080 InventoryManager *invmgr, IGameDef *gamedef,
1081 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1082 Client *client, std::string text)
1084 std::string formspec =
1085 FORMSPEC_VERSION_STRING
1087 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1088 "button_exit[4,3;3,0.5;btn_send;" + strgettext("Proceed") + "]"
1092 /* Note: FormspecFormSource and LocalFormspecHandler
1093 * are deleted by guiFormSpecMenu */
1094 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1095 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1097 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1100 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1101 InventoryManager *invmgr, IGameDef *gamedef,
1102 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1104 std::string formspec =
1105 std::string(FORMSPEC_VERSION_STRING) +
1107 "bgcolor[#320000b4;true]"
1108 "label[4.85,1.35;" + gettext("You died.") + "]"
1109 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1113 /* Note: FormspecFormSource and LocalFormspecHandler
1114 * are deleted by guiFormSpecMenu */
1115 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1116 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1118 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1121 /******************************************************************************/
1122 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1123 InventoryManager *invmgr, IGameDef *gamedef,
1124 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1125 bool singleplayermode)
1128 std::string control_text = strgettext("Default Controls:\n"
1129 "No menu visible:\n"
1130 "- single tap: button activate\n"
1131 "- double tap: place/use\n"
1132 "- slide finger: look around\n"
1133 "Menu/Inventory visible:\n"
1134 "- double tap (outside):\n"
1136 "- touch stack, touch slot:\n"
1138 "- touch&drag, tap 2nd finger\n"
1139 " --> place single item to slot\n"
1142 std::string control_text = strgettext("Default Controls:\n"
1144 "- Space: jump/climb\n"
1145 "- Shift: sneak/go down\n"
1148 "- Mouse: turn/look\n"
1149 "- Mouse left: dig/punch\n"
1150 "- Mouse right: place/use\n"
1151 "- Mouse wheel: select item\n"
1156 float ypos = singleplayermode ? 0.5 : 0.1;
1157 std::ostringstream os;
1159 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1160 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1161 << strgettext("Continue") << "]";
1163 if (!singleplayermode) {
1164 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1165 << strgettext("Change Password") << "]";
1169 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1170 << strgettext("Sound Volume") << "]";
1171 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1172 << strgettext("Change Keys") << "]";
1174 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1175 << strgettext("Exit to Menu") << "]";
1176 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1177 << strgettext("Exit to OS") << "]"
1178 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1179 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1180 << g_build_info << "\n"
1181 << "path_user = " << wrap_rows(porting::path_user, 20)
1185 /* Note: FormspecFormSource and LocalFormspecHandler *
1186 * are deleted by guiFormSpecMenu */
1187 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1188 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1190 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1191 std::string con("btn_continue");
1192 (*cur_formspec)->setFocus(con);
1193 (*cur_formspec)->doPause = true;
1196 /******************************************************************************/
1197 static void updateChat(Client &client, f32 dtime, bool show_debug,
1198 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1199 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1201 // Add chat log output for errors to be shown in chat
1202 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1204 // Get new messages from error log buffer
1205 while (!chat_log_error_buf.empty()) {
1206 chat_backend.addMessage(L"", utf8_to_wide(chat_log_error_buf.get()));
1209 // Get new messages from client
1210 std::wstring message;
1212 while (client.getChatMessage(message)) {
1213 chat_backend.addUnparsedMessage(message);
1216 // Remove old messages
1217 chat_backend.step(dtime);
1219 // Display all messages in a static text element
1220 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1221 std::wstring recent_chat = chat_backend.getRecentChat();
1222 unsigned int line_height = g_fontengine->getLineHeight();
1224 guitext_chat->setText(recent_chat.c_str());
1226 // Update gui element size and position
1227 s32 chat_y = 5 + line_height;
1230 chat_y += line_height;
1232 // first pass to calculate height of text to be set
1233 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1234 porting::getWindowSize().X - 20);
1235 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1236 guitext_chat->setRelativePosition(rect);
1238 //now use real height of text and adjust rect according to this size
1239 rect = core::rect<s32>(10, chat_y, width,
1240 chat_y + guitext_chat->getTextHeight());
1243 guitext_chat->setRelativePosition(rect);
1244 // Don't show chat if disabled or empty or profiler is enabled
1245 guitext_chat->setVisible(
1246 show_chat && recent_chat_count != 0 && !show_profiler);
1250 /****************************************************************************
1251 Fast key cache for main game loop
1252 ****************************************************************************/
1254 /* This is faster than using getKeySetting with the tradeoff that functions
1255 * using it must make sure that it's initialised before using it and there is
1256 * no error handling (for example bounds checking). This is really intended for
1257 * use only in the main running loop of the client (the_game()) where the faster
1258 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1259 * (e.g. formspecs) should continue using getKeySetting().
1263 KeyCache() { populate(); }
1278 KEYMAP_ID_INVENTORY,
1286 KEYMAP_ID_CINEMATIC,
1287 KEYMAP_ID_SCREENSHOT,
1288 KEYMAP_ID_TOGGLE_HUD,
1289 KEYMAP_ID_TOGGLE_CHAT,
1290 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1291 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1292 KEYMAP_ID_TOGGLE_DEBUG,
1293 KEYMAP_ID_TOGGLE_PROFILER,
1294 KEYMAP_ID_CAMERA_MODE,
1295 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1296 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1297 KEYMAP_ID_RANGESELECT,
1299 KEYMAP_ID_QUICKTUNE_NEXT,
1300 KEYMAP_ID_QUICKTUNE_PREV,
1301 KEYMAP_ID_QUICKTUNE_INC,
1302 KEYMAP_ID_QUICKTUNE_DEC,
1304 KEYMAP_ID_DEBUG_STACKS,
1306 // Fake keycode for array size and internal checks
1307 KEYMAP_INTERNAL_ENUM_COUNT
1314 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1317 void KeyCache::populate()
1319 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1320 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1321 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1322 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1323 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1324 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1325 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1327 key[KEYMAP_ID_AUTORUN] = getKeySetting("keymap_autorun");
1329 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1330 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1331 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1332 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1333 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1334 key[KEYMAP_ID_MINIMAP] = getKeySetting("keymap_minimap");
1335 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1336 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1337 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1338 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1339 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1340 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1341 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1342 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1343 = getKeySetting("keymap_toggle_force_fog_off");
1344 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1345 = getKeySetting("keymap_toggle_update_camera");
1346 key[KEYMAP_ID_TOGGLE_DEBUG]
1347 = getKeySetting("keymap_toggle_debug");
1348 key[KEYMAP_ID_TOGGLE_PROFILER]
1349 = getKeySetting("keymap_toggle_profiler");
1350 key[KEYMAP_ID_CAMERA_MODE]
1351 = getKeySetting("keymap_camera_mode");
1352 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1353 = getKeySetting("keymap_increase_viewing_range_min");
1354 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1355 = getKeySetting("keymap_decrease_viewing_range_min");
1356 key[KEYMAP_ID_RANGESELECT]
1357 = getKeySetting("keymap_rangeselect");
1359 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1360 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1361 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1362 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1364 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1368 /****************************************************************************
1370 ****************************************************************************/
1372 const float object_hit_delay = 0.2;
1375 u32 last_time, busy_time, sleep_time;
1379 /* The reason the following structs are not anonymous structs within the
1380 * class is that they are not used by the majority of member functions and
1381 * many functions that do require objects of thse types do not modify them
1382 * (so they can be passed as a const qualified parameter)
1384 struct CameraOrientation {
1385 f32 camera_yaw; // "right/left"
1386 f32 camera_pitch; // "up/down"
1389 struct GameRunData {
1392 PointedThing pointed_old;
1396 bool update_wielded_item_trigger;
1397 bool reset_jump_timer;
1398 float nodig_delay_timer;
1400 float dig_time_complete;
1401 float repeat_rightclick_timer;
1402 float object_hit_delay_timer;
1403 float time_from_last_punch;
1404 ClientActiveObject *selected_object;
1408 float update_draw_list_timer;
1409 float statustext_time;
1413 v3f update_draw_list_last_cam_dir;
1415 u32 profiler_current_page;
1416 u32 profiler_max_page; // Number of pages
1419 float time_of_day_smooth;
1423 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1431 Jitter dtime_jitter, busy_time_jitter;
1434 /* Flags that can, or may, change during main game loop
1436 struct VolatileRunFlags {
1443 bool show_profiler_graph;
1444 bool disable_camera_update;
1445 bool first_loop_after_window_activation;
1446 bool camera_offset_changed;
1450 /****************************************************************************
1452 ****************************************************************************/
1454 /* This is not intended to be a public class. If a public class becomes
1455 * desirable then it may be better to create another 'wrapper' class that
1456 * hides most of the stuff in this class (nothing in this class is required
1457 * by any other file) but exposes the public methods/data only.
1464 bool startup(bool *kill,
1466 InputHandler *input,
1467 IrrlichtDevice *device,
1468 const std::string &map_dir,
1469 const std::string &playername,
1470 const std::string &password,
1471 // If address is "", local server is used and address is updated
1472 std::string *address,
1474 std::string &error_message,
1476 ChatBackend *chat_backend,
1477 const SubgameSpec &gamespec, // Used for local game
1478 bool simple_singleplayer_mode);
1485 void extendedResourceCleanup();
1487 // Basic initialisation
1488 bool init(const std::string &map_dir, std::string *address,
1490 const SubgameSpec &gamespec);
1492 bool createSingleplayerServer(const std::string map_dir,
1493 const SubgameSpec &gamespec, u16 port, std::string *address);
1496 bool createClient(const std::string &playername,
1497 const std::string &password, std::string *address, u16 port);
1500 // Client connection
1501 bool connectToServer(const std::string &playername,
1502 const std::string &password, std::string *address, u16 port,
1503 bool *connect_ok, bool *aborted);
1504 bool getServerContent(bool *aborted);
1508 void updateInteractTimers(GameRunData *runData, f32 dtime);
1509 bool checkConnection();
1510 bool handleCallbacks();
1511 void processQueues();
1512 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1513 const FpsControl &draw_times, f32 dtime);
1514 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1516 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1518 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1520 void processKeyboardInput(VolatileRunFlags *flags,
1521 float *statustext_time,
1523 bool *reset_jump_timer,
1524 u32 *profiler_current_page,
1525 u32 profiler_max_page);
1526 void processItemSelection(u16 *new_playeritem);
1528 void dropSelectedItem();
1529 void openInventory();
1531 void toggleFreeMove(float *statustext_time);
1532 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1533 void toggleFast(float *statustext_time);
1534 void toggleNoClip(float *statustext_time);
1535 void toggleCinematic(float *statustext_time);
1536 void toggleAutorun(float *statustext_time);
1538 void toggleChat(float *statustext_time, bool *flag);
1539 void toggleHud(float *statustext_time, bool *flag);
1540 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1541 bool shift_pressed);
1542 void toggleFog(float *statustext_time, bool *flag);
1543 void toggleDebug(float *statustext_time, bool *show_debug,
1544 bool *show_profiler_graph);
1545 void toggleUpdateCamera(float *statustext_time, bool *flag);
1546 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1547 u32 profiler_max_page);
1549 void increaseViewRange(float *statustext_time);
1550 void decreaseViewRange(float *statustext_time);
1551 void toggleFullViewRange(float *statustext_time);
1553 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1554 void updateCameraOrientation(CameraOrientation *cam,
1555 const VolatileRunFlags &flags);
1556 void updatePlayerControl(const CameraOrientation &cam);
1557 void step(f32 *dtime);
1558 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1559 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1560 float time_from_last_punch);
1561 void updateSound(f32 dtime);
1562 void processPlayerInteraction(GameRunData *runData, f32 dtime, bool show_hud,
1564 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1565 void handlePointingAtNode(GameRunData *runData,
1566 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1567 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1568 void handlePointingAtObject(GameRunData *runData,
1569 const PointedThing &pointed, const ItemStack &playeritem,
1570 const v3f &player_position, bool show_debug);
1571 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1572 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1574 void updateFrame(ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
1575 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1576 void updateGui(float *statustext_time, const RunStats &stats,
1577 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1578 const CameraOrientation &cam);
1579 void updateProfilerGraphs(ProfilerGraph *graph);
1582 void limitFps(FpsControl *fps_timings, f32 *dtime);
1584 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1585 bool draw_clouds = true);
1587 static void settingChangedCallback(const std::string &setting_name, void *data);
1588 void readSettings();
1591 InputHandler *input;
1596 IWritableTextureSource *texture_src;
1597 IWritableShaderSource *shader_src;
1599 // When created, these will be filled with data received from the server
1600 IWritableItemDefManager *itemdef_manager;
1601 IWritableNodeDefManager *nodedef_manager;
1603 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1604 ISoundManager *sound;
1605 bool sound_is_dummy;
1606 SoundMaker *soundmaker;
1608 ChatBackend *chat_backend;
1610 GUIFormSpecMenu *current_formspec;
1612 EventManager *eventmgr;
1613 QuicktuneShortcutter *quicktune;
1615 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1616 MapDrawControl *draw_control;
1618 Clouds *clouds; // Free using ->Drop()
1619 Sky *sky; // Free using ->Drop()
1620 Inventory *local_inventory;
1625 This class does take ownership/responsibily for cleaning up etc of any of
1626 these items (e.g. device)
1628 IrrlichtDevice *device;
1629 video::IVideoDriver *driver;
1630 scene::ISceneManager *smgr;
1632 std::string *error_message;
1633 bool *reconnect_requested;
1634 IGameDef *gamedef; // Convenience (same as *client)
1635 scene::ISceneNode *skybox;
1638 bool simple_singleplayer_mode;
1641 /* Pre-calculated values
1643 int crack_animation_length;
1647 gui::IGUIStaticText *guitext; // First line of debug text
1648 gui::IGUIStaticText *guitext2; // Second line of debug text
1649 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1650 gui::IGUIStaticText *guitext_status;
1651 gui::IGUIStaticText *guitext_chat; // Chat text
1652 gui::IGUIStaticText *guitext_profiler; // Profiler text
1654 std::wstring infotext;
1655 std::wstring statustext;
1659 IntervalLimiter profiler_interval;
1662 * TODO: Local caching of settings is not optimal and should at some stage
1663 * be updated to use a global settings object for getting thse values
1664 * (as opposed to the this local caching). This can be addressed in
1667 bool m_cache_doubletap_jump;
1668 bool m_cache_enable_clouds;
1669 bool m_cache_enable_particles;
1670 bool m_cache_enable_fog;
1671 f32 m_cache_mouse_sensitivity;
1672 f32 m_repeat_right_click_time;
1675 bool m_cache_hold_aux1;
1685 itemdef_manager(NULL),
1686 nodedef_manager(NULL),
1688 sound_is_dummy(false),
1691 current_formspec(NULL),
1694 gui_chat_console(NULL),
1699 local_inventory(NULL),
1703 g_settings->registerChangedCallback("doubletap_jump",
1704 &settingChangedCallback, this);
1705 g_settings->registerChangedCallback("enable_clouds",
1706 &settingChangedCallback, this);
1707 g_settings->registerChangedCallback("enable_particles",
1708 &settingChangedCallback, this);
1709 g_settings->registerChangedCallback("enable_fog",
1710 &settingChangedCallback, this);
1711 g_settings->registerChangedCallback("mouse_sensitivity",
1712 &settingChangedCallback, this);
1713 g_settings->registerChangedCallback("repeat_rightclick_time",
1714 &settingChangedCallback, this);
1719 m_cache_hold_aux1 = false; // This is initialised properly later
1726 /****************************************************************************
1728 ****************************************************************************/
1734 if (!sound_is_dummy)
1737 delete server; // deleted first to stop all server threads
1740 delete local_inventory;
1746 delete nodedef_manager;
1747 delete itemdef_manager;
1748 delete draw_control;
1750 extendedResourceCleanup();
1752 g_settings->deregisterChangedCallback("doubletap_jump",
1753 &settingChangedCallback, this);
1754 g_settings->deregisterChangedCallback("enable_clouds",
1755 &settingChangedCallback, this);
1756 g_settings->deregisterChangedCallback("enable_particles",
1757 &settingChangedCallback, this);
1758 g_settings->deregisterChangedCallback("enable_fog",
1759 &settingChangedCallback, this);
1760 g_settings->deregisterChangedCallback("mouse_sensitivity",
1761 &settingChangedCallback, this);
1762 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1763 &settingChangedCallback, this);
1766 bool Game::startup(bool *kill,
1768 InputHandler *input,
1769 IrrlichtDevice *device,
1770 const std::string &map_dir,
1771 const std::string &playername,
1772 const std::string &password,
1773 std::string *address, // can change if simple_singleplayer_mode
1775 std::string &error_message,
1777 ChatBackend *chat_backend,
1778 const SubgameSpec &gamespec,
1779 bool simple_singleplayer_mode)
1782 this->device = device;
1784 this->error_message = &error_message;
1785 this->reconnect_requested = reconnect;
1786 this->random_input = random_input;
1787 this->input = input;
1788 this->chat_backend = chat_backend;
1789 this->simple_singleplayer_mode = simple_singleplayer_mode;
1791 driver = device->getVideoDriver();
1792 smgr = device->getSceneManager();
1794 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1796 if (!init(map_dir, address, port, gamespec))
1799 if (!createClient(playername, password, address, port))
1808 ProfilerGraph graph;
1809 RunStats stats = { 0 };
1810 CameraOrientation cam_view_target = { 0 };
1811 CameraOrientation cam_view = { 0 };
1812 GameRunData runData = { 0 };
1813 FpsControl draw_times = { 0 };
1814 VolatileRunFlags flags = { 0 };
1815 f32 dtime; // in seconds
1817 runData.time_from_last_punch = 10.0;
1818 runData.profiler_max_page = 3;
1819 runData.update_wielded_item_trigger = true;
1821 flags.show_chat = true;
1822 flags.show_hud = true;
1823 flags.show_minimap = g_settings->getBool("enable_minimap");
1824 flags.show_debug = g_settings->getBool("show_debug");
1825 flags.invert_mouse = g_settings->getBool("invert_mouse");
1826 flags.first_loop_after_window_activation = true;
1828 /* Clear the profiler */
1829 Profiler::GraphValues dummyvalues;
1830 g_profiler->graphGet(dummyvalues);
1832 draw_times.last_time = device->getTimer()->getTime();
1834 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1836 &flags.force_fog_off,
1840 set_light_table(g_settings->getFloat("display_gamma"));
1843 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1844 && client->checkPrivilege("fast");
1847 while (device->run()
1848 && !(*kill || g_gamecallback->shutdown_requested
1849 || (server && server->getShutdownRequested()))) {
1851 /* Must be called immediately after a device->run() call because it
1852 * uses device->getTimer()->getTime()
1854 limitFps(&draw_times, &dtime);
1856 updateStats(&stats, draw_times, dtime);
1857 updateInteractTimers(&runData, dtime);
1859 if (!checkConnection())
1861 if (!handleCallbacks())
1867 hud->resizeHotbar();
1869 updateProfilers(runData, stats, draw_times, dtime);
1870 processUserInput(&flags, &runData, dtime);
1871 // Update camera before player movement to avoid camera lag of one frame
1872 updateCameraDirection(&cam_view_target, &flags);
1873 float cam_smoothing = 0;
1874 if (g_settings->getBool("cinematic"))
1875 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1877 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1878 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1879 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1880 cam_view.camera_yaw) * cam_smoothing;
1881 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1882 cam_view.camera_pitch) * cam_smoothing;
1883 updatePlayerControl(cam_view);
1885 processClientEvents(&cam_view_target, &runData.damage_flash);
1886 updateCamera(&flags, draw_times.busy_time, dtime,
1887 runData.time_from_last_punch);
1889 processPlayerInteraction(&runData, dtime, flags.show_hud,
1891 updateFrame(&graph, &stats, &runData, dtime, flags, cam_view);
1892 updateProfilerGraphs(&graph);
1894 // Update if minimap has been disabled by the server
1895 flags.show_minimap &= !client->isMinimapDisabledByServer();
1900 void Game::shutdown()
1902 if (g_settings->get("3d_mode") == "pageflip") {
1903 driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS);
1906 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1911 if (gui_chat_console)
1912 gui_chat_console->drop();
1918 while (g_menumgr.menuCount() > 0) {
1919 g_menumgr.m_stack.front()->setVisible(false);
1920 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1923 if (current_formspec) {
1924 current_formspec->drop();
1925 current_formspec = NULL;
1928 chat_backend->addMessage(L"", L"# Disconnected.");
1929 chat_backend->addMessage(L"", L"");
1933 while (!client->isShutdown()) {
1934 assert(texture_src != NULL);
1935 assert(shader_src != NULL);
1936 texture_src->processQueue();
1937 shader_src->processQueue();
1944 /****************************************************************************/
1945 /****************************************************************************
1947 ****************************************************************************/
1948 /****************************************************************************/
1951 const std::string &map_dir,
1952 std::string *address,
1954 const SubgameSpec &gamespec)
1956 showOverlayMessage(wgettext("Loading..."), 0, 0);
1958 texture_src = createTextureSource(device);
1959 shader_src = createShaderSource(device);
1961 itemdef_manager = createItemDefManager();
1962 nodedef_manager = createNodeDefManager();
1964 eventmgr = new EventManager();
1965 quicktune = new QuicktuneShortcutter();
1967 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1968 && eventmgr && quicktune))
1974 // Create a server if not connecting to an existing one
1975 if (*address == "") {
1976 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1983 bool Game::initSound()
1986 if (g_settings->getBool("enable_sound")) {
1987 infostream << "Attempting to use OpenAL audio" << std::endl;
1988 sound = createOpenALSoundManager(&soundfetcher);
1990 infostream << "Failed to initialize OpenAL audio" << std::endl;
1992 infostream << "Sound disabled." << std::endl;
1996 infostream << "Using dummy audio." << std::endl;
1997 sound = &dummySoundManager;
1998 sound_is_dummy = true;
2001 soundmaker = new SoundMaker(sound, nodedef_manager);
2005 soundmaker->registerReceiver(eventmgr);
2010 bool Game::createSingleplayerServer(const std::string map_dir,
2011 const SubgameSpec &gamespec, u16 port, std::string *address)
2013 showOverlayMessage(wgettext("Creating server..."), 0, 5);
2015 std::string bind_str = g_settings->get("bind_address");
2016 Address bind_addr(0, 0, 0, 0, port);
2018 if (g_settings->getBool("ipv6_server")) {
2019 bind_addr.setAddress((IPv6AddressBytes *) NULL);
2023 bind_addr.Resolve(bind_str.c_str());
2024 } catch (ResolveError &e) {
2025 infostream << "Resolving bind address \"" << bind_str
2026 << "\" failed: " << e.what()
2027 << " -- Listening on all addresses." << std::endl;
2030 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2031 *error_message = "Unable to listen on " +
2032 bind_addr.serializeString() +
2033 " because IPv6 is disabled";
2034 errorstream << *error_message << std::endl;
2038 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2039 bind_addr.isIPv6());
2041 server->start(bind_addr);
2046 bool Game::createClient(const std::string &playername,
2047 const std::string &password, std::string *address, u16 port)
2049 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2051 draw_control = new MapDrawControl;
2055 bool could_connect, connect_aborted;
2057 if (!connectToServer(playername, password, address, port,
2058 &could_connect, &connect_aborted))
2061 if (!could_connect) {
2062 if (error_message->empty() && !connect_aborted) {
2063 // Should not happen if error messages are set properly
2064 *error_message = "Connection failed for unknown reason";
2065 errorstream << *error_message << std::endl;
2070 if (!getServerContent(&connect_aborted)) {
2071 if (error_message->empty() && !connect_aborted) {
2072 // Should not happen if error messages are set properly
2073 *error_message = "Connection failed for unknown reason";
2074 errorstream << *error_message << std::endl;
2079 // Update cached textures, meshes and materials
2080 client->afterContentReceived(device);
2084 camera = new Camera(smgr, *draw_control, gamedef);
2085 if (!camera || !camera->successfullyCreated(*error_message))
2090 if (m_cache_enable_clouds) {
2091 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2093 *error_message = "Memory allocation error (clouds)";
2094 errorstream << *error_message << std::endl;
2101 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2102 skybox = NULL; // This is used/set later on in the main run loop
2104 local_inventory = new Inventory(itemdef_manager);
2106 if (!(sky && local_inventory)) {
2107 *error_message = "Memory allocation error (sky or local inventory)";
2108 errorstream << *error_message << std::endl;
2112 /* Pre-calculated values
2114 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2116 v2u32 size = t->getOriginalSize();
2117 crack_animation_length = size.Y / size.X;
2119 crack_animation_length = 5;
2125 /* Set window caption
2127 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2129 str += driver->getName();
2131 device->setWindowCaption(str.c_str());
2133 LocalPlayer *player = client->getEnv().getLocalPlayer();
2134 player->hurt_tilt_timer = 0;
2135 player->hurt_tilt_strength = 0;
2137 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2140 *error_message = "Memory error: could not create HUD";
2141 errorstream << *error_message << std::endl;
2145 mapper = client->getMapper();
2146 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2151 bool Game::initGui()
2153 // First line of debug text
2154 guitext = guienv->addStaticText(
2155 utf8_to_wide(PROJECT_NAME_C).c_str(),
2156 core::rect<s32>(0, 0, 0, 0),
2157 false, false, guiroot);
2159 // Second line of debug text
2160 guitext2 = guienv->addStaticText(
2162 core::rect<s32>(0, 0, 0, 0),
2163 false, false, guiroot);
2165 // At the middle of the screen
2166 // Object infos are shown in this
2167 guitext_info = guienv->addStaticText(
2169 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2170 false, true, guiroot);
2172 // Status text (displays info when showing and hiding GUI stuff, etc.)
2173 guitext_status = guienv->addStaticText(
2175 core::rect<s32>(0, 0, 0, 0),
2176 false, false, guiroot);
2177 guitext_status->setVisible(false);
2180 guitext_chat = guienv->addStaticText(
2182 core::rect<s32>(0, 0, 0, 0),
2183 //false, false); // Disable word wrap as of now
2184 false, true, guiroot);
2185 // Remove stale "recent" chat messages from previous connections
2186 chat_backend->clearRecentChat();
2188 // Chat backend and console
2189 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2190 -1, chat_backend, client);
2191 if (!gui_chat_console) {
2192 *error_message = "Could not allocate memory for chat console";
2193 errorstream << *error_message << std::endl;
2197 // Profiler text (size is updated when text is updated)
2198 guitext_profiler = guienv->addStaticText(
2200 core::rect<s32>(0, 0, 0, 0),
2201 false, false, guiroot);
2202 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2203 guitext_profiler->setVisible(false);
2204 guitext_profiler->setWordWrap(true);
2206 #ifdef HAVE_TOUCHSCREENGUI
2208 if (g_touchscreengui)
2209 g_touchscreengui->init(texture_src);
2216 bool Game::connectToServer(const std::string &playername,
2217 const std::string &password, std::string *address, u16 port,
2218 bool *connect_ok, bool *aborted)
2220 *connect_ok = false; // Let's not be overly optimistic
2222 bool local_server_mode = false;
2224 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2226 Address connect_address(0, 0, 0, 0, port);
2229 connect_address.Resolve(address->c_str());
2231 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2232 //connect_address.Resolve("localhost");
2233 if (connect_address.isIPv6()) {
2234 IPv6AddressBytes addr_bytes;
2235 addr_bytes.bytes[15] = 1;
2236 connect_address.setAddress(&addr_bytes);
2238 connect_address.setAddress(127, 0, 0, 1);
2240 local_server_mode = true;
2242 } catch (ResolveError &e) {
2243 *error_message = std::string("Couldn't resolve address: ") + e.what();
2244 errorstream << *error_message << std::endl;
2248 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2249 *error_message = "Unable to connect to " +
2250 connect_address.serializeString() +
2251 " because IPv6 is disabled";
2252 errorstream << *error_message << std::endl;
2256 client = new Client(device,
2257 playername.c_str(), password,
2258 *draw_control, texture_src, shader_src,
2259 itemdef_manager, nodedef_manager, sound, eventmgr,
2260 connect_address.isIPv6());
2265 gamedef = client; // Client acts as our GameDef
2267 infostream << "Connecting to server at ";
2268 connect_address.print(&infostream);
2269 infostream << std::endl;
2271 client->connect(connect_address, *address,
2272 simple_singleplayer_mode || local_server_mode);
2275 Wait for server to accept connection
2281 FpsControl fps_control = { 0 };
2283 f32 wait_time = 0; // in seconds
2285 fps_control.last_time = device->getTimer()->getTime();
2287 while (device->run()) {
2289 limitFps(&fps_control, &dtime);
2291 // Update client and server
2292 client->step(dtime);
2295 server->step(dtime);
2298 if (client->getState() == LC_Init) {
2304 if (client->accessDenied()) {
2305 *error_message = "Access denied. Reason: "
2306 + client->accessDeniedReason();
2307 *reconnect_requested = client->reconnectRequested();
2308 errorstream << *error_message << std::endl;
2312 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2314 infostream << "Connect aborted [Escape]" << std::endl;
2319 // Only time out if we aren't waiting for the server we started
2320 if ((*address != "") && (wait_time > 10)) {
2321 *error_message = "Connection timed out.";
2322 errorstream << *error_message << std::endl;
2327 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2329 } catch (con::PeerNotFoundException &e) {
2330 // TODO: Should something be done here? At least an info/error
2338 bool Game::getServerContent(bool *aborted)
2342 FpsControl fps_control = { 0 };
2343 f32 dtime; // in seconds
2345 fps_control.last_time = device->getTimer()->getTime();
2347 while (device->run()) {
2349 limitFps(&fps_control, &dtime);
2351 // Update client and server
2352 client->step(dtime);
2355 server->step(dtime);
2358 if (client->mediaReceived() && client->itemdefReceived() &&
2359 client->nodedefReceived()) {
2364 if (!checkConnection())
2367 if (client->getState() < LC_Init) {
2368 *error_message = "Client disconnected";
2369 errorstream << *error_message << std::endl;
2373 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2375 infostream << "Connect aborted [Escape]" << std::endl;
2382 if (!client->itemdefReceived()) {
2383 const wchar_t *text = wgettext("Item definitions...");
2385 draw_load_screen(text, device, guienv, dtime, progress);
2387 } else if (!client->nodedefReceived()) {
2388 const wchar_t *text = wgettext("Node definitions...");
2390 draw_load_screen(text, device, guienv, dtime, progress);
2393 std::stringstream message;
2394 message.precision(3);
2395 message << gettext("Media...");
2397 if ((USE_CURL == 0) ||
2398 (!g_settings->getBool("enable_remote_media_server"))) {
2399 float cur = client->getCurRate();
2400 std::string cur_unit = gettext("KiB/s");
2404 cur_unit = gettext("MiB/s");
2407 message << " (" << cur << ' ' << cur_unit << ")";
2410 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2411 draw_load_screen(utf8_to_wide(message.str()), device,
2412 guienv, dtime, progress);
2420 /****************************************************************************/
2421 /****************************************************************************
2423 ****************************************************************************/
2424 /****************************************************************************/
2426 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2428 if (runData->nodig_delay_timer >= 0)
2429 runData->nodig_delay_timer -= dtime;
2431 if (runData->object_hit_delay_timer >= 0)
2432 runData->object_hit_delay_timer -= dtime;
2434 runData->time_from_last_punch += dtime;
2438 /* returns false if game should exit, otherwise true
2440 inline bool Game::checkConnection()
2442 if (client->accessDenied()) {
2443 *error_message = "Access denied. Reason: "
2444 + client->accessDeniedReason();
2445 *reconnect_requested = client->reconnectRequested();
2446 errorstream << *error_message << std::endl;
2454 /* returns false if game should exit, otherwise true
2456 inline bool Game::handleCallbacks()
2458 if (g_gamecallback->disconnect_requested) {
2459 g_gamecallback->disconnect_requested = false;
2463 if (g_gamecallback->changepassword_requested) {
2464 (new GUIPasswordChange(guienv, guiroot, -1,
2465 &g_menumgr, client))->drop();
2466 g_gamecallback->changepassword_requested = false;
2469 if (g_gamecallback->changevolume_requested) {
2470 (new GUIVolumeChange(guienv, guiroot, -1,
2471 &g_menumgr, client))->drop();
2472 g_gamecallback->changevolume_requested = false;
2475 if (g_gamecallback->keyconfig_requested) {
2476 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2477 &g_menumgr))->drop();
2478 g_gamecallback->keyconfig_requested = false;
2481 if (g_gamecallback->keyconfig_changed) {
2482 keycache.populate(); // update the cache with new settings
2483 g_gamecallback->keyconfig_changed = false;
2490 void Game::processQueues()
2492 texture_src->processQueue();
2493 itemdef_manager->processQueue(gamedef);
2494 shader_src->processQueue();
2498 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2499 const FpsControl &draw_times, f32 dtime)
2501 float profiler_print_interval =
2502 g_settings->getFloat("profiler_print_interval");
2503 bool print_to_log = true;
2505 if (profiler_print_interval == 0) {
2506 print_to_log = false;
2507 profiler_print_interval = 5;
2510 if (profiler_interval.step(dtime, profiler_print_interval)) {
2512 infostream << "Profiler:" << std::endl;
2513 g_profiler->print(infostream);
2516 update_profiler_gui(guitext_profiler, g_fontengine,
2517 runData.profiler_current_page, runData.profiler_max_page,
2518 driver->getScreenSize().Height);
2520 g_profiler->clear();
2523 addProfilerGraphs(stats, draw_times, dtime);
2527 void Game::addProfilerGraphs(const RunStats &stats,
2528 const FpsControl &draw_times, f32 dtime)
2530 g_profiler->graphAdd("mainloop_other",
2531 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2533 if (draw_times.sleep_time != 0)
2534 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2535 g_profiler->graphAdd("mainloop_dtime", dtime);
2537 g_profiler->add("Elapsed time", dtime);
2538 g_profiler->avg("FPS", 1. / dtime);
2542 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2549 /* Time average and jitter calculation
2551 jp = &stats->dtime_jitter;
2552 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2554 jitter = dtime - jp->avg;
2556 if (jitter > jp->max)
2559 jp->counter += dtime;
2561 if (jp->counter > 0.0) {
2563 jp->max_sample = jp->max;
2564 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2568 /* Busytime average and jitter calculation
2570 jp = &stats->busy_time_jitter;
2571 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2573 jitter = draw_times.busy_time - jp->avg;
2575 if (jitter > jp->max)
2577 if (jitter < jp->min)
2580 jp->counter += dtime;
2582 if (jp->counter > 0.0) {
2584 jp->max_sample = jp->max;
2585 jp->min_sample = jp->min;
2593 /****************************************************************************
2595 ****************************************************************************/
2597 void Game::processUserInput(VolatileRunFlags *flags,
2598 GameRunData *runData, f32 dtime)
2600 // Reset input if window not active or some menu is active
2601 if (device->isWindowActive() == false
2602 || noMenuActive() == false
2603 || guienv->hasFocus(gui_chat_console)) {
2605 #ifdef HAVE_TOUCHSCREENGUI
2606 g_touchscreengui->hide();
2609 #ifdef HAVE_TOUCHSCREENGUI
2610 else if (g_touchscreengui) {
2611 /* on touchscreengui step may generate own input events which ain't
2612 * what we want in case we just did clear them */
2613 g_touchscreengui->step(dtime);
2617 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2618 gui_chat_console->closeConsoleAtOnce();
2621 // Input handler step() (used by the random input generator)
2626 if (current_formspec != 0)
2627 current_formspec->getAndroidUIInput();
2631 // Increase timer for double tap of "keymap_jump"
2632 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2633 runData->jump_timer += dtime;
2635 processKeyboardInput(
2637 &runData->statustext_time,
2638 &runData->jump_timer,
2639 &runData->reset_jump_timer,
2640 &runData->profiler_current_page,
2641 runData->profiler_max_page);
2643 processItemSelection(&runData->new_playeritem);
2647 void Game::processKeyboardInput(VolatileRunFlags *flags,
2648 float *statustext_time,
2650 bool *reset_jump_timer,
2651 u32 *profiler_current_page,
2652 u32 profiler_max_page)
2655 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2657 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2659 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_AUTORUN])) {
2660 toggleAutorun(statustext_time);
2661 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2663 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2664 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2665 simple_singleplayer_mode);
2666 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2667 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2669 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2670 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2672 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2674 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2675 toggleFreeMove(statustext_time);
2676 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2677 toggleFreeMoveAlt(statustext_time, jump_timer);
2678 *reset_jump_timer = true;
2679 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2680 toggleFast(statustext_time);
2681 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2682 toggleNoClip(statustext_time);
2683 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2684 toggleCinematic(statustext_time);
2685 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2686 client->makeScreenshot(device);
2687 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2688 toggleHud(statustext_time, &flags->show_hud);
2689 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_MINIMAP])) {
2690 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2691 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]));
2692 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2693 toggleChat(statustext_time, &flags->show_chat);
2694 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2695 toggleFog(statustext_time, &flags->force_fog_off);
2696 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2697 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2698 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2699 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2700 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2701 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2702 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2703 increaseViewRange(statustext_time);
2704 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2705 decreaseViewRange(statustext_time);
2706 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2707 toggleFullViewRange(statustext_time);
2708 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2710 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2712 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2714 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2716 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2717 // Print debug stacks
2718 dstream << "-----------------------------------------"
2720 dstream << "Printing debug stacks:" << std::endl;
2721 dstream << "-----------------------------------------"
2723 debug_stacks_print();
2726 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2727 *reset_jump_timer = false;
2733 if (quicktune->hasMessage()) {
2734 std::string msg = quicktune->getMessage();
2735 statustext = utf8_to_wide(msg);
2736 *statustext_time = 0;
2741 void Game::processItemSelection(u16 *new_playeritem)
2743 LocalPlayer *player = client->getEnv().getLocalPlayer();
2745 /* Item selection using mouse wheel
2747 *new_playeritem = client->getPlayerItem();
2749 s32 wheel = input->getMouseWheel();
2750 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2751 player->hud_hotbar_itemcount - 1);
2754 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2756 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2760 /* Item selection using keyboard
2762 for (u16 i = 0; i < 10; i++) {
2763 static const KeyPress *item_keys[10] = {
2764 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2765 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2766 NumberKey + 9, NumberKey + 0,
2769 if (input->wasKeyDown(*item_keys[i])) {
2770 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2771 *new_playeritem = i;
2772 infostream << "Selected item: " << new_playeritem << std::endl;
2780 void Game::dropSelectedItem()
2782 IDropAction *a = new IDropAction();
2784 a->from_inv.setCurrentPlayer();
2785 a->from_list = "main";
2786 a->from_i = client->getPlayerItem();
2787 client->inventoryAction(a);
2791 void Game::openInventory()
2794 * Don't permit to open inventory is CAO or player doesn't exists.
2795 * This prevent showing an empty inventory at player load
2798 LocalPlayer *player = client->getEnv().getLocalPlayer();
2799 if (player == NULL || player->getCAO() == NULL)
2802 infostream << "the_game: " << "Launching inventory" << std::endl;
2804 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2805 TextDest *txt_dst = new TextDestPlayerInventory(client);
2807 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2808 device, fs_src, txt_dst, client);
2810 InventoryLocation inventoryloc;
2811 inventoryloc.setCurrentPlayer();
2812 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2816 void Game::openConsole()
2818 if (!gui_chat_console->isOpenInhibited()) {
2819 // Open up to over half of the screen
2820 gui_chat_console->openConsole(0.6);
2821 guienv->setFocus(gui_chat_console);
2826 void Game::toggleFreeMove(float *statustext_time)
2828 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2830 bool free_move = !g_settings->getBool("free_move");
2831 g_settings->set("free_move", bool_to_cstr(free_move));
2833 *statustext_time = 0;
2834 statustext = msg[free_move];
2835 if (free_move && !client->checkPrivilege("fly"))
2836 statustext += L" (note: no 'fly' privilege)";
2840 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2842 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2843 toggleFreeMove(statustext_time);
2847 void Game::toggleFast(float *statustext_time)
2849 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2850 bool fast_move = !g_settings->getBool("fast_move");
2851 g_settings->set("fast_move", bool_to_cstr(fast_move));
2853 *statustext_time = 0;
2854 statustext = msg[fast_move];
2856 bool has_fast_privs = client->checkPrivilege("fast");
2858 if (fast_move && !has_fast_privs)
2859 statustext += L" (note: no 'fast' privilege)";
2862 m_cache_hold_aux1 = fast_move && has_fast_privs;
2867 void Game::toggleNoClip(float *statustext_time)
2869 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2870 bool noclip = !g_settings->getBool("noclip");
2871 g_settings->set("noclip", bool_to_cstr(noclip));
2873 *statustext_time = 0;
2874 statustext = msg[noclip];
2876 if (noclip && !client->checkPrivilege("noclip"))
2877 statustext += L" (note: no 'noclip' privilege)";
2880 void Game::toggleCinematic(float *statustext_time)
2882 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2883 bool cinematic = !g_settings->getBool("cinematic");
2884 g_settings->set("cinematic", bool_to_cstr(cinematic));
2886 *statustext_time = 0;
2887 statustext = msg[cinematic];
2890 // Add WoW-style autorun by toggling continuous forward.
2891 void Game::toggleAutorun(float *statustext_time)
2893 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2894 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2895 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2897 *statustext_time = 0;
2898 statustext = msg[autorun_enabled ? 1 : 0];
2901 void Game::toggleChat(float *statustext_time, bool *flag)
2903 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2906 *statustext_time = 0;
2907 statustext = msg[*flag];
2911 void Game::toggleHud(float *statustext_time, bool *flag)
2913 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2916 *statustext_time = 0;
2917 statustext = msg[*flag];
2920 void Game::toggleMinimap(float *statustext_time, bool *flag,
2921 bool show_hud, bool shift_pressed)
2923 if (!show_hud || !g_settings->getBool("enable_minimap"))
2926 if (shift_pressed) {
2927 mapper->toggleMinimapShape();
2931 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2933 MinimapMode mode = MINIMAP_MODE_OFF;
2934 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2935 mode = mapper->getMinimapMode();
2936 mode = (MinimapMode)((int)mode + 1);
2941 case MINIMAP_MODE_SURFACEx1:
2942 statustext = L"Minimap in surface mode, Zoom x1";
2944 case MINIMAP_MODE_SURFACEx2:
2945 statustext = L"Minimap in surface mode, Zoom x2";
2947 case MINIMAP_MODE_SURFACEx4:
2948 statustext = L"Minimap in surface mode, Zoom x4";
2950 case MINIMAP_MODE_RADARx1:
2951 statustext = L"Minimap in radar mode, Zoom x1";
2953 case MINIMAP_MODE_RADARx2:
2954 statustext = L"Minimap in radar mode, Zoom x2";
2956 case MINIMAP_MODE_RADARx4:
2957 statustext = L"Minimap in radar mode, Zoom x4";
2960 mode = MINIMAP_MODE_OFF;
2962 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2963 L"Minimap hidden" : L"Minimap disabled by server";
2966 *statustext_time = 0;
2967 mapper->setMinimapMode(mode);
2970 void Game::toggleFog(float *statustext_time, bool *flag)
2972 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2975 *statustext_time = 0;
2976 statustext = msg[*flag];
2980 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2981 bool *show_profiler_graph)
2983 // Initial / 3x toggle: Chat only
2984 // 1x toggle: Debug text with chat
2985 // 2x toggle: Debug text with profiler graph
2988 *show_profiler_graph = false;
2989 statustext = L"Debug info shown";
2990 } else if (*show_profiler_graph) {
2991 *show_debug = false;
2992 *show_profiler_graph = false;
2993 statustext = L"Debug info and profiler graph hidden";
2995 *show_profiler_graph = true;
2996 statustext = L"Profiler graph shown";
2998 *statustext_time = 0;
3002 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
3004 static const wchar_t *msg[] = {
3005 L"Camera update enabled",
3006 L"Camera update disabled"
3010 *statustext_time = 0;
3011 statustext = msg[*flag];
3015 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
3016 u32 profiler_max_page)
3018 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
3020 // FIXME: This updates the profiler with incomplete values
3021 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
3022 profiler_max_page, driver->getScreenSize().Height);
3024 if (*profiler_current_page != 0) {
3025 std::wstringstream sstr;
3026 sstr << "Profiler shown (page " << *profiler_current_page
3027 << " of " << profiler_max_page << ")";
3028 statustext = sstr.str();
3030 statustext = L"Profiler hidden";
3032 *statustext_time = 0;
3036 void Game::increaseViewRange(float *statustext_time)
3038 s16 range = g_settings->getS16("viewing_range_nodes_min");
3039 s16 range_new = range + 10;
3040 g_settings->set("viewing_range_nodes_min", itos(range_new));
3041 statustext = utf8_to_wide("Minimum viewing range changed to "
3043 *statustext_time = 0;
3047 void Game::decreaseViewRange(float *statustext_time)
3049 s16 range = g_settings->getS16("viewing_range_nodes_min");
3050 s16 range_new = range - 10;
3055 g_settings->set("viewing_range_nodes_min", itos(range_new));
3056 statustext = utf8_to_wide("Minimum viewing range changed to "
3058 *statustext_time = 0;
3062 void Game::toggleFullViewRange(float *statustext_time)
3064 static const wchar_t *msg[] = {
3065 L"Disabled full viewing range",
3066 L"Enabled full viewing range"
3069 draw_control->range_all = !draw_control->range_all;
3070 infostream << msg[draw_control->range_all] << std::endl;
3071 statustext = msg[draw_control->range_all];
3072 *statustext_time = 0;
3076 void Game::updateCameraDirection(CameraOrientation *cam,
3077 VolatileRunFlags *flags)
3079 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3082 if (!random_input) {
3083 // Mac OSX gets upset if this is set every frame
3084 if (device->getCursorControl()->isVisible())
3085 device->getCursorControl()->setVisible(false);
3089 if (flags->first_loop_after_window_activation)
3090 flags->first_loop_after_window_activation = false;
3092 updateCameraOrientation(cam, *flags);
3094 input->setMousePos((driver->getScreenSize().Width / 2),
3095 (driver->getScreenSize().Height / 2));
3099 // Mac OSX gets upset if this is set every frame
3100 if (device->getCursorControl()->isVisible() == false)
3101 device->getCursorControl()->setVisible(true);
3104 if (!flags->first_loop_after_window_activation)
3105 flags->first_loop_after_window_activation = true;
3111 void Game::updateCameraOrientation(CameraOrientation *cam,
3112 const VolatileRunFlags &flags)
3114 #ifdef HAVE_TOUCHSCREENGUI
3115 if (g_touchscreengui) {
3116 cam->camera_yaw = g_touchscreengui->getYaw();
3117 cam->camera_pitch = g_touchscreengui->getPitch();
3120 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3121 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3123 if (flags.invert_mouse
3124 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3128 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3129 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3131 #ifdef HAVE_TOUCHSCREENGUI
3135 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3139 void Game::updatePlayerControl(const CameraOrientation &cam)
3141 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3143 PlayerControl control(
3144 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
3145 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
3146 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3147 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3148 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3149 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3150 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3151 input->getLeftState(),
3152 input->getRightState(),
3158 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3159 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3160 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3161 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3162 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3163 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3164 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3165 ( (u32)(input->getLeftState() & 0x1) << 7) |
3166 ( (u32)(input->getRightState() & 0x1) << 8
3170 /* For Android, simulate holding down AUX1 (fast move) if the user has
3171 * the fast_move setting toggled on. If there is an aux1 key defined for
3172 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3175 if (m_cache_hold_aux1) {
3176 control.aux1 = control.aux1 ^ true;
3177 keypress_bits ^= ((u32)(1U << 5));
3181 client->setPlayerControl(control);
3182 LocalPlayer *player = client->getEnv().getLocalPlayer();
3183 player->keyPressed = keypress_bits;
3189 inline void Game::step(f32 *dtime)
3191 bool can_be_and_is_paused =
3192 (simple_singleplayer_mode && g_menumgr.pausesGame());
3194 if (can_be_and_is_paused) { // This is for a singleplayer server
3195 *dtime = 0; // No time passes
3197 if (server != NULL) {
3198 //TimeTaker timer("server->step(dtime)");
3199 server->step(*dtime);
3202 //TimeTaker timer("client.step(dtime)");
3203 client->step(*dtime);
3208 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3210 ClientEvent event = client->getClientEvent();
3212 LocalPlayer *player = client->getEnv().getLocalPlayer();
3214 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3216 if (event.type == CE_PLAYER_DAMAGE &&
3217 client->getHP() != 0) {
3218 //u16 damage = event.player_damage.amount;
3219 //infostream<<"Player damage: "<<damage<<std::endl;
3221 *damage_flash += 100.0;
3222 *damage_flash += 8.0 * event.player_damage.amount;
3224 player->hurt_tilt_timer = 1.5;
3225 player->hurt_tilt_strength = event.player_damage.amount / 4;
3226 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3228 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3229 gamedef->event()->put(e);
3230 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3231 cam->camera_yaw = event.player_force_move.yaw;
3232 cam->camera_pitch = event.player_force_move.pitch;
3233 } else if (event.type == CE_DEATHSCREEN) {
3234 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3237 chat_backend->addMessage(L"", L"You died.");
3239 /* Handle visualization */
3241 player->hurt_tilt_timer = 0;
3242 player->hurt_tilt_strength = 0;
3244 } else if (event.type == CE_SHOW_FORMSPEC) {
3245 FormspecFormSource *fs_src =
3246 new FormspecFormSource(*(event.show_formspec.formspec));
3247 TextDestPlayerInventory *txt_dst =
3248 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3250 create_formspec_menu(¤t_formspec, client, gamedef,
3251 texture_src, device, fs_src, txt_dst, client);
3253 delete(event.show_formspec.formspec);
3254 delete(event.show_formspec.formname);
3255 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3256 (event.type == CE_ADD_PARTICLESPAWNER) ||
3257 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3258 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3260 } else if (event.type == CE_HUDADD) {
3261 u32 id = event.hudadd.id;
3263 LocalPlayer *player = client->getEnv().getLocalPlayer();
3264 HudElement *e = player->getHud(id);
3267 delete event.hudadd.pos;
3268 delete event.hudadd.name;
3269 delete event.hudadd.scale;
3270 delete event.hudadd.text;
3271 delete event.hudadd.align;
3272 delete event.hudadd.offset;
3273 delete event.hudadd.world_pos;
3274 delete event.hudadd.size;
3279 e->type = (HudElementType)event.hudadd.type;
3280 e->pos = *event.hudadd.pos;
3281 e->name = *event.hudadd.name;
3282 e->scale = *event.hudadd.scale;
3283 e->text = *event.hudadd.text;
3284 e->number = event.hudadd.number;
3285 e->item = event.hudadd.item;
3286 e->dir = event.hudadd.dir;
3287 e->align = *event.hudadd.align;
3288 e->offset = *event.hudadd.offset;
3289 e->world_pos = *event.hudadd.world_pos;
3290 e->size = *event.hudadd.size;
3292 u32 new_id = player->addHud(e);
3293 //if this isn't true our huds aren't consistent
3294 sanity_check(new_id == id);
3296 delete event.hudadd.pos;
3297 delete event.hudadd.name;
3298 delete event.hudadd.scale;
3299 delete event.hudadd.text;
3300 delete event.hudadd.align;
3301 delete event.hudadd.offset;
3302 delete event.hudadd.world_pos;
3303 delete event.hudadd.size;
3304 } else if (event.type == CE_HUDRM) {
3305 HudElement *e = player->removeHud(event.hudrm.id);
3309 } else if (event.type == CE_HUDCHANGE) {
3310 u32 id = event.hudchange.id;
3311 HudElement *e = player->getHud(id);
3314 delete event.hudchange.v3fdata;
3315 delete event.hudchange.v2fdata;
3316 delete event.hudchange.sdata;
3317 delete event.hudchange.v2s32data;
3321 switch (event.hudchange.stat) {
3323 e->pos = *event.hudchange.v2fdata;
3327 e->name = *event.hudchange.sdata;
3330 case HUD_STAT_SCALE:
3331 e->scale = *event.hudchange.v2fdata;
3335 e->text = *event.hudchange.sdata;
3338 case HUD_STAT_NUMBER:
3339 e->number = event.hudchange.data;
3343 e->item = event.hudchange.data;
3347 e->dir = event.hudchange.data;
3350 case HUD_STAT_ALIGN:
3351 e->align = *event.hudchange.v2fdata;
3354 case HUD_STAT_OFFSET:
3355 e->offset = *event.hudchange.v2fdata;
3358 case HUD_STAT_WORLD_POS:
3359 e->world_pos = *event.hudchange.v3fdata;
3363 e->size = *event.hudchange.v2s32data;
3367 delete event.hudchange.v3fdata;
3368 delete event.hudchange.v2fdata;
3369 delete event.hudchange.sdata;
3370 delete event.hudchange.v2s32data;
3371 } else if (event.type == CE_SET_SKY) {
3372 sky->setVisible(false);
3379 // Handle according to type
3380 if (*event.set_sky.type == "regular") {
3381 sky->setVisible(true);
3382 } else if (*event.set_sky.type == "skybox" &&
3383 event.set_sky.params->size() == 6) {
3384 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3385 skybox = smgr->addSkyBoxSceneNode(
3386 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3387 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3388 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3389 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3390 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3391 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3393 // Handle everything else as plain color
3395 if (*event.set_sky.type != "plain")
3396 infostream << "Unknown sky type: "
3397 << (*event.set_sky.type) << std::endl;
3399 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3402 delete event.set_sky.bgcolor;
3403 delete event.set_sky.type;
3404 delete event.set_sky.params;
3405 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3406 bool enable = event.override_day_night_ratio.do_override;
3407 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3408 client->getEnv().setDayNightRatioOverride(enable, value);
3414 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3415 f32 dtime, float time_from_last_punch)
3417 LocalPlayer *player = client->getEnv().getLocalPlayer();
3420 For interaction purposes, get info about the held item
3422 - Is it a usable item?
3423 - Can it point to liquids?
3425 ItemStack playeritem;
3427 InventoryList *mlist = local_inventory->getList("main");
3429 if (mlist && client->getPlayerItem() < mlist->getSize())
3430 playeritem = mlist->getItem(client->getPlayerItem());
3433 ToolCapabilities playeritem_toolcap =
3434 playeritem.getToolCapabilities(itemdef_manager);
3436 v3s16 old_camera_offset = camera->getOffset();
3438 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3439 GenericCAO *playercao = player->getCAO();
3441 // If playercao not loaded, don't change camera
3442 if (playercao == NULL)
3445 camera->toggleCameraMode();
3447 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3448 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3451 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3452 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3454 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3455 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3457 camera->step(dtime);
3459 v3f camera_position = camera->getPosition();
3460 v3f camera_direction = camera->getDirection();
3461 f32 camera_fov = camera->getFovMax();
3462 v3s16 camera_offset = camera->getOffset();
3464 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3466 if (!flags->disable_camera_update) {
3467 client->getEnv().getClientMap().updateCamera(camera_position,
3468 camera_direction, camera_fov, camera_offset);
3470 if (flags->camera_offset_changed) {
3471 client->updateCameraOffset(camera_offset);
3472 client->getEnv().updateCameraOffset(camera_offset);
3475 clouds->updateCameraOffset(camera_offset);
3481 void Game::updateSound(f32 dtime)
3483 // Update sound listener
3484 v3s16 camera_offset = camera->getOffset();
3485 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3486 v3f(0, 0, 0), // velocity
3487 camera->getDirection(),
3488 camera->getCameraNode()->getUpVector());
3489 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3492 // Update sound maker
3493 soundmaker->step(dtime);
3495 LocalPlayer *player = client->getEnv().getLocalPlayer();
3497 ClientMap &map = client->getEnv().getClientMap();
3498 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3499 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3503 void Game::processPlayerInteraction(GameRunData *runData,
3504 f32 dtime, bool show_hud, bool show_debug)
3506 LocalPlayer *player = client->getEnv().getLocalPlayer();
3508 ItemStack playeritem;
3510 InventoryList *mlist = local_inventory->getList("main");
3512 if (mlist && client->getPlayerItem() < mlist->getSize())
3513 playeritem = mlist->getItem(client->getPlayerItem());
3516 const ItemDefinition &playeritem_def =
3517 playeritem.getDefinition(itemdef_manager);
3519 v3f player_position = player->getPosition();
3520 v3f camera_position = camera->getPosition();
3521 v3f camera_direction = camera->getDirection();
3522 v3s16 camera_offset = camera->getOffset();
3526 Calculate what block is the crosshair pointing to
3529 f32 d = playeritem_def.range; // max. distance
3530 f32 d_hand = itemdef_manager->get("").range;
3532 if (d < 0 && d_hand >= 0)
3537 core::line3d<f32> shootline;
3539 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3541 shootline = core::line3d<f32>(camera_position,
3542 camera_position + camera_direction * BS * (d + 1));
3545 // prevent player pointing anything in front-view
3546 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3547 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3550 #ifdef HAVE_TOUCHSCREENGUI
3552 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3553 shootline = g_touchscreengui->getShootline();
3554 shootline.start += intToFloat(camera_offset, BS);
3555 shootline.end += intToFloat(camera_offset, BS);
3560 PointedThing pointed = getPointedThing(
3562 client, hud, player_position, camera_direction,
3563 camera_position, shootline, d,
3564 playeritem_def.liquids_pointable,
3565 !runData->ldown_for_dig,
3568 runData->selected_object);
3570 if (pointed != runData->pointed_old) {
3571 infostream << "Pointing at " << pointed.dump() << std::endl;
3572 hud->updateSelectionMesh(camera_offset);
3577 - releasing left mouse button
3578 - pointing away from node
3580 if (runData->digging) {
3581 if (input->getLeftReleased()) {
3582 infostream << "Left button released"
3583 << " (stopped digging)" << std::endl;
3584 runData->digging = false;
3585 } else if (pointed != runData->pointed_old) {
3586 if (pointed.type == POINTEDTHING_NODE
3587 && runData->pointed_old.type == POINTEDTHING_NODE
3588 && pointed.node_undersurface
3589 == runData->pointed_old.node_undersurface) {
3590 // Still pointing to the same node, but a different face.
3593 infostream << "Pointing away from node"
3594 << " (stopped digging)" << std::endl;
3595 runData->digging = false;
3596 hud->updateSelectionMesh(camera_offset);
3600 if (!runData->digging) {
3601 client->interact(1, runData->pointed_old);
3602 client->setCrack(-1, v3s16(0, 0, 0));
3603 runData->dig_time = 0.0;
3607 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3608 runData->ldown_for_dig = false;
3611 runData->left_punch = false;
3613 soundmaker->m_player_leftpunch_sound.name = "";
3615 if (input->getRightState())
3616 runData->repeat_rightclick_timer += dtime;
3618 runData->repeat_rightclick_timer = 0;
3620 if (playeritem_def.usable && input->getLeftState()) {
3621 if (input->getLeftClicked())
3622 client->interact(4, pointed);
3623 } else if (pointed.type == POINTEDTHING_NODE) {
3624 ToolCapabilities playeritem_toolcap =
3625 playeritem.getToolCapabilities(itemdef_manager);
3626 handlePointingAtNode(runData, pointed, playeritem_def,
3627 playeritem_toolcap, dtime);
3628 } else if (pointed.type == POINTEDTHING_OBJECT) {
3629 handlePointingAtObject(runData, pointed, playeritem,
3630 player_position, show_debug);
3631 } else if (input->getLeftState()) {
3632 // When button is held down in air, show continuous animation
3633 runData->left_punch = true;
3634 } else if (input->getRightClicked()) {
3635 handlePointingAtNothing(runData, playeritem);
3638 runData->pointed_old = pointed;
3640 if (runData->left_punch || input->getLeftClicked())
3641 camera->setDigging(0); // left click animation
3643 input->resetLeftClicked();
3644 input->resetRightClicked();
3646 input->resetLeftReleased();
3647 input->resetRightReleased();
3651 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3653 infostream << "Right Clicked in Air" << std::endl;
3654 PointedThing fauxPointed;
3655 fauxPointed.type = POINTEDTHING_NOTHING;
3656 client->interact(5, fauxPointed);
3660 void Game::handlePointingAtNode(GameRunData *runData,
3661 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3662 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3664 v3s16 nodepos = pointed.node_undersurface;
3665 v3s16 neighbourpos = pointed.node_abovesurface;
3668 Check information text of node
3671 ClientMap &map = client->getEnv().getClientMap();
3672 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3675 infotext = utf8_to_wide(meta->getString("infotext"));
3677 MapNode n = map.getNodeNoEx(nodepos);
3679 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3680 infotext = L"Unknown node: ";
3681 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3685 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3686 && client->checkPrivilege("interact")) {
3687 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3690 if ((input->getRightClicked() ||
3691 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3692 client->checkPrivilege("interact")) {
3693 runData->repeat_rightclick_timer = 0;
3694 infostream << "Ground right-clicked" << std::endl;
3696 if (meta && meta->getString("formspec") != "" && !random_input
3697 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3698 infostream << "Launching custom inventory view" << std::endl;
3700 InventoryLocation inventoryloc;
3701 inventoryloc.setNodeMeta(nodepos);
3703 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3704 &client->getEnv().getClientMap(), nodepos);
3705 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3707 create_formspec_menu(¤t_formspec, client, gamedef,
3708 texture_src, device, fs_src, txt_dst, client);
3710 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3712 // Report right click to server
3714 camera->setDigging(1); // right click animation (always shown for feedback)
3716 // If the wielded item has node placement prediction,
3718 bool placed = nodePlacementPrediction(*client,
3720 nodepos, neighbourpos);
3724 client->interact(3, pointed);
3726 soundmaker->m_player_rightpunch_sound =
3727 playeritem_def.sound_place;
3729 soundmaker->m_player_rightpunch_sound =
3732 if (playeritem_def.node_placement_prediction == "" ||
3733 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3734 client->interact(3, pointed); // Report to server
3736 soundmaker->m_player_rightpunch_sound =
3737 playeritem_def.sound_place_failed;
3745 void Game::handlePointingAtObject(GameRunData *runData,
3746 const PointedThing &pointed,
3747 const ItemStack &playeritem,
3748 const v3f &player_position,
3751 infotext = utf8_to_wide(runData->selected_object->infoText());
3754 if (infotext != L"") {
3757 infotext += utf8_to_wide(runData->selected_object->debugInfoText());
3760 if (input->getLeftState()) {
3761 bool do_punch = false;
3762 bool do_punch_damage = false;
3764 if (runData->object_hit_delay_timer <= 0.0) {
3766 do_punch_damage = true;
3767 runData->object_hit_delay_timer = object_hit_delay;
3770 if (input->getLeftClicked())
3774 infostream << "Left-clicked object" << std::endl;
3775 runData->left_punch = true;
3778 if (do_punch_damage) {
3779 // Report direct punch
3780 v3f objpos = runData->selected_object->getPosition();
3781 v3f dir = (objpos - player_position).normalize();
3783 bool disable_send = runData->selected_object->directReportPunch(
3784 dir, &playeritem, runData->time_from_last_punch);
3785 runData->time_from_last_punch = 0;
3788 client->interact(0, pointed);
3790 } else if (input->getRightClicked()) {
3791 infostream << "Right-clicked object" << std::endl;
3792 client->interact(3, pointed); // place
3797 void Game::handleDigging(GameRunData *runData,
3798 const PointedThing &pointed, const v3s16 &nodepos,
3799 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3801 if (!runData->digging) {
3802 infostream << "Started digging" << std::endl;
3803 client->interact(0, pointed);
3804 runData->digging = true;
3805 runData->ldown_for_dig = true;
3808 LocalPlayer *player = client->getEnv().getLocalPlayer();
3809 ClientMap &map = client->getEnv().getClientMap();
3810 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3812 // NOTE: Similar piece of code exists on the server side for
3814 // Get digging parameters
3815 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3816 &playeritem_toolcap);
3818 // If can't dig, try hand
3819 if (!params.diggable) {
3820 const ItemDefinition &hand = itemdef_manager->get("");
3821 const ToolCapabilities *tp = hand.tool_capabilities;
3824 params = getDigParams(nodedef_manager->get(n).groups, tp);
3827 if (params.diggable == false) {
3828 // I guess nobody will wait for this long
3829 runData->dig_time_complete = 10000000.0;
3831 runData->dig_time_complete = params.time;
3833 if (m_cache_enable_particles) {
3834 const ContentFeatures &features =
3835 client->getNodeDefManager()->get(n);
3836 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3837 player, nodepos, features.tiles);
3841 if (runData->dig_time_complete >= 0.001) {
3842 runData->dig_index = (float)crack_animation_length
3844 / runData->dig_time_complete;
3846 // This is for torches
3847 runData->dig_index = crack_animation_length;
3850 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3852 if (sound_dig.exists() && params.diggable) {
3853 if (sound_dig.name == "__group") {
3854 if (params.main_group != "") {
3855 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3856 soundmaker->m_player_leftpunch_sound.name =
3857 std::string("default_dig_") +
3861 soundmaker->m_player_leftpunch_sound = sound_dig;
3865 // Don't show cracks if not diggable
3866 if (runData->dig_time_complete >= 100000.0) {
3867 } else if (runData->dig_index < crack_animation_length) {
3868 //TimeTaker timer("client.setTempMod");
3869 //infostream<<"dig_index="<<dig_index<<std::endl;
3870 client->setCrack(runData->dig_index, nodepos);
3872 infostream << "Digging completed" << std::endl;
3873 client->interact(2, pointed);
3874 client->setCrack(-1, v3s16(0, 0, 0));
3875 bool is_valid_position;
3876 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3877 if (is_valid_position)
3878 client->removeNode(nodepos);
3880 if (m_cache_enable_particles) {
3881 const ContentFeatures &features =
3882 client->getNodeDefManager()->get(wasnode);
3883 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3884 player, nodepos, features.tiles);
3887 runData->dig_time = 0;
3888 runData->digging = false;
3890 runData->nodig_delay_timer =
3891 runData->dig_time_complete / (float)crack_animation_length;
3893 // We don't want a corresponding delay to
3894 // very time consuming nodes
3895 if (runData->nodig_delay_timer > 0.3)
3896 runData->nodig_delay_timer = 0.3;
3898 // We want a slight delay to very little
3899 // time consuming nodes
3900 const float mindelay = 0.15;
3902 if (runData->nodig_delay_timer < mindelay)
3903 runData->nodig_delay_timer = mindelay;
3905 // Send event to trigger sound
3906 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3907 gamedef->event()->put(e);
3910 if (runData->dig_time_complete < 100000.0) {
3911 runData->dig_time += dtime;
3913 runData->dig_time = 0;
3914 client->setCrack(-1, nodepos);
3917 camera->setDigging(0); // left click animation
3921 void Game::updateFrame(ProfilerGraph *graph, RunStats *stats,
3922 GameRunData *runData, f32 dtime, const VolatileRunFlags &flags,
3923 const CameraOrientation &cam)
3925 LocalPlayer *player = client->getEnv().getLocalPlayer();
3931 if (draw_control->range_all) {
3932 runData->fog_range = 100000 * BS;
3934 runData->fog_range = draw_control->wanted_range * BS
3935 + 0.0 * MAP_BLOCKSIZE * BS;
3936 runData->fog_range = MYMIN(
3938 (draw_control->farthest_drawn + 20) * BS);
3939 runData->fog_range *= 0.9;
3943 Calculate general brightness
3945 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3946 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3947 float direct_brightness;
3950 if (g_settings->getBool("free_move")) {
3951 direct_brightness = time_brightness;
3952 sunlight_seen = true;
3954 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3955 float old_brightness = sky->getBrightness();
3956 direct_brightness = client->getEnv().getClientMap()
3957 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3958 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3962 float time_of_day = runData->time_of_day;
3963 float time_of_day_smooth = runData->time_of_day_smooth;
3965 time_of_day = client->getEnv().getTimeOfDayF();
3967 const float maxsm = 0.05;
3968 const float todsm = 0.05;
3970 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3971 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3972 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3973 time_of_day_smooth = time_of_day;
3975 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3976 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3977 + (time_of_day + 1.0) * todsm;
3979 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3980 + time_of_day * todsm;
3982 runData->time_of_day = time_of_day;
3983 runData->time_of_day_smooth = time_of_day_smooth;
3985 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3986 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3987 player->getPitch());
3993 v3f player_position = player->getPosition();
3994 if (sky->getCloudsVisible()) {
3995 clouds->setVisible(true);
3996 clouds->step(dtime);
3997 clouds->update(v2f(player_position.X, player_position.Z),
3998 sky->getCloudColor());
4000 clouds->setVisible(false);
4007 client->getParticleManager()->step(dtime);
4013 if (m_cache_enable_fog && !flags.force_fog_off) {
4016 video::EFT_FOG_LINEAR,
4017 runData->fog_range * 0.4,
4018 runData->fog_range * 1.0,
4026 video::EFT_FOG_LINEAR,
4036 Get chat messages from client
4039 v2u32 screensize = driver->getScreenSize();
4041 updateChat(*client, dtime, flags.show_debug, screensize,
4042 flags.show_chat, runData->profiler_current_page,
4043 *chat_backend, guitext_chat);
4049 if (client->getPlayerItem() != runData->new_playeritem)
4050 client->selectPlayerItem(runData->new_playeritem);
4052 // Update local inventory if it has changed
4053 if (client->getLocalInventoryUpdated()) {
4054 //infostream<<"Updating local inventory"<<std::endl;
4055 client->getLocalInventory(*local_inventory);
4056 runData->update_wielded_item_trigger = true;
4059 if (runData->update_wielded_item_trigger) {
4060 // Update wielded tool
4061 InventoryList *mlist = local_inventory->getList("main");
4063 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4064 ItemStack item = mlist->getItem(client->getPlayerItem());
4065 camera->wield(item);
4067 runData->update_wielded_item_trigger = false;
4071 Update block draw list every 200ms or when camera direction has
4074 runData->update_draw_list_timer += dtime;
4076 v3f camera_direction = camera->getDirection();
4077 if (runData->update_draw_list_timer >= 0.2
4078 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4079 || flags.camera_offset_changed) {
4080 runData->update_draw_list_timer = 0;
4081 client->getEnv().getClientMap().updateDrawList(driver);
4082 runData->update_draw_list_last_cam_dir = camera_direction;
4085 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4088 make sure menu is on top
4089 1. Delete formspec menu reference if menu was removed
4090 2. Else, make sure formspec menu is on top
4092 if (current_formspec) {
4093 if (current_formspec->getReferenceCount() == 1) {
4094 current_formspec->drop();
4095 current_formspec = NULL;
4096 } else if (!noMenuActive()) {
4097 guiroot->bringToFront(current_formspec);
4105 video::SColor skycolor = sky->getSkyColor();
4107 TimeTaker tt_draw("mainloop: draw");
4109 TimeTaker timer("beginScene");
4110 driver->beginScene(true, true, skycolor);
4111 stats->beginscenetime = timer.stop(true);
4114 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4115 guienv, screensize, skycolor, flags.show_hud,
4116 flags.show_minimap);
4121 if (flags.show_profiler_graph)
4122 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4127 if (runData->damage_flash > 0.0) {
4128 video::SColor color(std::min(runData->damage_flash, 180.0f),
4132 driver->draw2DRectangle(color,
4133 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4136 runData->damage_flash -= 100.0 * dtime;
4142 if (player->hurt_tilt_timer > 0.0) {
4143 player->hurt_tilt_timer -= dtime * 5;
4145 if (player->hurt_tilt_timer < 0)
4146 player->hurt_tilt_strength = 0;
4150 Update minimap pos and rotation
4152 if (flags.show_minimap && flags.show_hud) {
4153 mapper->setPos(floatToInt(player->getPosition(), BS));
4154 mapper->setAngle(player->getYaw());
4161 TimeTaker timer("endScene");
4163 stats->endscenetime = timer.stop(true);
4166 stats->drawtime = tt_draw.stop(true);
4167 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4171 inline static const char *yawToDirectionString(int yaw)
4173 // NOTE: TODO: This can be done mathematically without the else/else-if
4176 const char *player_direction;
4178 yaw = wrapDegrees_0_360(yaw);
4180 if (yaw >= 45 && yaw < 135)
4181 player_direction = "West [-X]";
4182 else if (yaw >= 135 && yaw < 225)
4183 player_direction = "South [-Z]";
4184 else if (yaw >= 225 && yaw < 315)
4185 player_direction = "East [+X]";
4187 player_direction = "North [+Z]";
4189 return player_direction;
4193 void Game::updateGui(float *statustext_time, const RunStats &stats,
4194 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4195 const CameraOrientation &cam)
4197 v2u32 screensize = driver->getScreenSize();
4198 LocalPlayer *player = client->getEnv().getLocalPlayer();
4199 v3f player_position = player->getPosition();
4201 if (flags.show_debug) {
4202 static float drawtime_avg = 0;
4203 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4205 u16 fps = 1.0 / stats.dtime_jitter.avg;
4206 //s32 fps = driver->getFPS();
4208 std::ostringstream os(std::ios_base::binary);
4210 << PROJECT_NAME_C " " << g_version_hash
4212 << " (R: range_all=" << draw_control->range_all << ")"
4213 << std::setprecision(0)
4214 << " drawtime = " << drawtime_avg
4215 << std::setprecision(1)
4216 << ", dtime_jitter = "
4217 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4218 << std::setprecision(1)
4219 << ", v_range = " << draw_control->wanted_range
4220 << std::setprecision(3)
4221 << ", RTT = " << client->getRTT();
4222 guitext->setText(utf8_to_wide(os.str()).c_str());
4223 guitext->setVisible(true);
4224 } else if (flags.show_hud || flags.show_chat) {
4225 std::ostringstream os(std::ios_base::binary);
4226 os << PROJECT_NAME_C " " << g_version_hash;
4227 guitext->setText(utf8_to_wide(os.str()).c_str());
4228 guitext->setVisible(true);
4230 guitext->setVisible(false);
4233 if (guitext->isVisible()) {
4234 core::rect<s32> rect(
4236 screensize.X, 5 + g_fontengine->getTextHeight()
4238 guitext->setRelativePosition(rect);
4241 if (flags.show_debug) {
4242 std::ostringstream os(std::ios_base::binary);
4243 os << std::setprecision(1) << std::fixed
4244 << "(" << (player_position.X / BS)
4245 << ", " << (player_position.Y / BS)
4246 << ", " << (player_position.Z / BS)
4247 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4248 << " " << yawToDirectionString(cam.camera_yaw)
4249 << ") (seed = " << ((u64)client->getMapSeed())
4252 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4253 ClientMap &map = client->getEnv().getClientMap();
4254 const INodeDefManager *nodedef = client->getNodeDefManager();
4255 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4256 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4257 const ContentFeatures &features = nodedef->get(n);
4258 os << " (pointing_at = " << nodedef->get(n).name
4259 << " - " << features.tiledef[0].name.c_str()
4264 guitext2->setText(utf8_to_wide(os.str()).c_str());
4265 guitext2->setVisible(true);
4267 core::rect<s32> rect(
4268 5, 5 + g_fontengine->getTextHeight(),
4269 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4271 guitext2->setRelativePosition(rect);
4273 guitext2->setVisible(false);
4276 guitext_info->setText(infotext.c_str());
4277 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4279 float statustext_time_max = 1.5;
4281 if (!statustext.empty()) {
4282 *statustext_time += dtime;
4284 if (*statustext_time >= statustext_time_max) {
4286 *statustext_time = 0;
4290 guitext_status->setText(statustext.c_str());
4291 guitext_status->setVisible(!statustext.empty());
4293 if (!statustext.empty()) {
4294 s32 status_width = guitext_status->getTextWidth();
4295 s32 status_height = guitext_status->getTextHeight();
4296 s32 status_y = screensize.Y - 150;
4297 s32 status_x = (screensize.X - status_width) / 2;
4298 core::rect<s32> rect(
4299 status_x , status_y - status_height,
4300 status_x + status_width, status_y
4302 guitext_status->setRelativePosition(rect);
4305 video::SColor initial_color(255, 0, 0, 0);
4307 if (guienv->getSkin())
4308 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4310 video::SColor final_color = initial_color;
4311 final_color.setAlpha(0);
4312 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4313 initial_color, final_color,
4314 pow(*statustext_time / statustext_time_max, 2.0f));
4315 guitext_status->setOverrideColor(fade_color);
4316 guitext_status->enableOverrideColor(true);
4321 /* Log times and stuff for visualization */
4322 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4324 Profiler::GraphValues values;
4325 g_profiler->graphGet(values);
4331 /****************************************************************************
4333 ****************************************************************************/
4335 /* On some computers framerate doesn't seem to be automatically limited
4337 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4339 // not using getRealTime is necessary for wine
4340 device->getTimer()->tick(); // Maker sure device time is up-to-date
4341 u32 time = device->getTimer()->getTime();
4342 u32 last_time = fps_timings->last_time;
4344 if (time > last_time) // Make sure time hasn't overflowed
4345 fps_timings->busy_time = time - last_time;
4347 fps_timings->busy_time = 0;
4349 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4350 ? g_settings->getFloat("pause_fps_max")
4351 : g_settings->getFloat("fps_max"));
4353 if (fps_timings->busy_time < frametime_min) {
4354 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4355 device->sleep(fps_timings->sleep_time);
4357 fps_timings->sleep_time = 0;
4360 /* Get the new value of the device timer. Note that device->sleep() may
4361 * not sleep for the entire requested time as sleep may be interrupted and
4362 * therefore it is arguably more accurate to get the new time from the
4363 * device rather than calculating it by adding sleep_time to time.
4366 device->getTimer()->tick(); // Update device timer
4367 time = device->getTimer()->getTime();
4369 if (time > last_time) // Make sure last_time hasn't overflowed
4370 *dtime = (time - last_time) / 1000.0;
4374 fps_timings->last_time = time;
4377 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4378 // pass a copy of it to this function
4379 // Note: \p msg must be allocated using new (not malloc())
4380 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4381 int percent, bool draw_clouds)
4383 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4387 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4389 ((Game *)data)->readSettings();
4392 void Game::readSettings()
4394 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4395 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4396 m_cache_enable_particles = g_settings->getBool("enable_particles");
4397 m_cache_enable_fog = g_settings->getBool("enable_fog");
4398 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4399 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4401 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4404 /****************************************************************************/
4405 /****************************************************************************
4407 ****************************************************************************/
4408 /****************************************************************************/
4410 void Game::extendedResourceCleanup()
4412 // Extended resource accounting
4413 infostream << "Irrlicht resources after cleanup:" << std::endl;
4414 infostream << "\tRemaining meshes : "
4415 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4416 infostream << "\tRemaining textures : "
4417 << driver->getTextureCount() << std::endl;
4419 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4420 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4421 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4425 clearTextureNameCache();
4426 infostream << "\tRemaining materials: "
4427 << driver-> getMaterialRendererCount()
4428 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4432 /****************************************************************************/
4433 /****************************************************************************
4434 extern function for launching the game
4435 ****************************************************************************/
4436 /****************************************************************************/
4438 void the_game(bool *kill,
4440 InputHandler *input,
4441 IrrlichtDevice *device,
4443 const std::string &map_dir,
4444 const std::string &playername,
4445 const std::string &password,
4446 const std::string &address, // If empty local server is created
4449 std::string &error_message,
4450 ChatBackend &chat_backend,
4451 bool *reconnect_requested,
4452 const SubgameSpec &gamespec, // Used for local game
4453 bool simple_singleplayer_mode)
4457 /* Make a copy of the server address because if a local singleplayer server
4458 * is created then this is updated and we don't want to change the value
4459 * passed to us by the calling function
4461 std::string server_address = address;
4465 if (game.startup(kill, random_input, input, device, map_dir,
4466 playername, password, &server_address, port, error_message,
4467 reconnect_requested, &chat_backend, gamespec,
4468 simple_singleplayer_mode)) {
4473 } catch (SerializationError &e) {
4474 error_message = std::string("A serialization error occurred:\n")
4475 + e.what() + "\n\nThe server is probably "
4476 " running a different version of " PROJECT_NAME_C ".";
4477 errorstream << error_message << std::endl;
4478 } catch (ServerError &e) {
4479 error_message = e.what();
4480 errorstream << "ServerError: " << error_message << std::endl;
4481 } catch (ModError &e) {
4482 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4483 errorstream << "ModError: " << error_message << std::endl;