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"
64 #include "sound_openal.h"
67 #ifdef HAVE_TOUCHSCREENGUI
68 #include "touchscreengui.h"
71 extern Settings *g_settings;
72 extern Profiler *g_profiler;
78 struct TextDestNodeMetadata : public TextDest {
79 TextDestNodeMetadata(v3s16 p, Client *client)
84 // This is deprecated I guess? -celeron55
85 void gotText(std::wstring text)
87 std::string ntext = wide_to_utf8(text);
88 infostream << "Submitting 'text' field of node at (" << m_p.X << ","
89 << m_p.Y << "," << m_p.Z << "): " << ntext << std::endl;
91 fields["text"] = ntext;
92 m_client->sendNodemetaFields(m_p, "", fields);
94 void gotText(const StringMap &fields)
96 m_client->sendNodemetaFields(m_p, "", fields);
103 struct TextDestPlayerInventory : public TextDest {
104 TextDestPlayerInventory(Client *client)
109 TextDestPlayerInventory(Client *client, std::string formname)
112 m_formname = formname;
114 void gotText(const StringMap &fields)
116 m_client->sendInventoryFields(m_formname, fields);
122 struct LocalFormspecHandler : public TextDest {
123 LocalFormspecHandler();
124 LocalFormspecHandler(std::string formname) :
127 m_formname = formname;
130 LocalFormspecHandler(std::string formname, Client *client) :
133 m_formname = formname;
136 void gotText(std::wstring message)
138 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
141 void gotText(const StringMap &fields)
143 if (m_formname == "MT_PAUSE_MENU") {
144 if (fields.find("btn_sound") != fields.end()) {
145 g_gamecallback->changeVolume();
149 if (fields.find("btn_key_config") != fields.end()) {
150 g_gamecallback->keyConfig();
154 if (fields.find("btn_exit_menu") != fields.end()) {
155 g_gamecallback->disconnect();
159 if (fields.find("btn_exit_os") != fields.end()) {
160 g_gamecallback->exitToOS();
164 if (fields.find("btn_change_password") != fields.end()) {
165 g_gamecallback->changePassword();
169 if (fields.find("quit") != fields.end()) {
173 if (fields.find("btn_continue") != fields.end()) {
178 if (m_formname == "MT_CHAT_MENU") {
179 assert(m_client != 0);
181 if ((fields.find("btn_send") != fields.end()) ||
182 (fields.find("quit") != fields.end())) {
183 StringMap::const_iterator it = fields.find("f_text");
184 if (it != fields.end())
185 m_client->typeChatMessage(utf8_to_wide(it->second));
191 if (m_formname == "MT_DEATH_SCREEN") {
192 assert(m_client != 0);
194 if ((fields.find("btn_respawn") != fields.end())) {
195 m_client->sendRespawn();
199 if (fields.find("quit") != fields.end()) {
200 m_client->sendRespawn();
205 // don't show error message for unhandled cursor keys
206 if ((fields.find("key_up") != fields.end()) ||
207 (fields.find("key_down") != fields.end()) ||
208 (fields.find("key_left") != fields.end()) ||
209 (fields.find("key_right") != fields.end())) {
213 errorstream << "LocalFormspecHandler::gotText unhandled >"
214 << m_formname << "< event" << std::endl;
217 StringMap::const_iterator it;
218 for (it = fields.begin(); it != fields.end(); ++it) {
219 errorstream << "\t" << i << ": " << it->first
220 << "=" << it->second << std::endl;
228 /* Form update callback */
230 class NodeMetadataFormSource: public IFormSource
233 NodeMetadataFormSource(ClientMap *map, v3s16 p):
238 std::string getForm()
240 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
245 return meta->getString("formspec");
247 std::string resolveText(std::string str)
249 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
254 return meta->resolveString(str);
261 class PlayerInventoryFormSource: public IFormSource
264 PlayerInventoryFormSource(Client *client):
268 std::string getForm()
270 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
271 return player->inventory_formspec;
278 Check if a node is pointable
280 inline bool isPointableNode(const MapNode &n,
281 Client *client, bool liquids_pointable)
283 const ContentFeatures &features = client->getNodeDefManager()->get(n);
284 return features.pointable ||
285 (liquids_pointable && features.isLiquid());
289 Find what the player is pointing at
291 PointedThing getPointedThing(Client *client, v3f player_position,
292 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
293 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
294 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
298 hilightboxes.clear();
299 selected_object = NULL;
301 INodeDefManager *nodedef = client->getNodeDefManager();
302 ClientMap &map = client->getEnv().getClientMap();
304 f32 mindistance = BS * 1001;
306 // First try to find a pointed at active object
307 if (look_for_object) {
308 selected_object = client->getSelectedActiveObject(d * BS,
309 camera_position, shootline);
311 if (selected_object != NULL) {
312 if (selected_object->doShowSelectionBox()) {
313 aabb3f *selection_box = selected_object->getSelectionBox();
314 // Box should exist because object was
315 // returned in the first place
316 assert(selection_box);
318 v3f pos = selected_object->getPosition();
319 hilightboxes.push_back(aabb3f(
320 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
321 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
324 mindistance = (selected_object->getPosition() - camera_position).getLength();
326 result.type = POINTEDTHING_OBJECT;
327 result.object_id = selected_object->getId();
331 // That didn't work, try to find a pointed at node
334 v3s16 pos_i = floatToInt(player_position, BS);
336 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
340 s16 ystart = pos_i.Y + 0 - (camera_direction.Y < 0 ? a : 1);
341 s16 zstart = pos_i.Z - (camera_direction.Z < 0 ? a : 1);
342 s16 xstart = pos_i.X - (camera_direction.X < 0 ? a : 1);
343 s16 yend = pos_i.Y + 1 + (camera_direction.Y > 0 ? a : 1);
344 s16 zend = pos_i.Z + (camera_direction.Z > 0 ? a : 1);
345 s16 xend = pos_i.X + (camera_direction.X > 0 ? a : 1);
347 // Prevent signed number overflow
357 for (s16 y = ystart; y <= yend; y++)
358 for (s16 z = zstart; z <= zend; z++)
359 for (s16 x = xstart; x <= xend; x++) {
361 bool is_valid_position;
363 n = map.getNodeNoEx(v3s16(x, y, z), &is_valid_position);
364 if (!is_valid_position)
367 if (!isPointableNode(n, client, liquids_pointable))
370 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
373 v3f npf = intToFloat(np, BS);
375 for (std::vector<aabb3f>::const_iterator
377 i != boxes.end(); ++i) {
382 for (u16 j = 0; j < 6; j++) {
383 v3s16 facedir = g_6dirs[j];
384 aabb3f facebox = box;
389 facebox.MinEdge.X = facebox.MaxEdge.X - d;
390 else if (facedir.X < 0)
391 facebox.MaxEdge.X = facebox.MinEdge.X + d;
392 else if (facedir.Y > 0)
393 facebox.MinEdge.Y = facebox.MaxEdge.Y - d;
394 else if (facedir.Y < 0)
395 facebox.MaxEdge.Y = facebox.MinEdge.Y + d;
396 else if (facedir.Z > 0)
397 facebox.MinEdge.Z = facebox.MaxEdge.Z - d;
398 else if (facedir.Z < 0)
399 facebox.MaxEdge.Z = facebox.MinEdge.Z + d;
401 v3f centerpoint = facebox.getCenter();
402 f32 distance = (centerpoint - camera_position).getLength();
404 if (distance >= mindistance)
407 if (!facebox.intersectsWithLine(shootline))
410 v3s16 np_above = np + facedir;
412 result.type = POINTEDTHING_NODE;
413 result.node_undersurface = np;
414 result.node_abovesurface = np_above;
415 mindistance = distance;
417 hilightboxes.clear();
419 if (!g_settings->getBool("enable_node_highlighting")) {
420 for (std::vector<aabb3f>::const_iterator
422 i2 != boxes.end(); ++i2) {
424 box.MinEdge += npf + v3f(-d, -d, -d) - intToFloat(camera_offset, BS);
425 box.MaxEdge += npf + v3f(d, d, d) - intToFloat(camera_offset, BS);
426 hilightboxes.push_back(box);
436 /* Profiler display */
438 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler, FontEngine *fe,
439 u32 show_profiler, u32 show_profiler_max, s32 screen_height)
441 if (show_profiler == 0) {
442 guitext_profiler->setVisible(false);
445 std::ostringstream os(std::ios_base::binary);
446 g_profiler->printPage(os, show_profiler, show_profiler_max);
447 std::wstring text = utf8_to_wide(os.str());
448 guitext_profiler->setText(text.c_str());
449 guitext_profiler->setVisible(true);
451 s32 w = fe->getTextWidth(text.c_str());
456 unsigned text_height = fe->getTextHeight();
458 core::position2di upper_left, lower_right;
461 upper_left.Y = (text_height + 5) * 2;
462 lower_right.X = 12 + w;
463 lower_right.Y = upper_left.Y + (text_height + 1) * MAX_PROFILER_TEXT_ROWS;
465 if (lower_right.Y > screen_height * 2 / 3)
466 lower_right.Y = screen_height * 2 / 3;
468 core::rect<s32> rect(upper_left, lower_right);
470 guitext_profiler->setRelativePosition(rect);
471 guitext_profiler->setVisible(true);
479 Profiler::GraphValues values;
485 Meta(float initial = 0,
486 video::SColor color = video::SColor(255, 255, 255, 255)):
492 std::deque<Piece> m_log;
500 void put(const Profiler::GraphValues &values)
503 piece.values = values;
504 m_log.push_back(piece);
506 while (m_log.size() > m_log_max_size)
507 m_log.erase(m_log.begin());
510 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
511 gui::IGUIFont *font) const
513 std::map<std::string, Meta> m_meta;
515 for (std::deque<Piece>::const_iterator k = m_log.begin();
516 k != m_log.end(); ++k) {
517 const Piece &piece = *k;
519 for (Profiler::GraphValues::const_iterator i = piece.values.begin();
520 i != piece.values.end(); ++i) {
521 const std::string &id = i->first;
522 const float &value = i->second;
523 std::map<std::string, Meta>::iterator j =
526 if (j == m_meta.end()) {
527 m_meta[id] = Meta(value);
531 if (value < j->second.min)
532 j->second.min = value;
534 if (value > j->second.max)
535 j->second.max = value;
540 static const video::SColor usable_colors[] = {
541 video::SColor(255, 255, 100, 100),
542 video::SColor(255, 90, 225, 90),
543 video::SColor(255, 100, 100, 255),
544 video::SColor(255, 255, 150, 50),
545 video::SColor(255, 220, 220, 100)
547 static const u32 usable_colors_count =
548 sizeof(usable_colors) / sizeof(*usable_colors);
549 u32 next_color_i = 0;
551 for (std::map<std::string, Meta>::iterator i = m_meta.begin();
552 i != m_meta.end(); ++i) {
553 Meta &meta = i->second;
554 video::SColor color(255, 200, 200, 200);
556 if (next_color_i < usable_colors_count)
557 color = usable_colors[next_color_i++];
563 s32 textx = x_left + m_log_max_size + 15;
564 s32 textx2 = textx + 200 - 15;
567 for (std::map<std::string, Meta>::const_iterator i = m_meta.begin();
568 i != m_meta.end(); ++i) {
569 const std::string &id = i->first;
570 const Meta &meta = i->second;
572 s32 y = y_bottom - meta_i * 50;
573 float show_min = meta.min;
574 float show_max = meta.max;
576 if (show_min >= -0.0001 && show_max >= -0.0001) {
577 if (show_min <= show_max * 0.5)
583 snprintf(buf, 10, "%.3g", show_max);
584 font->draw(utf8_to_wide(buf).c_str(),
585 core::rect<s32>(textx, y - graphh,
586 textx2, y - graphh + texth),
588 snprintf(buf, 10, "%.3g", show_min);
589 font->draw(utf8_to_wide(buf).c_str(),
590 core::rect<s32>(textx, y - texth,
593 font->draw(utf8_to_wide(id).c_str(),
594 core::rect<s32>(textx, y - graphh / 2 - texth / 2,
595 textx2, y - graphh / 2 + texth / 2),
598 s32 graph1h = graphh;
599 bool relativegraph = (show_min != 0 && show_min != show_max);
600 float lastscaledvalue = 0.0;
601 bool lastscaledvalue_exists = false;
603 for (std::deque<Piece>::const_iterator j = m_log.begin();
604 j != m_log.end(); ++j) {
605 const Piece &piece = *j;
607 bool value_exists = false;
608 Profiler::GraphValues::const_iterator k =
609 piece.values.find(id);
611 if (k != piece.values.end()) {
618 lastscaledvalue_exists = false;
622 float scaledvalue = 1.0;
624 if (show_max != show_min)
625 scaledvalue = (value - show_min) / (show_max - show_min);
627 if (scaledvalue == 1.0 && value == 0) {
629 lastscaledvalue_exists = false;
634 if (lastscaledvalue_exists) {
635 s32 ivalue1 = lastscaledvalue * graph1h;
636 s32 ivalue2 = scaledvalue * graph1h;
637 driver->draw2DLine(v2s32(x - 1, graph1y - ivalue1),
638 v2s32(x, graph1y - ivalue2), meta.color);
641 lastscaledvalue = scaledvalue;
642 lastscaledvalue_exists = true;
644 s32 ivalue = scaledvalue * graph1h;
645 driver->draw2DLine(v2s32(x, graph1y),
646 v2s32(x, graph1y - ivalue), meta.color);
657 class NodeDugEvent: public MtEvent
663 NodeDugEvent(v3s16 p, MapNode n):
667 const char *getType() const
675 ISoundManager *m_sound;
676 INodeDefManager *m_ndef;
678 float m_player_step_timer;
680 SimpleSoundSpec m_player_step_sound;
681 SimpleSoundSpec m_player_leftpunch_sound;
682 SimpleSoundSpec m_player_rightpunch_sound;
684 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
687 m_player_step_timer(0)
691 void playPlayerStep()
693 if (m_player_step_timer <= 0 && m_player_step_sound.exists()) {
694 m_player_step_timer = 0.03;
695 m_sound->playSound(m_player_step_sound, false);
699 static void viewBobbingStep(MtEvent *e, void *data)
701 SoundMaker *sm = (SoundMaker *)data;
702 sm->playPlayerStep();
705 static void playerRegainGround(MtEvent *e, void *data)
707 SoundMaker *sm = (SoundMaker *)data;
708 sm->playPlayerStep();
711 static void playerJump(MtEvent *e, void *data)
713 //SoundMaker *sm = (SoundMaker*)data;
716 static void cameraPunchLeft(MtEvent *e, void *data)
718 SoundMaker *sm = (SoundMaker *)data;
719 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
722 static void cameraPunchRight(MtEvent *e, void *data)
724 SoundMaker *sm = (SoundMaker *)data;
725 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
728 static void nodeDug(MtEvent *e, void *data)
730 SoundMaker *sm = (SoundMaker *)data;
731 NodeDugEvent *nde = (NodeDugEvent *)e;
732 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
735 static void playerDamage(MtEvent *e, void *data)
737 SoundMaker *sm = (SoundMaker *)data;
738 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
741 static void playerFallingDamage(MtEvent *e, void *data)
743 SoundMaker *sm = (SoundMaker *)data;
744 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
747 void registerReceiver(MtEventManager *mgr)
749 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
750 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
751 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
752 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
753 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
754 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
755 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
756 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
759 void step(float dtime)
761 m_player_step_timer -= dtime;
765 // Locally stored sounds don't need to be preloaded because of this
766 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
768 std::set<std::string> m_fetched;
770 void fetchSounds(const std::string &name,
771 std::set<std::string> &dst_paths,
772 std::set<std::string> &dst_datas)
774 if (m_fetched.count(name))
777 m_fetched.insert(name);
778 std::string base = porting::path_share + DIR_DELIM + "testsounds";
779 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
780 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
781 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
782 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
783 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
784 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
785 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
786 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
787 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
788 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
789 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
793 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
796 bool *m_force_fog_off;
802 void onSettingsChange(const std::string &name)
804 if (name == "enable_fog")
805 m_fogEnabled = g_settings->getBool("enable_fog");
808 static void SettingsCallback(const std::string &name, void *userdata)
810 reinterpret_cast<GameGlobalShaderConstantSetter*>(userdata)->onSettingsChange(name);
813 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
814 f32 *fog_range, Client *client) :
816 m_force_fog_off(force_fog_off),
817 m_fog_range(fog_range),
820 g_settings->registerChangedCallback("enable_fog", SettingsCallback, this);
821 m_fogEnabled = g_settings->getBool("enable_fog");
824 ~GameGlobalShaderConstantSetter()
826 g_settings->deregisterChangedCallback("enable_fog", SettingsCallback, this);
829 virtual void onSetConstants(video::IMaterialRendererServices *services,
836 video::SColor bgcolor = m_sky->getBgColor();
837 video::SColorf bgcolorf(bgcolor);
838 float bgcolorfa[4] = {
844 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
847 float fog_distance = 10000 * BS;
849 if (m_fogEnabled && !*m_force_fog_off)
850 fog_distance = *m_fog_range;
852 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
855 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
856 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
857 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
859 u32 animation_timer = porting::getTimeMs() % 100000;
860 float animation_timer_f = (float)animation_timer / 100000.0;
861 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
862 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
864 LocalPlayer *player = m_client->getEnv().getLocalPlayer();
865 v3f eye_position = player->getEyePosition();
866 services->setPixelShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
867 services->setVertexShaderConstant("eyePosition", (irr::f32 *)&eye_position, 3);
869 v3f minimap_yaw_vec = m_client->getMapper()->getYawVec();
870 services->setPixelShaderConstant("yawVec", (irr::f32 *)&minimap_yaw_vec, 3);
872 // Uniform sampler layers
876 // before 1.8 there isn't a "integer interface", only float
877 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
878 services->setPixelShaderConstant("baseTexture" , (irr::f32 *)&layer0, 1);
879 services->setPixelShaderConstant("normalTexture" , (irr::f32 *)&layer1, 1);
880 services->setPixelShaderConstant("textureFlags" , (irr::f32 *)&layer2, 1);
882 services->setPixelShaderConstant("baseTexture" , (irr::s32 *)&layer0, 1);
883 services->setPixelShaderConstant("normalTexture" , (irr::s32 *)&layer1, 1);
884 services->setPixelShaderConstant("textureFlags" , (irr::s32 *)&layer2, 1);
889 bool nodePlacementPrediction(Client &client,
890 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
892 std::string prediction = playeritem_def.node_placement_prediction;
893 INodeDefManager *nodedef = client.ndef();
894 ClientMap &map = client.getEnv().getClientMap();
896 bool is_valid_position;
898 node = map.getNodeNoEx(nodepos, &is_valid_position);
899 if (!is_valid_position)
902 if (prediction != "" && !nodedef->get(node).rightclickable) {
903 verbosestream << "Node placement prediction for "
904 << playeritem_def.name << " is "
905 << prediction << std::endl;
906 v3s16 p = neighbourpos;
908 // Place inside node itself if buildable_to
909 MapNode n_under = map.getNodeNoEx(nodepos, &is_valid_position);
910 if (is_valid_position)
912 if (nodedef->get(n_under).buildable_to)
915 node = map.getNodeNoEx(p, &is_valid_position);
916 if (is_valid_position &&!nodedef->get(node).buildable_to)
921 // Find id of predicted node
923 bool found = nodedef->getId(prediction, id);
926 errorstream << "Node placement prediction failed for "
927 << playeritem_def.name << " (places "
929 << ") - Name not known" << std::endl;
933 // Predict param2 for facedir and wallmounted nodes
936 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED) {
937 v3s16 dir = nodepos - neighbourpos;
939 if (abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))) {
940 param2 = dir.Y < 0 ? 1 : 0;
941 } else if (abs(dir.X) > abs(dir.Z)) {
942 param2 = dir.X < 0 ? 3 : 2;
944 param2 = dir.Z < 0 ? 5 : 4;
948 if (nodedef->get(id).param_type_2 == CPT2_FACEDIR) {
949 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
951 if (abs(dir.X) > abs(dir.Z)) {
952 param2 = dir.X < 0 ? 3 : 1;
954 param2 = dir.Z < 0 ? 2 : 0;
960 //Check attachment if node is in group attached_node
961 if (((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0) {
962 static v3s16 wallmounted_dirs[8] = {
972 if (nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
973 pp = p + wallmounted_dirs[param2];
975 pp = p + v3s16(0, -1, 0);
977 if (!nodedef->get(map.getNodeNoEx(pp)).walkable)
981 // Add node to client map
982 MapNode n(id, 0, param2);
985 LocalPlayer *player = client.getEnv().getLocalPlayer();
987 // Dont place node when player would be inside new node
988 // NOTE: This is to be eventually implemented by a mod as client-side Lua
989 if (!nodedef->get(n).walkable ||
990 g_settings->getBool("enable_build_where_you_stand") ||
991 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
992 (nodedef->get(n).walkable &&
993 neighbourpos != player->getStandingNodePos() + v3s16(0, 1, 0) &&
994 neighbourpos != player->getStandingNodePos() + v3s16(0, 2, 0))) {
996 // This triggers the required mesh update too
997 client.addNode(p, n);
1000 } catch (InvalidPositionException &e) {
1001 errorstream << "Node placement prediction failed for "
1002 << playeritem_def.name << " (places "
1004 << ") - Position not loaded" << std::endl;
1011 static inline void create_formspec_menu(GUIFormSpecMenu **cur_formspec,
1012 InventoryManager *invmgr, IGameDef *gamedef,
1013 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1014 IFormSource *fs_src, TextDest *txt_dest, Client *client)
1017 if (*cur_formspec == 0) {
1018 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
1019 invmgr, gamedef, tsrc, fs_src, txt_dest, client);
1020 (*cur_formspec)->doPause = false;
1023 Caution: do not call (*cur_formspec)->drop() here --
1024 the reference might outlive the menu, so we will
1025 periodically check if *cur_formspec is the only
1026 remaining reference (i.e. the menu was removed)
1027 and delete it in that case.
1031 (*cur_formspec)->setFormSource(fs_src);
1032 (*cur_formspec)->setTextDest(txt_dest);
1037 #define SIZE_TAG "size[11,5.5]"
1039 #define SIZE_TAG "size[11,5.5,true]" // Fixed size on desktop
1042 static void show_chat_menu(GUIFormSpecMenu **cur_formspec,
1043 InventoryManager *invmgr, IGameDef *gamedef,
1044 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1045 Client *client, std::string text)
1047 std::string formspec =
1048 FORMSPEC_VERSION_STRING
1050 "field[3,2.35;6,0.5;f_text;;" + text + "]"
1051 "button_exit[4,3;3,0.5;btn_send;" + strgettext("Proceed") + "]"
1055 /* Note: FormspecFormSource and LocalFormspecHandler
1056 * are deleted by guiFormSpecMenu */
1057 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1058 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
1060 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1063 static void show_deathscreen(GUIFormSpecMenu **cur_formspec,
1064 InventoryManager *invmgr, IGameDef *gamedef,
1065 IWritableTextureSource *tsrc, IrrlichtDevice *device, Client *client)
1067 std::string formspec =
1068 std::string(FORMSPEC_VERSION_STRING) +
1070 "bgcolor[#320000b4;true]"
1071 "label[4.85,1.35;" + gettext("You died.") + "]"
1072 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
1076 /* Note: FormspecFormSource and LocalFormspecHandler
1077 * are deleted by guiFormSpecMenu */
1078 FormspecFormSource *fs_src = new FormspecFormSource(formspec);
1079 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
1081 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1084 /******************************************************************************/
1085 static void show_pause_menu(GUIFormSpecMenu **cur_formspec,
1086 InventoryManager *invmgr, IGameDef *gamedef,
1087 IWritableTextureSource *tsrc, IrrlichtDevice *device,
1088 bool singleplayermode)
1091 std::string control_text = strgettext("Default Controls:\n"
1092 "No menu visible:\n"
1093 "- single tap: button activate\n"
1094 "- double tap: place/use\n"
1095 "- slide finger: look around\n"
1096 "Menu/Inventory visible:\n"
1097 "- double tap (outside):\n"
1099 "- touch stack, touch slot:\n"
1101 "- touch&drag, tap 2nd finger\n"
1102 " --> place single item to slot\n"
1105 std::string control_text = strgettext("Default Controls:\n"
1107 "- Space: jump/climb\n"
1108 "- Shift: sneak/go down\n"
1111 "- Mouse: turn/look\n"
1112 "- Mouse left: dig/punch\n"
1113 "- Mouse right: place/use\n"
1114 "- Mouse wheel: select item\n"
1119 float ypos = singleplayermode ? 0.5 : 0.1;
1120 std::ostringstream os;
1122 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1123 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1124 << strgettext("Continue") << "]";
1126 if (!singleplayermode) {
1127 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1128 << strgettext("Change Password") << "]";
1132 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1133 << strgettext("Sound Volume") << "]";
1134 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_key_config;"
1135 << strgettext("Change Keys") << "]";
1137 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1138 << strgettext("Exit to Menu") << "]";
1139 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1140 << strgettext("Exit to OS") << "]"
1141 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1142 << "textarea[0.4,0.25;3.5,6;;" << PROJECT_NAME_C "\n"
1143 << g_build_info << "\n"
1144 << "path_user = " << wrap_rows(porting::path_user, 20)
1148 /* Note: FormspecFormSource and LocalFormspecHandler *
1149 * are deleted by guiFormSpecMenu */
1150 FormspecFormSource *fs_src = new FormspecFormSource(os.str());
1151 LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1153 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1154 std::string con("btn_continue");
1155 (*cur_formspec)->setFocus(con);
1156 (*cur_formspec)->doPause = true;
1159 /******************************************************************************/
1160 static void updateChat(Client &client, f32 dtime, bool show_debug,
1161 const v2u32 &screensize, bool show_chat, u32 show_profiler,
1162 ChatBackend &chat_backend, gui::IGUIStaticText *guitext_chat)
1164 // Add chat log output for errors to be shown in chat
1165 static LogOutputBuffer chat_log_error_buf(g_logger, LL_ERROR);
1167 // Get new messages from error log buffer
1168 while (!chat_log_error_buf.empty()) {
1169 chat_backend.addMessage(L"", utf8_to_wide(chat_log_error_buf.get()));
1172 // Get new messages from client
1173 std::wstring message;
1175 while (client.getChatMessage(message)) {
1176 chat_backend.addUnparsedMessage(message);
1179 // Remove old messages
1180 chat_backend.step(dtime);
1182 // Display all messages in a static text element
1183 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1184 std::wstring recent_chat = chat_backend.getRecentChat();
1185 unsigned int line_height = g_fontengine->getLineHeight();
1187 guitext_chat->setText(recent_chat.c_str());
1189 // Update gui element size and position
1190 s32 chat_y = 5 + line_height;
1193 chat_y += line_height;
1195 // first pass to calculate height of text to be set
1196 s32 width = std::min(g_fontengine->getTextWidth(recent_chat) + 10,
1197 porting::getWindowSize().X - 20);
1198 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1199 guitext_chat->setRelativePosition(rect);
1201 //now use real height of text and adjust rect according to this size
1202 rect = core::rect<s32>(10, chat_y, width,
1203 chat_y + guitext_chat->getTextHeight());
1206 guitext_chat->setRelativePosition(rect);
1207 // Don't show chat if disabled or empty or profiler is enabled
1208 guitext_chat->setVisible(
1209 show_chat && recent_chat_count != 0 && !show_profiler);
1213 /****************************************************************************
1214 Fast key cache for main game loop
1215 ****************************************************************************/
1217 /* This is faster than using getKeySetting with the tradeoff that functions
1218 * using it must make sure that it's initialised before using it and there is
1219 * no error handling (for example bounds checking). This is really intended for
1220 * use only in the main running loop of the client (the_game()) where the faster
1221 * (up to 10x faster) key lookup is an asset. Other parts of the codebase
1222 * (e.g. formspecs) should continue using getKeySetting().
1226 KeyCache() { populate(); }
1241 KEYMAP_ID_INVENTORY,
1249 KEYMAP_ID_CINEMATIC,
1250 KEYMAP_ID_SCREENSHOT,
1251 KEYMAP_ID_TOGGLE_HUD,
1252 KEYMAP_ID_TOGGLE_CHAT,
1253 KEYMAP_ID_TOGGLE_FORCE_FOG_OFF,
1254 KEYMAP_ID_TOGGLE_UPDATE_CAMERA,
1255 KEYMAP_ID_TOGGLE_DEBUG,
1256 KEYMAP_ID_TOGGLE_PROFILER,
1257 KEYMAP_ID_CAMERA_MODE,
1258 KEYMAP_ID_INCREASE_VIEWING_RANGE,
1259 KEYMAP_ID_DECREASE_VIEWING_RANGE,
1260 KEYMAP_ID_RANGESELECT,
1262 KEYMAP_ID_QUICKTUNE_NEXT,
1263 KEYMAP_ID_QUICKTUNE_PREV,
1264 KEYMAP_ID_QUICKTUNE_INC,
1265 KEYMAP_ID_QUICKTUNE_DEC,
1267 KEYMAP_ID_DEBUG_STACKS,
1269 // Fake keycode for array size and internal checks
1270 KEYMAP_INTERNAL_ENUM_COUNT
1277 KeyPress key[KEYMAP_INTERNAL_ENUM_COUNT];
1280 void KeyCache::populate()
1282 key[KEYMAP_ID_FORWARD] = getKeySetting("keymap_forward");
1283 key[KEYMAP_ID_BACKWARD] = getKeySetting("keymap_backward");
1284 key[KEYMAP_ID_LEFT] = getKeySetting("keymap_left");
1285 key[KEYMAP_ID_RIGHT] = getKeySetting("keymap_right");
1286 key[KEYMAP_ID_JUMP] = getKeySetting("keymap_jump");
1287 key[KEYMAP_ID_SPECIAL1] = getKeySetting("keymap_special1");
1288 key[KEYMAP_ID_SNEAK] = getKeySetting("keymap_sneak");
1290 key[KEYMAP_ID_AUTORUN] = getKeySetting("keymap_autorun");
1292 key[KEYMAP_ID_DROP] = getKeySetting("keymap_drop");
1293 key[KEYMAP_ID_INVENTORY] = getKeySetting("keymap_inventory");
1294 key[KEYMAP_ID_CHAT] = getKeySetting("keymap_chat");
1295 key[KEYMAP_ID_CMD] = getKeySetting("keymap_cmd");
1296 key[KEYMAP_ID_CONSOLE] = getKeySetting("keymap_console");
1297 key[KEYMAP_ID_MINIMAP] = getKeySetting("keymap_minimap");
1298 key[KEYMAP_ID_FREEMOVE] = getKeySetting("keymap_freemove");
1299 key[KEYMAP_ID_FASTMOVE] = getKeySetting("keymap_fastmove");
1300 key[KEYMAP_ID_NOCLIP] = getKeySetting("keymap_noclip");
1301 key[KEYMAP_ID_CINEMATIC] = getKeySetting("keymap_cinematic");
1302 key[KEYMAP_ID_SCREENSHOT] = getKeySetting("keymap_screenshot");
1303 key[KEYMAP_ID_TOGGLE_HUD] = getKeySetting("keymap_toggle_hud");
1304 key[KEYMAP_ID_TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat");
1305 key[KEYMAP_ID_TOGGLE_FORCE_FOG_OFF]
1306 = getKeySetting("keymap_toggle_force_fog_off");
1307 key[KEYMAP_ID_TOGGLE_UPDATE_CAMERA]
1308 = getKeySetting("keymap_toggle_update_camera");
1309 key[KEYMAP_ID_TOGGLE_DEBUG]
1310 = getKeySetting("keymap_toggle_debug");
1311 key[KEYMAP_ID_TOGGLE_PROFILER]
1312 = getKeySetting("keymap_toggle_profiler");
1313 key[KEYMAP_ID_CAMERA_MODE]
1314 = getKeySetting("keymap_camera_mode");
1315 key[KEYMAP_ID_INCREASE_VIEWING_RANGE]
1316 = getKeySetting("keymap_increase_viewing_range_min");
1317 key[KEYMAP_ID_DECREASE_VIEWING_RANGE]
1318 = getKeySetting("keymap_decrease_viewing_range_min");
1319 key[KEYMAP_ID_RANGESELECT]
1320 = getKeySetting("keymap_rangeselect");
1322 key[KEYMAP_ID_QUICKTUNE_NEXT] = getKeySetting("keymap_quicktune_next");
1323 key[KEYMAP_ID_QUICKTUNE_PREV] = getKeySetting("keymap_quicktune_prev");
1324 key[KEYMAP_ID_QUICKTUNE_INC] = getKeySetting("keymap_quicktune_inc");
1325 key[KEYMAP_ID_QUICKTUNE_DEC] = getKeySetting("keymap_quicktune_dec");
1327 key[KEYMAP_ID_DEBUG_STACKS] = getKeySetting("keymap_print_debug_stacks");
1331 /****************************************************************************
1333 ****************************************************************************/
1335 const float object_hit_delay = 0.2;
1338 u32 last_time, busy_time, sleep_time;
1342 /* The reason the following structs are not anonymous structs within the
1343 * class is that they are not used by the majority of member functions and
1344 * many functions that do require objects of thse types do not modify them
1345 * (so they can be passed as a const qualified parameter)
1347 struct CameraOrientation {
1348 f32 camera_yaw; // "right/left"
1349 f32 camera_pitch; // "up/down"
1352 struct GameRunData {
1355 PointedThing pointed_old;
1359 bool update_wielded_item_trigger;
1360 bool reset_jump_timer;
1361 float nodig_delay_timer;
1363 float dig_time_complete;
1364 float repeat_rightclick_timer;
1365 float object_hit_delay_timer;
1366 float time_from_last_punch;
1367 ClientActiveObject *selected_object;
1371 float update_draw_list_timer;
1372 float statustext_time;
1376 v3f update_draw_list_last_cam_dir;
1378 u32 profiler_current_page;
1379 u32 profiler_max_page; // Number of pages
1382 float time_of_day_smooth;
1386 f32 max, min, avg, counter, max_sample, min_sample, max_fraction;
1394 Jitter dtime_jitter, busy_time_jitter;
1397 /* Flags that can, or may, change during main game loop
1399 struct VolatileRunFlags {
1406 bool show_profiler_graph;
1407 bool disable_camera_update;
1408 bool first_loop_after_window_activation;
1409 bool camera_offset_changed;
1413 /****************************************************************************
1415 ****************************************************************************/
1417 /* This is not intended to be a public class. If a public class becomes
1418 * desirable then it may be better to create another 'wrapper' class that
1419 * hides most of the stuff in this class (nothing in this class is required
1420 * by any other file) but exposes the public methods/data only.
1427 bool startup(bool *kill,
1429 InputHandler *input,
1430 IrrlichtDevice *device,
1431 const std::string &map_dir,
1432 const std::string &playername,
1433 const std::string &password,
1434 // If address is "", local server is used and address is updated
1435 std::string *address,
1437 std::string &error_message,
1439 ChatBackend *chat_backend,
1440 const SubgameSpec &gamespec, // Used for local game
1441 bool simple_singleplayer_mode);
1448 void extendedResourceCleanup();
1450 // Basic initialisation
1451 bool init(const std::string &map_dir, std::string *address,
1453 const SubgameSpec &gamespec);
1455 bool createSingleplayerServer(const std::string map_dir,
1456 const SubgameSpec &gamespec, u16 port, std::string *address);
1459 bool createClient(const std::string &playername,
1460 const std::string &password, std::string *address, u16 port);
1463 // Client connection
1464 bool connectToServer(const std::string &playername,
1465 const std::string &password, std::string *address, u16 port,
1466 bool *connect_ok, bool *aborted);
1467 bool getServerContent(bool *aborted);
1471 void updateInteractTimers(GameRunData *runData, f32 dtime);
1472 bool checkConnection();
1473 bool handleCallbacks();
1474 void processQueues();
1475 void updateProfilers(const GameRunData &runData, const RunStats &stats,
1476 const FpsControl &draw_times, f32 dtime);
1477 void addProfilerGraphs(const RunStats &stats, const FpsControl &draw_times,
1479 void updateStats(RunStats *stats, const FpsControl &draw_times, f32 dtime);
1481 void processUserInput(VolatileRunFlags *flags, GameRunData *runData,
1483 void processKeyboardInput(VolatileRunFlags *flags,
1484 float *statustext_time,
1486 bool *reset_jump_timer,
1487 u32 *profiler_current_page,
1488 u32 profiler_max_page);
1489 void processItemSelection(u16 *new_playeritem);
1491 void dropSelectedItem();
1492 void openInventory();
1494 void toggleFreeMove(float *statustext_time);
1495 void toggleFreeMoveAlt(float *statustext_time, float *jump_timer);
1496 void toggleFast(float *statustext_time);
1497 void toggleNoClip(float *statustext_time);
1498 void toggleCinematic(float *statustext_time);
1499 void toggleAutorun(float *statustext_time);
1501 void toggleChat(float *statustext_time, bool *flag);
1502 void toggleHud(float *statustext_time, bool *flag);
1503 void toggleMinimap(float *statustext_time, bool *flag, bool show_hud,
1504 bool shift_pressed);
1505 void toggleFog(float *statustext_time, bool *flag);
1506 void toggleDebug(float *statustext_time, bool *show_debug,
1507 bool *show_profiler_graph);
1508 void toggleUpdateCamera(float *statustext_time, bool *flag);
1509 void toggleProfiler(float *statustext_time, u32 *profiler_current_page,
1510 u32 profiler_max_page);
1512 void increaseViewRange(float *statustext_time);
1513 void decreaseViewRange(float *statustext_time);
1514 void toggleFullViewRange(float *statustext_time);
1516 void updateCameraDirection(CameraOrientation *cam, VolatileRunFlags *flags);
1517 void updateCameraOrientation(CameraOrientation *cam,
1518 const VolatileRunFlags &flags);
1519 void updatePlayerControl(const CameraOrientation &cam);
1520 void step(f32 *dtime);
1521 void processClientEvents(CameraOrientation *cam, float *damage_flash);
1522 void updateCamera(VolatileRunFlags *flags, u32 busy_time, f32 dtime,
1523 float time_from_last_punch);
1524 void updateSound(f32 dtime);
1525 void processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
1526 GameRunData *runData, f32 dtime, bool show_hud,
1528 void handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem);
1529 void handlePointingAtNode(GameRunData *runData,
1530 const PointedThing &pointed, const ItemDefinition &playeritem_def,
1531 const ToolCapabilities &playeritem_toolcap, f32 dtime);
1532 void handlePointingAtObject(GameRunData *runData,
1533 const PointedThing &pointed, const ItemStack &playeritem,
1534 const v3f &player_position, bool show_debug);
1535 void handleDigging(GameRunData *runData, const PointedThing &pointed,
1536 const v3s16 &nodepos, const ToolCapabilities &playeritem_toolcap,
1538 void updateFrame(std::vector<aabb3f> &highlight_boxes, ProfilerGraph *graph,
1539 RunStats *stats, GameRunData *runData,
1540 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam);
1541 void updateGui(float *statustext_time, const RunStats &stats,
1542 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
1543 const CameraOrientation &cam);
1544 void updateProfilerGraphs(ProfilerGraph *graph);
1547 void limitFps(FpsControl *fps_timings, f32 *dtime);
1549 void showOverlayMessage(const wchar_t *msg, float dtime, int percent,
1550 bool draw_clouds = true);
1552 static void settingChangedCallback(const std::string &setting_name, void *data);
1553 void readSettings();
1556 InputHandler *input;
1561 IWritableTextureSource *texture_src;
1562 IWritableShaderSource *shader_src;
1564 // When created, these will be filled with data received from the server
1565 IWritableItemDefManager *itemdef_manager;
1566 IWritableNodeDefManager *nodedef_manager;
1568 GameOnDemandSoundFetcher soundfetcher; // useful when testing
1569 ISoundManager *sound;
1570 bool sound_is_dummy;
1571 SoundMaker *soundmaker;
1573 ChatBackend *chat_backend;
1575 GUIFormSpecMenu *current_formspec;
1577 EventManager *eventmgr;
1578 QuicktuneShortcutter *quicktune;
1580 GUIChatConsole *gui_chat_console; // Free using ->Drop()
1581 MapDrawControl *draw_control;
1583 Clouds *clouds; // Free using ->Drop()
1584 Sky *sky; // Free using ->Drop()
1585 Inventory *local_inventory;
1590 This class does take ownership/responsibily for cleaning up etc of any of
1591 these items (e.g. device)
1593 IrrlichtDevice *device;
1594 video::IVideoDriver *driver;
1595 scene::ISceneManager *smgr;
1597 std::string *error_message;
1598 bool *reconnect_requested;
1599 IGameDef *gamedef; // Convenience (same as *client)
1600 scene::ISceneNode *skybox;
1603 bool simple_singleplayer_mode;
1606 /* Pre-calculated values
1608 int crack_animation_length;
1612 gui::IGUIStaticText *guitext; // First line of debug text
1613 gui::IGUIStaticText *guitext2; // Second line of debug text
1614 gui::IGUIStaticText *guitext_info; // At the middle of the screen
1615 gui::IGUIStaticText *guitext_status;
1616 gui::IGUIStaticText *guitext_chat; // Chat text
1617 gui::IGUIStaticText *guitext_profiler; // Profiler text
1619 std::wstring infotext;
1620 std::wstring statustext;
1624 IntervalLimiter profiler_interval;
1627 * TODO: Local caching of settings is not optimal and should at some stage
1628 * be updated to use a global settings object for getting thse values
1629 * (as opposed to the this local caching). This can be addressed in
1632 bool m_cache_doubletap_jump;
1633 bool m_cache_enable_node_highlighting;
1634 bool m_cache_enable_clouds;
1635 bool m_cache_enable_particles;
1636 bool m_cache_enable_fog;
1637 f32 m_cache_mouse_sensitivity;
1638 f32 m_repeat_right_click_time;
1641 bool m_cache_hold_aux1;
1651 itemdef_manager(NULL),
1652 nodedef_manager(NULL),
1654 sound_is_dummy(false),
1657 current_formspec(NULL),
1660 gui_chat_console(NULL),
1665 local_inventory(NULL),
1669 g_settings->registerChangedCallback("doubletap_jump",
1670 &settingChangedCallback, this);
1671 g_settings->registerChangedCallback("enable_node_highlighting",
1672 &settingChangedCallback, this);
1673 g_settings->registerChangedCallback("enable_clouds",
1674 &settingChangedCallback, this);
1675 g_settings->registerChangedCallback("enable_particles",
1676 &settingChangedCallback, this);
1677 g_settings->registerChangedCallback("enable_fog",
1678 &settingChangedCallback, this);
1679 g_settings->registerChangedCallback("mouse_sensitivity",
1680 &settingChangedCallback, this);
1681 g_settings->registerChangedCallback("repeat_rightclick_time",
1682 &settingChangedCallback, this);
1687 m_cache_hold_aux1 = false; // This is initialised properly later
1694 /****************************************************************************
1696 ****************************************************************************/
1702 if (!sound_is_dummy)
1705 delete server; // deleted first to stop all server threads
1708 delete local_inventory;
1714 delete nodedef_manager;
1715 delete itemdef_manager;
1716 delete draw_control;
1718 extendedResourceCleanup();
1720 g_settings->deregisterChangedCallback("doubletap_jump",
1721 &settingChangedCallback, this);
1722 g_settings->deregisterChangedCallback("enable_node_highlighting",
1723 &settingChangedCallback, this);
1724 g_settings->deregisterChangedCallback("enable_clouds",
1725 &settingChangedCallback, this);
1726 g_settings->deregisterChangedCallback("enable_particles",
1727 &settingChangedCallback, this);
1728 g_settings->deregisterChangedCallback("enable_fog",
1729 &settingChangedCallback, this);
1730 g_settings->deregisterChangedCallback("mouse_sensitivity",
1731 &settingChangedCallback, this);
1732 g_settings->deregisterChangedCallback("repeat_rightclick_time",
1733 &settingChangedCallback, this);
1736 bool Game::startup(bool *kill,
1738 InputHandler *input,
1739 IrrlichtDevice *device,
1740 const std::string &map_dir,
1741 const std::string &playername,
1742 const std::string &password,
1743 std::string *address, // can change if simple_singleplayer_mode
1745 std::string &error_message,
1747 ChatBackend *chat_backend,
1748 const SubgameSpec &gamespec,
1749 bool simple_singleplayer_mode)
1752 this->device = device;
1754 this->error_message = &error_message;
1755 this->reconnect_requested = reconnect;
1756 this->random_input = random_input;
1757 this->input = input;
1758 this->chat_backend = chat_backend;
1759 this->simple_singleplayer_mode = simple_singleplayer_mode;
1761 driver = device->getVideoDriver();
1762 smgr = device->getSceneManager();
1764 smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true);
1766 if (!init(map_dir, address, port, gamespec))
1769 if (!createClient(playername, password, address, port))
1778 ProfilerGraph graph;
1779 RunStats stats = { 0 };
1780 CameraOrientation cam_view_target = { 0 };
1781 CameraOrientation cam_view = { 0 };
1782 GameRunData runData = { 0 };
1783 FpsControl draw_times = { 0 };
1784 VolatileRunFlags flags = { 0 };
1785 f32 dtime; // in seconds
1787 runData.time_from_last_punch = 10.0;
1788 runData.profiler_max_page = 3;
1789 runData.update_wielded_item_trigger = true;
1791 flags.show_chat = true;
1792 flags.show_hud = true;
1793 flags.show_minimap = g_settings->getBool("enable_minimap");
1794 flags.show_debug = g_settings->getBool("show_debug");
1795 flags.invert_mouse = g_settings->getBool("invert_mouse");
1796 flags.first_loop_after_window_activation = true;
1798 /* Clear the profiler */
1799 Profiler::GraphValues dummyvalues;
1800 g_profiler->graphGet(dummyvalues);
1802 draw_times.last_time = device->getTimer()->getTime();
1804 shader_src->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1806 &flags.force_fog_off,
1810 std::vector<aabb3f> highlight_boxes;
1812 set_light_table(g_settings->getFloat("display_gamma"));
1815 m_cache_hold_aux1 = g_settings->getBool("fast_move")
1816 && client->checkPrivilege("fast");
1819 while (device->run()
1820 && !(*kill || g_gamecallback->shutdown_requested
1821 || server->getShutdownRequested())) {
1823 /* Must be called immediately after a device->run() call because it
1824 * uses device->getTimer()->getTime()
1826 limitFps(&draw_times, &dtime);
1828 updateStats(&stats, draw_times, dtime);
1829 updateInteractTimers(&runData, dtime);
1831 if (!checkConnection())
1833 if (!handleCallbacks())
1839 hud->resizeHotbar();
1841 updateProfilers(runData, stats, draw_times, dtime);
1842 processUserInput(&flags, &runData, dtime);
1843 // Update camera before player movement to avoid camera lag of one frame
1844 updateCameraDirection(&cam_view_target, &flags);
1845 float cam_smoothing = 0;
1846 if (g_settings->getBool("cinematic"))
1847 cam_smoothing = 1 - g_settings->getFloat("cinematic_camera_smoothing");
1849 cam_smoothing = 1 - g_settings->getFloat("camera_smoothing");
1850 cam_smoothing = rangelim(cam_smoothing, 0.01f, 1.0f);
1851 cam_view.camera_yaw += (cam_view_target.camera_yaw -
1852 cam_view.camera_yaw) * cam_smoothing;
1853 cam_view.camera_pitch += (cam_view_target.camera_pitch -
1854 cam_view.camera_pitch) * cam_smoothing;
1855 updatePlayerControl(cam_view);
1857 processClientEvents(&cam_view_target, &runData.damage_flash);
1858 updateCamera(&flags, draw_times.busy_time, dtime,
1859 runData.time_from_last_punch);
1861 processPlayerInteraction(highlight_boxes, &runData, dtime,
1862 flags.show_hud, flags.show_debug);
1863 updateFrame(highlight_boxes, &graph, &stats, &runData, dtime,
1865 updateProfilerGraphs(&graph);
1867 // Update if minimap has been disabled by the server
1868 flags.show_minimap &= !client->isMinimapDisabledByServer();
1873 void Game::shutdown()
1875 showOverlayMessage(wgettext("Shutting down..."), 0, 0, false);
1880 if (gui_chat_console)
1881 gui_chat_console->drop();
1887 while (g_menumgr.menuCount() > 0) {
1888 g_menumgr.m_stack.front()->setVisible(false);
1889 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
1892 if (current_formspec) {
1893 current_formspec->drop();
1894 current_formspec = NULL;
1897 chat_backend->addMessage(L"", L"# Disconnected.");
1898 chat_backend->addMessage(L"", L"");
1902 while (!client->isShutdown()) {
1903 assert(texture_src != NULL);
1904 assert(shader_src != NULL);
1905 texture_src->processQueue();
1906 shader_src->processQueue();
1913 /****************************************************************************/
1914 /****************************************************************************
1916 ****************************************************************************/
1917 /****************************************************************************/
1920 const std::string &map_dir,
1921 std::string *address,
1923 const SubgameSpec &gamespec)
1925 showOverlayMessage(wgettext("Loading..."), 0, 0);
1927 texture_src = createTextureSource(device);
1928 shader_src = createShaderSource(device);
1930 itemdef_manager = createItemDefManager();
1931 nodedef_manager = createNodeDefManager();
1933 eventmgr = new EventManager();
1934 quicktune = new QuicktuneShortcutter();
1936 if (!(texture_src && shader_src && itemdef_manager && nodedef_manager
1937 && eventmgr && quicktune))
1943 // Create a server if not connecting to an existing one
1944 if (*address == "") {
1945 if (!createSingleplayerServer(map_dir, gamespec, port, address))
1952 bool Game::initSound()
1955 if (g_settings->getBool("enable_sound")) {
1956 infostream << "Attempting to use OpenAL audio" << std::endl;
1957 sound = createOpenALSoundManager(&soundfetcher);
1959 infostream << "Failed to initialize OpenAL audio" << std::endl;
1961 infostream << "Sound disabled." << std::endl;
1965 infostream << "Using dummy audio." << std::endl;
1966 sound = &dummySoundManager;
1967 sound_is_dummy = true;
1970 soundmaker = new SoundMaker(sound, nodedef_manager);
1974 soundmaker->registerReceiver(eventmgr);
1979 bool Game::createSingleplayerServer(const std::string map_dir,
1980 const SubgameSpec &gamespec, u16 port, std::string *address)
1982 showOverlayMessage(wgettext("Creating server..."), 0, 5);
1984 std::string bind_str = g_settings->get("bind_address");
1985 Address bind_addr(0, 0, 0, 0, port);
1987 if (g_settings->getBool("ipv6_server")) {
1988 bind_addr.setAddress((IPv6AddressBytes *) NULL);
1992 bind_addr.Resolve(bind_str.c_str());
1993 } catch (ResolveError &e) {
1994 infostream << "Resolving bind address \"" << bind_str
1995 << "\" failed: " << e.what()
1996 << " -- Listening on all addresses." << std::endl;
1999 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2000 *error_message = "Unable to listen on " +
2001 bind_addr.serializeString() +
2002 " because IPv6 is disabled";
2003 errorstream << *error_message << std::endl;
2007 server = new Server(map_dir, gamespec, simple_singleplayer_mode,
2008 bind_addr.isIPv6());
2010 server->start(bind_addr);
2015 bool Game::createClient(const std::string &playername,
2016 const std::string &password, std::string *address, u16 port)
2018 showOverlayMessage(wgettext("Creating client..."), 0, 10);
2020 draw_control = new MapDrawControl;
2024 bool could_connect, connect_aborted;
2026 if (!connectToServer(playername, password, address, port,
2027 &could_connect, &connect_aborted))
2030 if (!could_connect) {
2031 if (error_message->empty() && !connect_aborted) {
2032 // Should not happen if error messages are set properly
2033 *error_message = "Connection failed for unknown reason";
2034 errorstream << *error_message << std::endl;
2039 if (!getServerContent(&connect_aborted)) {
2040 if (error_message->empty() && !connect_aborted) {
2041 // Should not happen if error messages are set properly
2042 *error_message = "Connection failed for unknown reason";
2043 errorstream << *error_message << std::endl;
2048 // Update cached textures, meshes and materials
2049 client->afterContentReceived(device);
2053 camera = new Camera(smgr, *draw_control, gamedef);
2054 if (!camera || !camera->successfullyCreated(*error_message))
2059 if (m_cache_enable_clouds) {
2060 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
2062 *error_message = "Memory allocation error (clouds)";
2063 errorstream << *error_message << std::endl;
2070 sky = new Sky(smgr->getRootSceneNode(), smgr, -1, texture_src);
2071 skybox = NULL; // This is used/set later on in the main run loop
2073 local_inventory = new Inventory(itemdef_manager);
2075 if (!(sky && local_inventory)) {
2076 *error_message = "Memory allocation error (sky or local inventory)";
2077 errorstream << *error_message << std::endl;
2081 /* Pre-calculated values
2083 video::ITexture *t = texture_src->getTexture("crack_anylength.png");
2085 v2u32 size = t->getOriginalSize();
2086 crack_animation_length = size.Y / size.X;
2088 crack_animation_length = 5;
2094 /* Set window caption
2096 std::wstring str = utf8_to_wide(PROJECT_NAME_C);
2098 str += driver->getName();
2100 device->setWindowCaption(str.c_str());
2102 LocalPlayer *player = client->getEnv().getLocalPlayer();
2103 player->hurt_tilt_timer = 0;
2104 player->hurt_tilt_strength = 0;
2106 hud = new Hud(driver, smgr, guienv, gamedef, player, local_inventory);
2109 *error_message = "Memory error: could not create HUD";
2110 errorstream << *error_message << std::endl;
2114 mapper = client->getMapper();
2115 mapper->setMinimapMode(MINIMAP_MODE_OFF);
2120 bool Game::initGui()
2122 // First line of debug text
2123 guitext = guienv->addStaticText(
2124 utf8_to_wide(PROJECT_NAME_C).c_str(),
2125 core::rect<s32>(0, 0, 0, 0),
2126 false, false, guiroot);
2128 // Second line of debug text
2129 guitext2 = guienv->addStaticText(
2131 core::rect<s32>(0, 0, 0, 0),
2132 false, false, guiroot);
2134 // At the middle of the screen
2135 // Object infos are shown in this
2136 guitext_info = guienv->addStaticText(
2138 core::rect<s32>(0, 0, 400, g_fontengine->getTextHeight() * 5 + 5) + v2s32(100, 200),
2139 false, true, guiroot);
2141 // Status text (displays info when showing and hiding GUI stuff, etc.)
2142 guitext_status = guienv->addStaticText(
2144 core::rect<s32>(0, 0, 0, 0),
2145 false, false, guiroot);
2146 guitext_status->setVisible(false);
2149 guitext_chat = guienv->addStaticText(
2151 core::rect<s32>(0, 0, 0, 0),
2152 //false, false); // Disable word wrap as of now
2153 false, true, guiroot);
2154 // Remove stale "recent" chat messages from previous connections
2155 chat_backend->clearRecentChat();
2157 // Chat backend and console
2158 gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(),
2159 -1, chat_backend, client);
2160 if (!gui_chat_console) {
2161 *error_message = "Could not allocate memory for chat console";
2162 errorstream << *error_message << std::endl;
2166 // Profiler text (size is updated when text is updated)
2167 guitext_profiler = guienv->addStaticText(
2169 core::rect<s32>(0, 0, 0, 0),
2170 false, false, guiroot);
2171 guitext_profiler->setBackgroundColor(video::SColor(120, 0, 0, 0));
2172 guitext_profiler->setVisible(false);
2173 guitext_profiler->setWordWrap(true);
2175 #ifdef HAVE_TOUCHSCREENGUI
2177 if (g_touchscreengui)
2178 g_touchscreengui->init(texture_src);
2185 bool Game::connectToServer(const std::string &playername,
2186 const std::string &password, std::string *address, u16 port,
2187 bool *connect_ok, bool *aborted)
2189 *connect_ok = false; // Let's not be overly optimistic
2191 bool local_server_mode = false;
2193 showOverlayMessage(wgettext("Resolving address..."), 0, 15);
2195 Address connect_address(0, 0, 0, 0, port);
2198 connect_address.Resolve(address->c_str());
2200 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
2201 //connect_address.Resolve("localhost");
2202 if (connect_address.isIPv6()) {
2203 IPv6AddressBytes addr_bytes;
2204 addr_bytes.bytes[15] = 1;
2205 connect_address.setAddress(&addr_bytes);
2207 connect_address.setAddress(127, 0, 0, 1);
2209 local_server_mode = true;
2211 } catch (ResolveError &e) {
2212 *error_message = std::string("Couldn't resolve address: ") + e.what();
2213 errorstream << *error_message << std::endl;
2217 if (connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
2218 *error_message = "Unable to connect to " +
2219 connect_address.serializeString() +
2220 " because IPv6 is disabled";
2221 errorstream << *error_message << std::endl;
2225 client = new Client(device,
2226 playername.c_str(), password,
2227 *draw_control, texture_src, shader_src,
2228 itemdef_manager, nodedef_manager, sound, eventmgr,
2229 connect_address.isIPv6());
2234 gamedef = client; // Client acts as our GameDef
2236 infostream << "Connecting to server at ";
2237 connect_address.print(&infostream);
2238 infostream << std::endl;
2240 client->connect(connect_address, *address,
2241 simple_singleplayer_mode || local_server_mode);
2244 Wait for server to accept connection
2250 FpsControl fps_control = { 0 };
2252 f32 wait_time = 0; // in seconds
2254 fps_control.last_time = device->getTimer()->getTime();
2256 while (device->run()) {
2258 limitFps(&fps_control, &dtime);
2260 // Update client and server
2261 client->step(dtime);
2264 server->step(dtime);
2267 if (client->getState() == LC_Init) {
2273 if (client->accessDenied()) {
2274 *error_message = "Access denied. Reason: "
2275 + client->accessDeniedReason();
2276 *reconnect_requested = client->reconnectRequested();
2277 errorstream << *error_message << std::endl;
2281 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2283 infostream << "Connect aborted [Escape]" << std::endl;
2288 // Only time out if we aren't waiting for the server we started
2289 if ((*address != "") && (wait_time > 10)) {
2290 *error_message = "Connection timed out.";
2291 errorstream << *error_message << std::endl;
2296 showOverlayMessage(wgettext("Connecting to server..."), dtime, 20);
2298 } catch (con::PeerNotFoundException &e) {
2299 // TODO: Should something be done here? At least an info/error
2307 bool Game::getServerContent(bool *aborted)
2311 FpsControl fps_control = { 0 };
2312 f32 dtime; // in seconds
2314 fps_control.last_time = device->getTimer()->getTime();
2316 while (device->run()) {
2318 limitFps(&fps_control, &dtime);
2320 // Update client and server
2321 client->step(dtime);
2324 server->step(dtime);
2327 if (client->mediaReceived() && client->itemdefReceived() &&
2328 client->nodedefReceived()) {
2333 if (!checkConnection())
2336 if (client->getState() < LC_Init) {
2337 *error_message = "Client disconnected";
2338 errorstream << *error_message << std::endl;
2342 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2344 infostream << "Connect aborted [Escape]" << std::endl;
2351 if (!client->itemdefReceived()) {
2352 const wchar_t *text = wgettext("Item definitions...");
2354 draw_load_screen(text, device, guienv, dtime, progress);
2356 } else if (!client->nodedefReceived()) {
2357 const wchar_t *text = wgettext("Node definitions...");
2359 draw_load_screen(text, device, guienv, dtime, progress);
2362 std::stringstream message;
2363 message.precision(3);
2364 message << gettext("Media...");
2366 if ((USE_CURL == 0) ||
2367 (!g_settings->getBool("enable_remote_media_server"))) {
2368 float cur = client->getCurRate();
2369 std::string cur_unit = gettext("KiB/s");
2373 cur_unit = gettext("MiB/s");
2376 message << " (" << cur << ' ' << cur_unit << ")";
2379 progress = 30 + client->mediaReceiveProgress() * 35 + 0.5;
2380 draw_load_screen(utf8_to_wide(message.str()), device,
2381 guienv, dtime, progress);
2389 /****************************************************************************/
2390 /****************************************************************************
2392 ****************************************************************************/
2393 /****************************************************************************/
2395 inline void Game::updateInteractTimers(GameRunData *runData, f32 dtime)
2397 if (runData->nodig_delay_timer >= 0)
2398 runData->nodig_delay_timer -= dtime;
2400 if (runData->object_hit_delay_timer >= 0)
2401 runData->object_hit_delay_timer -= dtime;
2403 runData->time_from_last_punch += dtime;
2407 /* returns false if game should exit, otherwise true
2409 inline bool Game::checkConnection()
2411 if (client->accessDenied()) {
2412 *error_message = "Access denied. Reason: "
2413 + client->accessDeniedReason();
2414 *reconnect_requested = client->reconnectRequested();
2415 errorstream << *error_message << std::endl;
2423 /* returns false if game should exit, otherwise true
2425 inline bool Game::handleCallbacks()
2427 if (g_gamecallback->disconnect_requested) {
2428 g_gamecallback->disconnect_requested = false;
2432 if (g_gamecallback->changepassword_requested) {
2433 (new GUIPasswordChange(guienv, guiroot, -1,
2434 &g_menumgr, client))->drop();
2435 g_gamecallback->changepassword_requested = false;
2438 if (g_gamecallback->changevolume_requested) {
2439 (new GUIVolumeChange(guienv, guiroot, -1,
2440 &g_menumgr, client))->drop();
2441 g_gamecallback->changevolume_requested = false;
2444 if (g_gamecallback->keyconfig_requested) {
2445 (new GUIKeyChangeMenu(guienv, guiroot, -1,
2446 &g_menumgr))->drop();
2447 g_gamecallback->keyconfig_requested = false;
2450 if (g_gamecallback->keyconfig_changed) {
2451 keycache.populate(); // update the cache with new settings
2452 g_gamecallback->keyconfig_changed = false;
2459 void Game::processQueues()
2461 texture_src->processQueue();
2462 itemdef_manager->processQueue(gamedef);
2463 shader_src->processQueue();
2467 void Game::updateProfilers(const GameRunData &runData, const RunStats &stats,
2468 const FpsControl &draw_times, f32 dtime)
2470 float profiler_print_interval =
2471 g_settings->getFloat("profiler_print_interval");
2472 bool print_to_log = true;
2474 if (profiler_print_interval == 0) {
2475 print_to_log = false;
2476 profiler_print_interval = 5;
2479 if (profiler_interval.step(dtime, profiler_print_interval)) {
2481 infostream << "Profiler:" << std::endl;
2482 g_profiler->print(infostream);
2485 update_profiler_gui(guitext_profiler, g_fontengine,
2486 runData.profiler_current_page, runData.profiler_max_page,
2487 driver->getScreenSize().Height);
2489 g_profiler->clear();
2492 addProfilerGraphs(stats, draw_times, dtime);
2496 void Game::addProfilerGraphs(const RunStats &stats,
2497 const FpsControl &draw_times, f32 dtime)
2499 g_profiler->graphAdd("mainloop_other",
2500 draw_times.busy_time / 1000.0f - stats.drawtime / 1000.0f);
2502 if (draw_times.sleep_time != 0)
2503 g_profiler->graphAdd("mainloop_sleep", draw_times.sleep_time / 1000.0f);
2504 g_profiler->graphAdd("mainloop_dtime", dtime);
2506 g_profiler->add("Elapsed time", dtime);
2507 g_profiler->avg("FPS", 1. / dtime);
2511 void Game::updateStats(RunStats *stats, const FpsControl &draw_times,
2518 /* Time average and jitter calculation
2520 jp = &stats->dtime_jitter;
2521 jp->avg = jp->avg * 0.96 + dtime * 0.04;
2523 jitter = dtime - jp->avg;
2525 if (jitter > jp->max)
2528 jp->counter += dtime;
2530 if (jp->counter > 0.0) {
2532 jp->max_sample = jp->max;
2533 jp->max_fraction = jp->max_sample / (jp->avg + 0.001);
2537 /* Busytime average and jitter calculation
2539 jp = &stats->busy_time_jitter;
2540 jp->avg = jp->avg + draw_times.busy_time * 0.02;
2542 jitter = draw_times.busy_time - jp->avg;
2544 if (jitter > jp->max)
2546 if (jitter < jp->min)
2549 jp->counter += dtime;
2551 if (jp->counter > 0.0) {
2553 jp->max_sample = jp->max;
2554 jp->min_sample = jp->min;
2562 /****************************************************************************
2564 ****************************************************************************/
2566 void Game::processUserInput(VolatileRunFlags *flags,
2567 GameRunData *runData, f32 dtime)
2569 // Reset input if window not active or some menu is active
2570 if (device->isWindowActive() == false
2571 || noMenuActive() == false
2572 || guienv->hasFocus(gui_chat_console)) {
2574 #ifdef HAVE_TOUCHSCREENGUI
2575 g_touchscreengui->hide();
2578 #ifdef HAVE_TOUCHSCREENGUI
2579 else if (g_touchscreengui) {
2580 /* on touchscreengui step may generate own input events which ain't
2581 * what we want in case we just did clear them */
2582 g_touchscreengui->step(dtime);
2586 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen()) {
2587 gui_chat_console->closeConsoleAtOnce();
2590 // Input handler step() (used by the random input generator)
2595 if (current_formspec != 0)
2596 current_formspec->getAndroidUIInput();
2600 // Increase timer for double tap of "keymap_jump"
2601 if (m_cache_doubletap_jump && runData->jump_timer <= 0.2)
2602 runData->jump_timer += dtime;
2604 processKeyboardInput(
2606 &runData->statustext_time,
2607 &runData->jump_timer,
2608 &runData->reset_jump_timer,
2609 &runData->profiler_current_page,
2610 runData->profiler_max_page);
2612 processItemSelection(&runData->new_playeritem);
2616 void Game::processKeyboardInput(VolatileRunFlags *flags,
2617 float *statustext_time,
2619 bool *reset_jump_timer,
2620 u32 *profiler_current_page,
2621 u32 profiler_max_page)
2624 //TimeTaker tt("process kybd input", NULL, PRECISION_NANO);
2626 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DROP])) {
2628 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_AUTORUN])) {
2629 toggleAutorun(statustext_time);
2630 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INVENTORY])) {
2632 } else if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
2633 show_pause_menu(¤t_formspec, client, gamedef, texture_src, device,
2634 simple_singleplayer_mode);
2635 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CHAT])) {
2636 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2638 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CMD])) {
2639 show_chat_menu(¤t_formspec, client, gamedef, texture_src, device,
2641 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CONSOLE])) {
2643 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FREEMOVE])) {
2644 toggleFreeMove(statustext_time);
2645 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP])) {
2646 toggleFreeMoveAlt(statustext_time, jump_timer);
2647 *reset_jump_timer = true;
2648 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_FASTMOVE])) {
2649 toggleFast(statustext_time);
2650 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_NOCLIP])) {
2651 toggleNoClip(statustext_time);
2652 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CINEMATIC])) {
2653 toggleCinematic(statustext_time);
2654 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_SCREENSHOT])) {
2655 client->makeScreenshot(device);
2656 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_HUD])) {
2657 toggleHud(statustext_time, &flags->show_hud);
2658 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_MINIMAP])) {
2659 toggleMinimap(statustext_time, &flags->show_minimap, flags->show_hud,
2660 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]));
2661 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_CHAT])) {
2662 toggleChat(statustext_time, &flags->show_chat);
2663 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_FORCE_FOG_OFF])) {
2664 toggleFog(statustext_time, &flags->force_fog_off);
2665 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_UPDATE_CAMERA])) {
2666 toggleUpdateCamera(statustext_time, &flags->disable_camera_update);
2667 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_DEBUG])) {
2668 toggleDebug(statustext_time, &flags->show_debug, &flags->show_profiler_graph);
2669 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_TOGGLE_PROFILER])) {
2670 toggleProfiler(statustext_time, profiler_current_page, profiler_max_page);
2671 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_INCREASE_VIEWING_RANGE])) {
2672 increaseViewRange(statustext_time);
2673 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DECREASE_VIEWING_RANGE])) {
2674 decreaseViewRange(statustext_time);
2675 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_RANGESELECT])) {
2676 toggleFullViewRange(statustext_time);
2677 } else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_NEXT]))
2679 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_PREV]))
2681 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_INC]))
2683 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_QUICKTUNE_DEC]))
2685 else if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_DEBUG_STACKS])) {
2686 // Print debug stacks
2687 dstream << "-----------------------------------------"
2689 dstream << "Printing debug stacks:" << std::endl;
2690 dstream << "-----------------------------------------"
2692 debug_stacks_print();
2695 if (!input->isKeyDown(getKeySetting("keymap_jump")) && *reset_jump_timer) {
2696 *reset_jump_timer = false;
2702 if (quicktune->hasMessage()) {
2703 std::string msg = quicktune->getMessage();
2704 statustext = utf8_to_wide(msg);
2705 *statustext_time = 0;
2710 void Game::processItemSelection(u16 *new_playeritem)
2712 LocalPlayer *player = client->getEnv().getLocalPlayer();
2714 /* Item selection using mouse wheel
2716 *new_playeritem = client->getPlayerItem();
2718 s32 wheel = input->getMouseWheel();
2719 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE - 1,
2720 player->hud_hotbar_itemcount - 1);
2723 *new_playeritem = *new_playeritem < max_item ? *new_playeritem + 1 : 0;
2725 *new_playeritem = *new_playeritem > 0 ? *new_playeritem - 1 : max_item;
2729 /* Item selection using keyboard
2731 for (u16 i = 0; i < 10; i++) {
2732 static const KeyPress *item_keys[10] = {
2733 NumberKey + 1, NumberKey + 2, NumberKey + 3, NumberKey + 4,
2734 NumberKey + 5, NumberKey + 6, NumberKey + 7, NumberKey + 8,
2735 NumberKey + 9, NumberKey + 0,
2738 if (input->wasKeyDown(*item_keys[i])) {
2739 if (i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount) {
2740 *new_playeritem = i;
2741 infostream << "Selected item: " << new_playeritem << std::endl;
2749 void Game::dropSelectedItem()
2751 IDropAction *a = new IDropAction();
2753 a->from_inv.setCurrentPlayer();
2754 a->from_list = "main";
2755 a->from_i = client->getPlayerItem();
2756 client->inventoryAction(a);
2760 void Game::openInventory()
2763 * Don't permit to open inventory is CAO or player doesn't exists.
2764 * This prevent showing an empty inventory at player load
2767 LocalPlayer *player = client->getEnv().getLocalPlayer();
2768 if (player == NULL || player->getCAO() == NULL)
2771 infostream << "the_game: " << "Launching inventory" << std::endl;
2773 PlayerInventoryFormSource *fs_src = new PlayerInventoryFormSource(client);
2774 TextDest *txt_dst = new TextDestPlayerInventory(client);
2776 create_formspec_menu(¤t_formspec, client, gamedef, texture_src,
2777 device, fs_src, txt_dst, client);
2779 InventoryLocation inventoryloc;
2780 inventoryloc.setCurrentPlayer();
2781 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
2785 void Game::openConsole()
2787 if (!gui_chat_console->isOpenInhibited()) {
2788 // Open up to over half of the screen
2789 gui_chat_console->openConsole(0.6);
2790 guienv->setFocus(gui_chat_console);
2795 void Game::toggleFreeMove(float *statustext_time)
2797 static const wchar_t *msg[] = { L"free_move disabled", L"free_move enabled" };
2799 bool free_move = !g_settings->getBool("free_move");
2800 g_settings->set("free_move", bool_to_cstr(free_move));
2802 *statustext_time = 0;
2803 statustext = msg[free_move];
2804 if (free_move && !client->checkPrivilege("fly"))
2805 statustext += L" (note: no 'fly' privilege)";
2809 void Game::toggleFreeMoveAlt(float *statustext_time, float *jump_timer)
2811 if (m_cache_doubletap_jump && *jump_timer < 0.2f)
2812 toggleFreeMove(statustext_time);
2816 void Game::toggleFast(float *statustext_time)
2818 static const wchar_t *msg[] = { L"fast_move disabled", L"fast_move enabled" };
2819 bool fast_move = !g_settings->getBool("fast_move");
2820 g_settings->set("fast_move", bool_to_cstr(fast_move));
2822 *statustext_time = 0;
2823 statustext = msg[fast_move];
2825 bool has_fast_privs = client->checkPrivilege("fast");
2827 if (fast_move && !has_fast_privs)
2828 statustext += L" (note: no 'fast' privilege)";
2831 m_cache_hold_aux1 = fast_move && has_fast_privs;
2836 void Game::toggleNoClip(float *statustext_time)
2838 static const wchar_t *msg[] = { L"noclip disabled", L"noclip enabled" };
2839 bool noclip = !g_settings->getBool("noclip");
2840 g_settings->set("noclip", bool_to_cstr(noclip));
2842 *statustext_time = 0;
2843 statustext = msg[noclip];
2845 if (noclip && !client->checkPrivilege("noclip"))
2846 statustext += L" (note: no 'noclip' privilege)";
2849 void Game::toggleCinematic(float *statustext_time)
2851 static const wchar_t *msg[] = { L"cinematic disabled", L"cinematic enabled" };
2852 bool cinematic = !g_settings->getBool("cinematic");
2853 g_settings->set("cinematic", bool_to_cstr(cinematic));
2855 *statustext_time = 0;
2856 statustext = msg[cinematic];
2859 // Add WoW-style autorun by toggling continuous forward.
2860 void Game::toggleAutorun(float *statustext_time)
2862 static const wchar_t *msg[] = { L"autorun disabled", L"autorun enabled" };
2863 bool autorun_enabled = !g_settings->getBool("continuous_forward");
2864 g_settings->set("continuous_forward", bool_to_cstr(autorun_enabled));
2866 *statustext_time = 0;
2867 statustext = msg[autorun_enabled ? 1 : 0];
2870 void Game::toggleChat(float *statustext_time, bool *flag)
2872 static const wchar_t *msg[] = { L"Chat hidden", L"Chat shown" };
2875 *statustext_time = 0;
2876 statustext = msg[*flag];
2880 void Game::toggleHud(float *statustext_time, bool *flag)
2882 static const wchar_t *msg[] = { L"HUD hidden", L"HUD shown" };
2885 *statustext_time = 0;
2886 statustext = msg[*flag];
2887 if (g_settings->getBool("enable_node_highlighting"))
2888 client->setHighlighted(client->getHighlighted(), *flag);
2891 void Game::toggleMinimap(float *statustext_time, bool *flag,
2892 bool show_hud, bool shift_pressed)
2894 if (!show_hud || !g_settings->getBool("enable_minimap"))
2897 if (shift_pressed) {
2898 mapper->toggleMinimapShape();
2902 u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags;
2904 MinimapMode mode = MINIMAP_MODE_OFF;
2905 if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) {
2906 mode = mapper->getMinimapMode();
2907 mode = (MinimapMode)((int)mode + 1);
2912 case MINIMAP_MODE_SURFACEx1:
2913 statustext = L"Minimap in surface mode, Zoom x1";
2915 case MINIMAP_MODE_SURFACEx2:
2916 statustext = L"Minimap in surface mode, Zoom x2";
2918 case MINIMAP_MODE_SURFACEx4:
2919 statustext = L"Minimap in surface mode, Zoom x4";
2921 case MINIMAP_MODE_RADARx1:
2922 statustext = L"Minimap in radar mode, Zoom x1";
2924 case MINIMAP_MODE_RADARx2:
2925 statustext = L"Minimap in radar mode, Zoom x2";
2927 case MINIMAP_MODE_RADARx4:
2928 statustext = L"Minimap in radar mode, Zoom x4";
2931 mode = MINIMAP_MODE_OFF;
2933 statustext = (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) ?
2934 L"Minimap hidden" : L"Minimap disabled by server";
2937 *statustext_time = 0;
2938 mapper->setMinimapMode(mode);
2941 void Game::toggleFog(float *statustext_time, bool *flag)
2943 static const wchar_t *msg[] = { L"Fog enabled", L"Fog disabled" };
2946 *statustext_time = 0;
2947 statustext = msg[*flag];
2951 void Game::toggleDebug(float *statustext_time, bool *show_debug,
2952 bool *show_profiler_graph)
2954 // Initial / 3x toggle: Chat only
2955 // 1x toggle: Debug text with chat
2956 // 2x toggle: Debug text with profiler graph
2959 *show_profiler_graph = false;
2960 statustext = L"Debug info shown";
2961 } else if (*show_profiler_graph) {
2962 *show_debug = false;
2963 *show_profiler_graph = false;
2964 statustext = L"Debug info and profiler graph hidden";
2966 *show_profiler_graph = true;
2967 statustext = L"Profiler graph shown";
2969 *statustext_time = 0;
2973 void Game::toggleUpdateCamera(float *statustext_time, bool *flag)
2975 static const wchar_t *msg[] = {
2976 L"Camera update enabled",
2977 L"Camera update disabled"
2981 *statustext_time = 0;
2982 statustext = msg[*flag];
2986 void Game::toggleProfiler(float *statustext_time, u32 *profiler_current_page,
2987 u32 profiler_max_page)
2989 *profiler_current_page = (*profiler_current_page + 1) % (profiler_max_page + 1);
2991 // FIXME: This updates the profiler with incomplete values
2992 update_profiler_gui(guitext_profiler, g_fontengine, *profiler_current_page,
2993 profiler_max_page, driver->getScreenSize().Height);
2995 if (*profiler_current_page != 0) {
2996 std::wstringstream sstr;
2997 sstr << "Profiler shown (page " << *profiler_current_page
2998 << " of " << profiler_max_page << ")";
2999 statustext = sstr.str();
3001 statustext = L"Profiler hidden";
3003 *statustext_time = 0;
3007 void Game::increaseViewRange(float *statustext_time)
3009 s16 range = g_settings->getS16("viewing_range_nodes_min");
3010 s16 range_new = range + 10;
3011 g_settings->set("viewing_range_nodes_min", itos(range_new));
3012 statustext = utf8_to_wide("Minimum viewing range changed to "
3014 *statustext_time = 0;
3018 void Game::decreaseViewRange(float *statustext_time)
3020 s16 range = g_settings->getS16("viewing_range_nodes_min");
3021 s16 range_new = range - 10;
3026 g_settings->set("viewing_range_nodes_min", itos(range_new));
3027 statustext = utf8_to_wide("Minimum viewing range changed to "
3029 *statustext_time = 0;
3033 void Game::toggleFullViewRange(float *statustext_time)
3035 static const wchar_t *msg[] = {
3036 L"Disabled full viewing range",
3037 L"Enabled full viewing range"
3040 draw_control->range_all = !draw_control->range_all;
3041 infostream << msg[draw_control->range_all] << std::endl;
3042 statustext = msg[draw_control->range_all];
3043 *statustext_time = 0;
3047 void Game::updateCameraDirection(CameraOrientation *cam,
3048 VolatileRunFlags *flags)
3050 if ((device->isWindowActive() && noMenuActive()) || random_input) {
3053 if (!random_input) {
3054 // Mac OSX gets upset if this is set every frame
3055 if (device->getCursorControl()->isVisible())
3056 device->getCursorControl()->setVisible(false);
3060 if (flags->first_loop_after_window_activation)
3061 flags->first_loop_after_window_activation = false;
3063 updateCameraOrientation(cam, *flags);
3065 input->setMousePos((driver->getScreenSize().Width / 2),
3066 (driver->getScreenSize().Height / 2));
3070 // Mac OSX gets upset if this is set every frame
3071 if (device->getCursorControl()->isVisible() == false)
3072 device->getCursorControl()->setVisible(true);
3075 if (!flags->first_loop_after_window_activation)
3076 flags->first_loop_after_window_activation = true;
3082 void Game::updateCameraOrientation(CameraOrientation *cam,
3083 const VolatileRunFlags &flags)
3085 #ifdef HAVE_TOUCHSCREENGUI
3086 if (g_touchscreengui) {
3087 cam->camera_yaw = g_touchscreengui->getYaw();
3088 cam->camera_pitch = g_touchscreengui->getPitch();
3091 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width / 2);
3092 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height / 2);
3094 if (flags.invert_mouse
3095 || camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
3099 cam->camera_yaw -= dx * m_cache_mouse_sensitivity;
3100 cam->camera_pitch += dy * m_cache_mouse_sensitivity;
3102 #ifdef HAVE_TOUCHSCREENGUI
3106 cam->camera_pitch = rangelim(cam->camera_pitch, -89.5, 89.5);
3110 void Game::updatePlayerControl(const CameraOrientation &cam)
3112 //TimeTaker tt("update player control", NULL, PRECISION_NANO);
3114 PlayerControl control(
3115 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]),
3116 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]),
3117 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]),
3118 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]),
3119 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]),
3120 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]),
3121 input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]),
3122 input->getLeftState(),
3123 input->getRightState(),
3129 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_FORWARD]) & 0x1) << 0) |
3130 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_BACKWARD]) & 0x1) << 1) |
3131 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_LEFT]) & 0x1) << 2) |
3132 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_RIGHT]) & 0x1) << 3) |
3133 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_JUMP]) & 0x1) << 4) |
3134 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SPECIAL1]) & 0x1) << 5) |
3135 ( (u32)(input->isKeyDown(keycache.key[KeyCache::KEYMAP_ID_SNEAK]) & 0x1) << 6) |
3136 ( (u32)(input->getLeftState() & 0x1) << 7) |
3137 ( (u32)(input->getRightState() & 0x1) << 8
3141 /* For Android, simulate holding down AUX1 (fast move) if the user has
3142 * the fast_move setting toggled on. If there is an aux1 key defined for
3143 * Android then its meaning is inverted (i.e. holding aux1 means walk and
3146 if (m_cache_hold_aux1) {
3147 control.aux1 = control.aux1 ^ true;
3148 keypress_bits ^= ((u32)(1U << 5));
3152 client->setPlayerControl(control);
3153 LocalPlayer *player = client->getEnv().getLocalPlayer();
3154 player->keyPressed = keypress_bits;
3160 inline void Game::step(f32 *dtime)
3162 bool can_be_and_is_paused =
3163 (simple_singleplayer_mode && g_menumgr.pausesGame());
3165 if (can_be_and_is_paused) { // This is for a singleplayer server
3166 *dtime = 0; // No time passes
3168 if (server != NULL) {
3169 //TimeTaker timer("server->step(dtime)");
3170 server->step(*dtime);
3173 //TimeTaker timer("client.step(dtime)");
3174 client->step(*dtime);
3179 void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
3181 ClientEvent event = client->getClientEvent();
3183 LocalPlayer *player = client->getEnv().getLocalPlayer();
3185 for ( ; event.type != CE_NONE; event = client->getClientEvent()) {
3187 if (event.type == CE_PLAYER_DAMAGE &&
3188 client->getHP() != 0) {
3189 //u16 damage = event.player_damage.amount;
3190 //infostream<<"Player damage: "<<damage<<std::endl;
3192 *damage_flash += 100.0;
3193 *damage_flash += 8.0 * event.player_damage.amount;
3195 player->hurt_tilt_timer = 1.5;
3196 player->hurt_tilt_strength = event.player_damage.amount / 4;
3197 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
3199 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
3200 gamedef->event()->put(e);
3201 } else if (event.type == CE_PLAYER_FORCE_MOVE) {
3202 cam->camera_yaw = event.player_force_move.yaw;
3203 cam->camera_pitch = event.player_force_move.pitch;
3204 } else if (event.type == CE_DEATHSCREEN) {
3205 show_deathscreen(¤t_formspec, client, gamedef, texture_src,
3208 chat_backend->addMessage(L"", L"You died.");
3210 /* Handle visualization */
3212 player->hurt_tilt_timer = 0;
3213 player->hurt_tilt_strength = 0;
3215 } else if (event.type == CE_SHOW_FORMSPEC) {
3216 FormspecFormSource *fs_src =
3217 new FormspecFormSource(*(event.show_formspec.formspec));
3218 TextDestPlayerInventory *txt_dst =
3219 new TextDestPlayerInventory(client, *(event.show_formspec.formname));
3221 create_formspec_menu(¤t_formspec, client, gamedef,
3222 texture_src, device, fs_src, txt_dst, client);
3224 delete(event.show_formspec.formspec);
3225 delete(event.show_formspec.formname);
3226 } else if ((event.type == CE_SPAWN_PARTICLE) ||
3227 (event.type == CE_ADD_PARTICLESPAWNER) ||
3228 (event.type == CE_DELETE_PARTICLESPAWNER)) {
3229 client->getParticleManager()->handleParticleEvent(&event, gamedef,
3231 } else if (event.type == CE_HUDADD) {
3232 u32 id = event.hudadd.id;
3234 LocalPlayer *player = client->getEnv().getLocalPlayer();
3235 HudElement *e = player->getHud(id);
3238 delete event.hudadd.pos;
3239 delete event.hudadd.name;
3240 delete event.hudadd.scale;
3241 delete event.hudadd.text;
3242 delete event.hudadd.align;
3243 delete event.hudadd.offset;
3244 delete event.hudadd.world_pos;
3245 delete event.hudadd.size;
3250 e->type = (HudElementType)event.hudadd.type;
3251 e->pos = *event.hudadd.pos;
3252 e->name = *event.hudadd.name;
3253 e->scale = *event.hudadd.scale;
3254 e->text = *event.hudadd.text;
3255 e->number = event.hudadd.number;
3256 e->item = event.hudadd.item;
3257 e->dir = event.hudadd.dir;
3258 e->align = *event.hudadd.align;
3259 e->offset = *event.hudadd.offset;
3260 e->world_pos = *event.hudadd.world_pos;
3261 e->size = *event.hudadd.size;
3263 u32 new_id = player->addHud(e);
3264 //if this isn't true our huds aren't consistent
3265 sanity_check(new_id == 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;
3275 } else if (event.type == CE_HUDRM) {
3276 HudElement *e = player->removeHud(event.hudrm.id);
3280 } else if (event.type == CE_HUDCHANGE) {
3281 u32 id = event.hudchange.id;
3282 HudElement *e = player->getHud(id);
3285 delete event.hudchange.v3fdata;
3286 delete event.hudchange.v2fdata;
3287 delete event.hudchange.sdata;
3288 delete event.hudchange.v2s32data;
3292 switch (event.hudchange.stat) {
3294 e->pos = *event.hudchange.v2fdata;
3298 e->name = *event.hudchange.sdata;
3301 case HUD_STAT_SCALE:
3302 e->scale = *event.hudchange.v2fdata;
3306 e->text = *event.hudchange.sdata;
3309 case HUD_STAT_NUMBER:
3310 e->number = event.hudchange.data;
3314 e->item = event.hudchange.data;
3318 e->dir = event.hudchange.data;
3321 case HUD_STAT_ALIGN:
3322 e->align = *event.hudchange.v2fdata;
3325 case HUD_STAT_OFFSET:
3326 e->offset = *event.hudchange.v2fdata;
3329 case HUD_STAT_WORLD_POS:
3330 e->world_pos = *event.hudchange.v3fdata;
3334 e->size = *event.hudchange.v2s32data;
3338 delete event.hudchange.v3fdata;
3339 delete event.hudchange.v2fdata;
3340 delete event.hudchange.sdata;
3341 delete event.hudchange.v2s32data;
3342 } else if (event.type == CE_SET_SKY) {
3343 sky->setVisible(false);
3350 // Handle according to type
3351 if (*event.set_sky.type == "regular") {
3352 sky->setVisible(true);
3353 } else if (*event.set_sky.type == "skybox" &&
3354 event.set_sky.params->size() == 6) {
3355 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3356 skybox = smgr->addSkyBoxSceneNode(
3357 texture_src->getTextureForMesh((*event.set_sky.params)[0]),
3358 texture_src->getTextureForMesh((*event.set_sky.params)[1]),
3359 texture_src->getTextureForMesh((*event.set_sky.params)[2]),
3360 texture_src->getTextureForMesh((*event.set_sky.params)[3]),
3361 texture_src->getTextureForMesh((*event.set_sky.params)[4]),
3362 texture_src->getTextureForMesh((*event.set_sky.params)[5]));
3364 // Handle everything else as plain color
3366 if (*event.set_sky.type != "plain")
3367 infostream << "Unknown sky type: "
3368 << (*event.set_sky.type) << std::endl;
3370 sky->setFallbackBgColor(*event.set_sky.bgcolor);
3373 delete event.set_sky.bgcolor;
3374 delete event.set_sky.type;
3375 delete event.set_sky.params;
3376 } else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
3377 bool enable = event.override_day_night_ratio.do_override;
3378 u32 value = event.override_day_night_ratio.ratio_f * 1000;
3379 client->getEnv().setDayNightRatioOverride(enable, value);
3385 void Game::updateCamera(VolatileRunFlags *flags, u32 busy_time,
3386 f32 dtime, float time_from_last_punch)
3388 LocalPlayer *player = client->getEnv().getLocalPlayer();
3391 For interaction purposes, get info about the held item
3393 - Is it a usable item?
3394 - Can it point to liquids?
3396 ItemStack playeritem;
3398 InventoryList *mlist = local_inventory->getList("main");
3400 if (mlist && client->getPlayerItem() < mlist->getSize())
3401 playeritem = mlist->getItem(client->getPlayerItem());
3404 ToolCapabilities playeritem_toolcap =
3405 playeritem.getToolCapabilities(itemdef_manager);
3407 v3s16 old_camera_offset = camera->getOffset();
3409 if (input->wasKeyDown(keycache.key[KeyCache::KEYMAP_ID_CAMERA_MODE])) {
3410 GenericCAO *playercao = player->getCAO();
3412 // If playercao not loaded, don't change camera
3413 if (playercao == NULL)
3416 camera->toggleCameraMode();
3418 playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3419 playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST);
3422 float full_punch_interval = playeritem_toolcap.full_punch_interval;
3423 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
3425 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
3426 camera->update(player, dtime, busy_time / 1000.0f, tool_reload_ratio,
3428 camera->step(dtime);
3430 v3f camera_position = camera->getPosition();
3431 v3f camera_direction = camera->getDirection();
3432 f32 camera_fov = camera->getFovMax();
3433 v3s16 camera_offset = camera->getOffset();
3435 flags->camera_offset_changed = (camera_offset != old_camera_offset);
3437 if (!flags->disable_camera_update) {
3438 client->getEnv().getClientMap().updateCamera(camera_position,
3439 camera_direction, camera_fov, camera_offset);
3441 if (flags->camera_offset_changed) {
3442 client->updateCameraOffset(camera_offset);
3443 client->getEnv().updateCameraOffset(camera_offset);
3446 clouds->updateCameraOffset(camera_offset);
3452 void Game::updateSound(f32 dtime)
3454 // Update sound listener
3455 v3s16 camera_offset = camera->getOffset();
3456 sound->updateListener(camera->getCameraNode()->getPosition() + intToFloat(camera_offset, BS),
3457 v3f(0, 0, 0), // velocity
3458 camera->getDirection(),
3459 camera->getCameraNode()->getUpVector());
3460 sound->setListenerGain(g_settings->getFloat("sound_volume"));
3463 // Update sound maker
3464 soundmaker->step(dtime);
3466 LocalPlayer *player = client->getEnv().getLocalPlayer();
3468 ClientMap &map = client->getEnv().getClientMap();
3469 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
3470 soundmaker->m_player_step_sound = nodedef_manager->get(n).sound_footstep;
3474 void Game::processPlayerInteraction(std::vector<aabb3f> &highlight_boxes,
3475 GameRunData *runData, f32 dtime, bool show_hud, bool show_debug)
3477 LocalPlayer *player = client->getEnv().getLocalPlayer();
3479 ItemStack playeritem;
3481 InventoryList *mlist = local_inventory->getList("main");
3483 if (mlist && client->getPlayerItem() < mlist->getSize())
3484 playeritem = mlist->getItem(client->getPlayerItem());
3487 const ItemDefinition &playeritem_def =
3488 playeritem.getDefinition(itemdef_manager);
3490 v3f player_position = player->getPosition();
3491 v3f camera_position = camera->getPosition();
3492 v3f camera_direction = camera->getDirection();
3493 v3s16 camera_offset = camera->getOffset();
3497 Calculate what block is the crosshair pointing to
3500 f32 d = playeritem_def.range; // max. distance
3501 f32 d_hand = itemdef_manager->get("").range;
3503 if (d < 0 && d_hand >= 0)
3508 core::line3d<f32> shootline;
3510 if (camera->getCameraMode() != CAMERA_MODE_THIRD_FRONT) {
3512 shootline = core::line3d<f32>(camera_position,
3513 camera_position + camera_direction * BS * (d + 1));
3516 // prevent player pointing anything in front-view
3517 if (camera->getCameraMode() == CAMERA_MODE_THIRD_FRONT)
3518 shootline = core::line3d<f32>(0, 0, 0, 0, 0, 0);
3521 #ifdef HAVE_TOUCHSCREENGUI
3523 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
3524 shootline = g_touchscreengui->getShootline();
3525 shootline.start += intToFloat(camera_offset, BS);
3526 shootline.end += intToFloat(camera_offset, BS);
3531 PointedThing pointed = getPointedThing(
3533 client, player_position, camera_direction,
3534 camera_position, shootline, d,
3535 playeritem_def.liquids_pointable,
3536 !runData->ldown_for_dig,
3540 runData->selected_object);
3542 if (pointed != runData->pointed_old) {
3543 infostream << "Pointing at " << pointed.dump() << std::endl;
3545 if (m_cache_enable_node_highlighting) {
3546 if (pointed.type == POINTEDTHING_NODE) {
3547 client->setHighlighted(pointed.node_undersurface, show_hud);
3549 client->setHighlighted(pointed.node_undersurface, false);
3556 - releasing left mouse button
3557 - pointing away from node
3559 if (runData->digging) {
3560 if (input->getLeftReleased()) {
3561 infostream << "Left button released"
3562 << " (stopped digging)" << std::endl;
3563 runData->digging = false;
3564 } else if (pointed != runData->pointed_old) {
3565 if (pointed.type == POINTEDTHING_NODE
3566 && runData->pointed_old.type == POINTEDTHING_NODE
3567 && pointed.node_undersurface
3568 == runData->pointed_old.node_undersurface) {
3569 // Still pointing to the same node, but a different face.
3572 infostream << "Pointing away from node"
3573 << " (stopped digging)" << std::endl;
3574 runData->digging = false;
3578 if (!runData->digging) {
3579 client->interact(1, runData->pointed_old);
3580 client->setCrack(-1, v3s16(0, 0, 0));
3581 runData->dig_time = 0.0;
3585 if (!runData->digging && runData->ldown_for_dig && !input->getLeftState()) {
3586 runData->ldown_for_dig = false;
3589 runData->left_punch = false;
3591 soundmaker->m_player_leftpunch_sound.name = "";
3593 if (input->getRightState())
3594 runData->repeat_rightclick_timer += dtime;
3596 runData->repeat_rightclick_timer = 0;
3598 if (playeritem_def.usable && input->getLeftState()) {
3599 if (input->getLeftClicked())
3600 client->interact(4, pointed);
3601 } else if (pointed.type == POINTEDTHING_NODE) {
3602 ToolCapabilities playeritem_toolcap =
3603 playeritem.getToolCapabilities(itemdef_manager);
3604 handlePointingAtNode(runData, pointed, playeritem_def,
3605 playeritem_toolcap, dtime);
3606 } else if (pointed.type == POINTEDTHING_OBJECT) {
3607 handlePointingAtObject(runData, pointed, playeritem,
3608 player_position, show_debug);
3609 } else if (input->getLeftState()) {
3610 // When button is held down in air, show continuous animation
3611 runData->left_punch = true;
3612 } else if (input->getRightClicked()) {
3613 handlePointingAtNothing(runData, playeritem);
3616 runData->pointed_old = pointed;
3618 if (runData->left_punch || input->getLeftClicked())
3619 camera->setDigging(0); // left click animation
3621 input->resetLeftClicked();
3622 input->resetRightClicked();
3624 input->resetLeftReleased();
3625 input->resetRightReleased();
3629 void Game::handlePointingAtNothing(GameRunData *runData, const ItemStack &playerItem)
3631 infostream << "Right Clicked in Air" << std::endl;
3632 PointedThing fauxPointed;
3633 fauxPointed.type = POINTEDTHING_NOTHING;
3634 client->interact(5, fauxPointed);
3638 void Game::handlePointingAtNode(GameRunData *runData,
3639 const PointedThing &pointed, const ItemDefinition &playeritem_def,
3640 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3642 v3s16 nodepos = pointed.node_undersurface;
3643 v3s16 neighbourpos = pointed.node_abovesurface;
3646 Check information text of node
3649 ClientMap &map = client->getEnv().getClientMap();
3650 NodeMetadata *meta = map.getNodeMetadata(nodepos);
3653 infotext = utf8_to_wide(meta->getString("infotext"));
3655 MapNode n = map.getNodeNoEx(nodepos);
3657 if (nodedef_manager->get(n).tiledef[0].name == "unknown_node.png") {
3658 infotext = L"Unknown node: ";
3659 infotext += utf8_to_wide(nodedef_manager->get(n).name);
3663 if (runData->nodig_delay_timer <= 0.0 && input->getLeftState()
3664 && client->checkPrivilege("interact")) {
3665 handleDigging(runData, pointed, nodepos, playeritem_toolcap, dtime);
3668 if ((input->getRightClicked() ||
3669 runData->repeat_rightclick_timer >= m_repeat_right_click_time) &&
3670 client->checkPrivilege("interact")) {
3671 runData->repeat_rightclick_timer = 0;
3672 infostream << "Ground right-clicked" << std::endl;
3674 if (meta && meta->getString("formspec") != "" && !random_input
3675 && !input->isKeyDown(getKeySetting("keymap_sneak"))) {
3676 infostream << "Launching custom inventory view" << std::endl;
3678 InventoryLocation inventoryloc;
3679 inventoryloc.setNodeMeta(nodepos);
3681 NodeMetadataFormSource *fs_src = new NodeMetadataFormSource(
3682 &client->getEnv().getClientMap(), nodepos);
3683 TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client);
3685 create_formspec_menu(¤t_formspec, client, gamedef,
3686 texture_src, device, fs_src, txt_dst, client);
3688 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3690 // Report right click to server
3692 camera->setDigging(1); // right click animation (always shown for feedback)
3694 // If the wielded item has node placement prediction,
3696 bool placed = nodePlacementPrediction(*client,
3698 nodepos, neighbourpos);
3702 client->interact(3, pointed);
3704 soundmaker->m_player_rightpunch_sound =
3705 playeritem_def.sound_place;
3707 soundmaker->m_player_rightpunch_sound =
3710 if (playeritem_def.node_placement_prediction == "" ||
3711 nodedef_manager->get(map.getNodeNoEx(nodepos)).rightclickable) {
3712 client->interact(3, pointed); // Report to server
3714 soundmaker->m_player_rightpunch_sound =
3715 playeritem_def.sound_place_failed;
3723 void Game::handlePointingAtObject(GameRunData *runData,
3724 const PointedThing &pointed,
3725 const ItemStack &playeritem,
3726 const v3f &player_position,
3729 infotext = utf8_to_wide(runData->selected_object->infoText());
3731 if (infotext == L"" && show_debug) {
3732 infotext = utf8_to_wide(runData->selected_object->debugInfoText());
3735 if (input->getLeftState()) {
3736 bool do_punch = false;
3737 bool do_punch_damage = false;
3739 if (runData->object_hit_delay_timer <= 0.0) {
3741 do_punch_damage = true;
3742 runData->object_hit_delay_timer = object_hit_delay;
3745 if (input->getLeftClicked())
3749 infostream << "Left-clicked object" << std::endl;
3750 runData->left_punch = true;
3753 if (do_punch_damage) {
3754 // Report direct punch
3755 v3f objpos = runData->selected_object->getPosition();
3756 v3f dir = (objpos - player_position).normalize();
3758 bool disable_send = runData->selected_object->directReportPunch(
3759 dir, &playeritem, runData->time_from_last_punch);
3760 runData->time_from_last_punch = 0;
3763 client->interact(0, pointed);
3765 } else if (input->getRightClicked()) {
3766 infostream << "Right-clicked object" << std::endl;
3767 client->interact(3, pointed); // place
3772 void Game::handleDigging(GameRunData *runData,
3773 const PointedThing &pointed, const v3s16 &nodepos,
3774 const ToolCapabilities &playeritem_toolcap, f32 dtime)
3776 if (!runData->digging) {
3777 infostream << "Started digging" << std::endl;
3778 client->interact(0, pointed);
3779 runData->digging = true;
3780 runData->ldown_for_dig = true;
3783 LocalPlayer *player = client->getEnv().getLocalPlayer();
3784 ClientMap &map = client->getEnv().getClientMap();
3785 MapNode n = client->getEnv().getClientMap().getNodeNoEx(nodepos);
3787 // NOTE: Similar piece of code exists on the server side for
3789 // Get digging parameters
3790 DigParams params = getDigParams(nodedef_manager->get(n).groups,
3791 &playeritem_toolcap);
3793 // If can't dig, try hand
3794 if (!params.diggable) {
3795 const ItemDefinition &hand = itemdef_manager->get("");
3796 const ToolCapabilities *tp = hand.tool_capabilities;
3799 params = getDigParams(nodedef_manager->get(n).groups, tp);
3802 if (params.diggable == false) {
3803 // I guess nobody will wait for this long
3804 runData->dig_time_complete = 10000000.0;
3806 runData->dig_time_complete = params.time;
3808 if (m_cache_enable_particles) {
3809 const ContentFeatures &features =
3810 client->getNodeDefManager()->get(n);
3811 client->getParticleManager()->addPunchingParticles(gamedef, smgr,
3812 player, nodepos, features.tiles);
3816 if (runData->dig_time_complete >= 0.001) {
3817 runData->dig_index = (float)crack_animation_length
3819 / runData->dig_time_complete;
3821 // This is for torches
3822 runData->dig_index = crack_animation_length;
3825 SimpleSoundSpec sound_dig = nodedef_manager->get(n).sound_dig;
3827 if (sound_dig.exists() && params.diggable) {
3828 if (sound_dig.name == "__group") {
3829 if (params.main_group != "") {
3830 soundmaker->m_player_leftpunch_sound.gain = 0.5;
3831 soundmaker->m_player_leftpunch_sound.name =
3832 std::string("default_dig_") +
3836 soundmaker->m_player_leftpunch_sound = sound_dig;
3840 // Don't show cracks if not diggable
3841 if (runData->dig_time_complete >= 100000.0) {
3842 } else if (runData->dig_index < crack_animation_length) {
3843 //TimeTaker timer("client.setTempMod");
3844 //infostream<<"dig_index="<<dig_index<<std::endl;
3845 client->setCrack(runData->dig_index, nodepos);
3847 infostream << "Digging completed" << std::endl;
3848 client->interact(2, pointed);
3849 client->setCrack(-1, v3s16(0, 0, 0));
3850 bool is_valid_position;
3851 MapNode wasnode = map.getNodeNoEx(nodepos, &is_valid_position);
3852 if (is_valid_position)
3853 client->removeNode(nodepos);
3855 if (m_cache_enable_particles) {
3856 const ContentFeatures &features =
3857 client->getNodeDefManager()->get(wasnode);
3858 client->getParticleManager()->addDiggingParticles(gamedef, smgr,
3859 player, nodepos, features.tiles);
3862 runData->dig_time = 0;
3863 runData->digging = false;
3865 runData->nodig_delay_timer =
3866 runData->dig_time_complete / (float)crack_animation_length;
3868 // We don't want a corresponding delay to
3869 // very time consuming nodes
3870 if (runData->nodig_delay_timer > 0.3)
3871 runData->nodig_delay_timer = 0.3;
3873 // We want a slight delay to very little
3874 // time consuming nodes
3875 const float mindelay = 0.15;
3877 if (runData->nodig_delay_timer < mindelay)
3878 runData->nodig_delay_timer = mindelay;
3880 // Send event to trigger sound
3881 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
3882 gamedef->event()->put(e);
3885 if (runData->dig_time_complete < 100000.0) {
3886 runData->dig_time += dtime;
3888 runData->dig_time = 0;
3889 client->setCrack(-1, nodepos);
3892 camera->setDigging(0); // left click animation
3896 void Game::updateFrame(std::vector<aabb3f> &highlight_boxes,
3897 ProfilerGraph *graph, RunStats *stats, GameRunData *runData,
3898 f32 dtime, const VolatileRunFlags &flags, const CameraOrientation &cam)
3900 LocalPlayer *player = client->getEnv().getLocalPlayer();
3906 if (draw_control->range_all) {
3907 runData->fog_range = 100000 * BS;
3909 runData->fog_range = draw_control->wanted_range * BS
3910 + 0.0 * MAP_BLOCKSIZE * BS;
3911 runData->fog_range = MYMIN(
3913 (draw_control->farthest_drawn + 20) * BS);
3914 runData->fog_range *= 0.9;
3918 Calculate general brightness
3920 u32 daynight_ratio = client->getEnv().getDayNightRatio();
3921 float time_brightness = decode_light_f((float)daynight_ratio / 1000.0);
3922 float direct_brightness;
3925 if (g_settings->getBool("free_move")) {
3926 direct_brightness = time_brightness;
3927 sunlight_seen = true;
3929 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3930 float old_brightness = sky->getBrightness();
3931 direct_brightness = client->getEnv().getClientMap()
3932 .getBackgroundBrightness(MYMIN(runData->fog_range * 1.2, 60 * BS),
3933 daynight_ratio, (int)(old_brightness * 255.5), &sunlight_seen)
3937 float time_of_day = runData->time_of_day;
3938 float time_of_day_smooth = runData->time_of_day_smooth;
3940 time_of_day = client->getEnv().getTimeOfDayF();
3942 const float maxsm = 0.05;
3943 const float todsm = 0.05;
3945 if (fabs(time_of_day - time_of_day_smooth) > maxsm &&
3946 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3947 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3948 time_of_day_smooth = time_of_day;
3950 if (time_of_day_smooth > 0.8 && time_of_day < 0.2)
3951 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3952 + (time_of_day + 1.0) * todsm;
3954 time_of_day_smooth = time_of_day_smooth * (1.0 - todsm)
3955 + time_of_day * todsm;
3957 runData->time_of_day = time_of_day;
3958 runData->time_of_day_smooth = time_of_day_smooth;
3960 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3961 sunlight_seen, camera->getCameraMode(), player->getYaw(),
3962 player->getPitch());
3968 v3f player_position = player->getPosition();
3969 if (sky->getCloudsVisible()) {
3970 clouds->setVisible(true);
3971 clouds->step(dtime);
3972 clouds->update(v2f(player_position.X, player_position.Z),
3973 sky->getCloudColor());
3975 clouds->setVisible(false);
3982 client->getParticleManager()->step(dtime);
3988 if (m_cache_enable_fog && !flags.force_fog_off) {
3991 video::EFT_FOG_LINEAR,
3992 runData->fog_range * 0.4,
3993 runData->fog_range * 1.0,
4001 video::EFT_FOG_LINEAR,
4011 Get chat messages from client
4014 v2u32 screensize = driver->getScreenSize();
4016 updateChat(*client, dtime, flags.show_debug, screensize,
4017 flags.show_chat, runData->profiler_current_page,
4018 *chat_backend, guitext_chat);
4024 if (client->getPlayerItem() != runData->new_playeritem)
4025 client->selectPlayerItem(runData->new_playeritem);
4027 // Update local inventory if it has changed
4028 if (client->getLocalInventoryUpdated()) {
4029 //infostream<<"Updating local inventory"<<std::endl;
4030 client->getLocalInventory(*local_inventory);
4031 runData->update_wielded_item_trigger = true;
4034 if (runData->update_wielded_item_trigger) {
4035 // Update wielded tool
4036 InventoryList *mlist = local_inventory->getList("main");
4038 if (mlist && (client->getPlayerItem() < mlist->getSize())) {
4039 ItemStack item = mlist->getItem(client->getPlayerItem());
4040 camera->wield(item);
4042 runData->update_wielded_item_trigger = false;
4046 Update block draw list every 200ms or when camera direction has
4049 runData->update_draw_list_timer += dtime;
4051 v3f camera_direction = camera->getDirection();
4052 if (runData->update_draw_list_timer >= 0.2
4053 || runData->update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2
4054 || flags.camera_offset_changed) {
4055 runData->update_draw_list_timer = 0;
4056 client->getEnv().getClientMap().updateDrawList(driver);
4057 runData->update_draw_list_last_cam_dir = camera_direction;
4060 updateGui(&runData->statustext_time, *stats, *runData, dtime, flags, cam);
4063 make sure menu is on top
4064 1. Delete formspec menu reference if menu was removed
4065 2. Else, make sure formspec menu is on top
4067 if (current_formspec) {
4068 if (current_formspec->getReferenceCount() == 1) {
4069 current_formspec->drop();
4070 current_formspec = NULL;
4071 } else if (!noMenuActive()) {
4072 guiroot->bringToFront(current_formspec);
4080 video::SColor skycolor = sky->getSkyColor();
4082 TimeTaker tt_draw("mainloop: draw");
4084 TimeTaker timer("beginScene");
4085 driver->beginScene(true, true, skycolor);
4086 stats->beginscenetime = timer.stop(true);
4089 draw_scene(driver, smgr, *camera, *client, player, *hud, *mapper,
4090 guienv, highlight_boxes, screensize, skycolor, flags.show_hud,
4091 flags.show_minimap);
4096 if (flags.show_profiler_graph)
4097 graph->draw(10, screensize.Y - 10, driver, g_fontengine->getFont());
4102 if (runData->damage_flash > 0.0) {
4103 video::SColor color(std::min(runData->damage_flash, 180.0f),
4107 driver->draw2DRectangle(color,
4108 core::rect<s32>(0, 0, screensize.X, screensize.Y),
4111 runData->damage_flash -= 100.0 * dtime;
4117 if (player->hurt_tilt_timer > 0.0) {
4118 player->hurt_tilt_timer -= dtime * 5;
4120 if (player->hurt_tilt_timer < 0)
4121 player->hurt_tilt_strength = 0;
4125 Update minimap pos and rotation
4127 if (flags.show_minimap && flags.show_hud) {
4128 mapper->setPos(floatToInt(player->getPosition(), BS));
4129 mapper->setAngle(player->getYaw());
4136 TimeTaker timer("endScene");
4138 stats->endscenetime = timer.stop(true);
4141 stats->drawtime = tt_draw.stop(true);
4142 g_profiler->graphAdd("mainloop_draw", stats->drawtime / 1000.0f);
4146 inline static const char *yawToDirectionString(int yaw)
4148 // NOTE: TODO: This can be done mathematically without the else/else-if
4151 const char *player_direction;
4153 yaw = wrapDegrees_0_360(yaw);
4155 if (yaw >= 45 && yaw < 135)
4156 player_direction = "West [-X]";
4157 else if (yaw >= 135 && yaw < 225)
4158 player_direction = "South [-Z]";
4159 else if (yaw >= 225 && yaw < 315)
4160 player_direction = "East [+X]";
4162 player_direction = "North [+Z]";
4164 return player_direction;
4168 void Game::updateGui(float *statustext_time, const RunStats &stats,
4169 const GameRunData& runData, f32 dtime, const VolatileRunFlags &flags,
4170 const CameraOrientation &cam)
4172 v2u32 screensize = driver->getScreenSize();
4173 LocalPlayer *player = client->getEnv().getLocalPlayer();
4174 v3f player_position = player->getPosition();
4176 if (flags.show_debug) {
4177 static float drawtime_avg = 0;
4178 drawtime_avg = drawtime_avg * 0.95 + stats.drawtime * 0.05;
4180 u16 fps = 1.0 / stats.dtime_jitter.avg;
4181 //s32 fps = driver->getFPS();
4183 std::ostringstream os(std::ios_base::binary);
4185 << PROJECT_NAME_C " " << g_version_hash
4187 << " (R: range_all=" << draw_control->range_all << ")"
4188 << std::setprecision(0)
4189 << " drawtime = " << drawtime_avg
4190 << std::setprecision(1)
4191 << ", dtime_jitter = "
4192 << (stats.dtime_jitter.max_fraction * 100.0) << " %"
4193 << std::setprecision(1)
4194 << ", v_range = " << draw_control->wanted_range
4195 << std::setprecision(3)
4196 << ", RTT = " << client->getRTT();
4197 guitext->setText(utf8_to_wide(os.str()).c_str());
4198 guitext->setVisible(true);
4199 } else if (flags.show_hud || flags.show_chat) {
4200 std::ostringstream os(std::ios_base::binary);
4201 os << PROJECT_NAME_C " " << g_version_hash;
4202 guitext->setText(utf8_to_wide(os.str()).c_str());
4203 guitext->setVisible(true);
4205 guitext->setVisible(false);
4208 if (guitext->isVisible()) {
4209 core::rect<s32> rect(
4211 screensize.X, 5 + g_fontengine->getTextHeight()
4213 guitext->setRelativePosition(rect);
4216 if (flags.show_debug) {
4217 std::ostringstream os(std::ios_base::binary);
4218 os << std::setprecision(1) << std::fixed
4219 << "(" << (player_position.X / BS)
4220 << ", " << (player_position.Y / BS)
4221 << ", " << (player_position.Z / BS)
4222 << ") (yaw=" << (wrapDegrees_0_360(cam.camera_yaw))
4223 << " " << yawToDirectionString(cam.camera_yaw)
4224 << ") (seed = " << ((u64)client->getMapSeed())
4227 if (runData.pointed_old.type == POINTEDTHING_NODE) {
4228 ClientMap &map = client->getEnv().getClientMap();
4229 const INodeDefManager *nodedef = client->getNodeDefManager();
4230 MapNode n = map.getNodeNoEx(runData.pointed_old.node_undersurface);
4231 if (n.getContent() != CONTENT_IGNORE && nodedef->get(n).name != "unknown") {
4232 const ContentFeatures &features = nodedef->get(n);
4233 os << " (pointing_at = " << nodedef->get(n).name
4234 << " - " << features.tiledef[0].name.c_str()
4239 guitext2->setText(utf8_to_wide(os.str()).c_str());
4240 guitext2->setVisible(true);
4242 core::rect<s32> rect(
4243 5, 5 + g_fontengine->getTextHeight(),
4244 screensize.X, 5 + g_fontengine->getTextHeight() * 2
4246 guitext2->setRelativePosition(rect);
4248 guitext2->setVisible(false);
4251 guitext_info->setText(infotext.c_str());
4252 guitext_info->setVisible(flags.show_hud && g_menumgr.menuCount() == 0);
4254 float statustext_time_max = 1.5;
4256 if (!statustext.empty()) {
4257 *statustext_time += dtime;
4259 if (*statustext_time >= statustext_time_max) {
4261 *statustext_time = 0;
4265 guitext_status->setText(statustext.c_str());
4266 guitext_status->setVisible(!statustext.empty());
4268 if (!statustext.empty()) {
4269 s32 status_width = guitext_status->getTextWidth();
4270 s32 status_height = guitext_status->getTextHeight();
4271 s32 status_y = screensize.Y - 150;
4272 s32 status_x = (screensize.X - status_width) / 2;
4273 core::rect<s32> rect(
4274 status_x , status_y - status_height,
4275 status_x + status_width, status_y
4277 guitext_status->setRelativePosition(rect);
4280 video::SColor initial_color(255, 0, 0, 0);
4282 if (guienv->getSkin())
4283 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
4285 video::SColor final_color = initial_color;
4286 final_color.setAlpha(0);
4287 video::SColor fade_color = initial_color.getInterpolated_quadratic(
4288 initial_color, final_color,
4289 pow(*statustext_time / statustext_time_max, 2.0f));
4290 guitext_status->setOverrideColor(fade_color);
4291 guitext_status->enableOverrideColor(true);
4296 /* Log times and stuff for visualization */
4297 inline void Game::updateProfilerGraphs(ProfilerGraph *graph)
4299 Profiler::GraphValues values;
4300 g_profiler->graphGet(values);
4306 /****************************************************************************
4308 ****************************************************************************/
4310 /* On some computers framerate doesn't seem to be automatically limited
4312 inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime)
4314 // not using getRealTime is necessary for wine
4315 device->getTimer()->tick(); // Maker sure device time is up-to-date
4316 u32 time = device->getTimer()->getTime();
4317 u32 last_time = fps_timings->last_time;
4319 if (time > last_time) // Make sure time hasn't overflowed
4320 fps_timings->busy_time = time - last_time;
4322 fps_timings->busy_time = 0;
4324 u32 frametime_min = 1000 / (g_menumgr.pausesGame()
4325 ? g_settings->getFloat("pause_fps_max")
4326 : g_settings->getFloat("fps_max"));
4328 if (fps_timings->busy_time < frametime_min) {
4329 fps_timings->sleep_time = frametime_min - fps_timings->busy_time;
4330 device->sleep(fps_timings->sleep_time);
4332 fps_timings->sleep_time = 0;
4335 /* Get the new value of the device timer. Note that device->sleep() may
4336 * not sleep for the entire requested time as sleep may be interrupted and
4337 * therefore it is arguably more accurate to get the new time from the
4338 * device rather than calculating it by adding sleep_time to time.
4341 device->getTimer()->tick(); // Update device timer
4342 time = device->getTimer()->getTime();
4344 if (time > last_time) // Make sure last_time hasn't overflowed
4345 *dtime = (time - last_time) / 1000.0;
4349 fps_timings->last_time = time;
4352 // Note: This will free (using delete[])! \p msg. If you want to use it later,
4353 // pass a copy of it to this function
4354 // Note: \p msg must be allocated using new (not malloc())
4355 void Game::showOverlayMessage(const wchar_t *msg, float dtime,
4356 int percent, bool draw_clouds)
4358 draw_load_screen(msg, device, guienv, dtime, percent, draw_clouds);
4362 void Game::settingChangedCallback(const std::string &setting_name, void *data)
4364 ((Game *)data)->readSettings();
4367 void Game::readSettings()
4369 m_cache_doubletap_jump = g_settings->getBool("doubletap_jump");
4370 m_cache_enable_node_highlighting = g_settings->getBool("enable_node_highlighting");
4371 m_cache_enable_clouds = g_settings->getBool("enable_clouds");
4372 m_cache_enable_particles = g_settings->getBool("enable_particles");
4373 m_cache_enable_fog = g_settings->getBool("enable_fog");
4374 m_cache_mouse_sensitivity = g_settings->getFloat("mouse_sensitivity");
4375 m_repeat_right_click_time = g_settings->getFloat("repeat_rightclick_time");
4377 m_cache_mouse_sensitivity = rangelim(m_cache_mouse_sensitivity, 0.001, 100.0);
4380 /****************************************************************************/
4381 /****************************************************************************
4383 ****************************************************************************/
4384 /****************************************************************************/
4386 void Game::extendedResourceCleanup()
4388 // Extended resource accounting
4389 infostream << "Irrlicht resources after cleanup:" << std::endl;
4390 infostream << "\tRemaining meshes : "
4391 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
4392 infostream << "\tRemaining textures : "
4393 << driver->getTextureCount() << std::endl;
4395 for (unsigned int i = 0; i < driver->getTextureCount(); i++) {
4396 irr::video::ITexture *texture = driver->getTextureByIndex(i);
4397 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
4401 clearTextureNameCache();
4402 infostream << "\tRemaining materials: "
4403 << driver-> getMaterialRendererCount()
4404 << " (note: irrlicht doesn't support removing renderers)" << std::endl;
4408 /****************************************************************************/
4409 /****************************************************************************
4410 extern function for launching the game
4411 ****************************************************************************/
4412 /****************************************************************************/
4414 void the_game(bool *kill,
4416 InputHandler *input,
4417 IrrlichtDevice *device,
4419 const std::string &map_dir,
4420 const std::string &playername,
4421 const std::string &password,
4422 const std::string &address, // If empty local server is created
4425 std::string &error_message,
4426 ChatBackend &chat_backend,
4427 bool *reconnect_requested,
4428 const SubgameSpec &gamespec, // Used for local game
4429 bool simple_singleplayer_mode)
4433 /* Make a copy of the server address because if a local singleplayer server
4434 * is created then this is updated and we don't want to change the value
4435 * passed to us by the calling function
4437 std::string server_address = address;
4441 if (game.startup(kill, random_input, input, device, map_dir,
4442 playername, password, &server_address, port, error_message,
4443 reconnect_requested, &chat_backend, gamespec,
4444 simple_singleplayer_mode)) {
4449 } catch (SerializationError &e) {
4450 error_message = std::string("A serialization error occurred:\n")
4451 + e.what() + "\n\nThe server is probably "
4452 " running a different version of " PROJECT_NAME_C ".";
4453 errorstream << error_message << std::endl;
4454 } catch (ServerError &e) {
4455 error_message = e.what();
4456 errorstream << "ServerError: " << error_message << std::endl;
4457 } catch (ModError &e) {
4458 error_message = e.what() + strgettext("\nCheck debug.txt for details.");
4459 errorstream << "ModError: " << error_message << std::endl;