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.
21 #include "irrlichttypes_extrabloated.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
27 #include <IMaterialRendererServices.h>
28 #include "IMeshCache.h"
31 #include "guiPasswordChange.h"
32 #include "guiVolumeChange.h"
33 #include "guiFormSpecMenu.h"
34 #include "guiTextInputMenu.h"
36 #include "guiChatConsole.h"
40 #include "particles.h"
45 #include "mainmenumanager.h"
49 // Needed for determining pointing to nodes
51 #include "nodemetadata.h"
52 #include "main.h" // For g_settings
54 #include "tile.h" // For TextureSource
55 #include "shader.h" // For ShaderSource
56 #include "logoutputbuffer.h"
58 #include "quicktune_shortcutter.h"
59 #include "clientmap.h"
64 #include "sound_openal.h"
66 #include "event_manager.h"
69 #include "util/directiontables.h"
70 #include "util/pointedthing.h"
71 #include "drawscene.h"
72 #include "content_cao.h"
78 struct TextDestNodeMetadata : public TextDest
80 TextDestNodeMetadata(v3s16 p, Client *client)
85 // This is deprecated I guess? -celeron55
86 void gotText(std::wstring text)
88 std::string ntext = wide_to_narrow(text);
89 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
90 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
91 std::map<std::string, std::string> fields;
92 fields["text"] = ntext;
93 m_client->sendNodemetaFields(m_p, "", fields);
95 void gotText(std::map<std::string, std::string> fields)
97 m_client->sendNodemetaFields(m_p, "", fields);
104 struct TextDestPlayerInventory : public TextDest
106 TextDestPlayerInventory(Client *client)
111 TextDestPlayerInventory(Client *client, std::string formname)
114 m_formname = formname;
116 void gotText(std::map<std::string, std::string> fields)
118 m_client->sendInventoryFields(m_formname, fields);
124 struct LocalFormspecHandler : public TextDest
126 LocalFormspecHandler();
127 LocalFormspecHandler(std::string formname) :
130 m_formname = formname;
133 LocalFormspecHandler(std::string formname, Client *client) :
136 m_formname = formname;
139 void gotText(std::wstring message) {
140 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
143 void gotText(std::map<std::string, std::string> fields)
145 if (m_formname == "MT_PAUSE_MENU") {
146 if (fields.find("btn_sound") != fields.end()) {
147 g_gamecallback->changeVolume();
151 if (fields.find("btn_exit_menu") != fields.end()) {
152 g_gamecallback->disconnect();
156 if (fields.find("btn_exit_os") != fields.end()) {
157 g_gamecallback->exitToOS();
161 if (fields.find("btn_change_password") != fields.end()) {
162 g_gamecallback->changePassword();
166 if (fields.find("quit") != fields.end()) {
170 if (fields.find("btn_continue") != fields.end()) {
174 if (m_formname == "MT_CHAT_MENU") {
175 assert(m_client != 0);
176 if ((fields.find("btn_send") != fields.end()) ||
177 (fields.find("quit") != fields.end())) {
178 if (fields.find("f_text") != fields.end()) {
179 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
185 if (m_formname == "MT_DEATH_SCREEN") {
186 assert(m_client != 0);
187 if ((fields.find("btn_respawn") != fields.end())) {
188 m_client->sendRespawn();
192 if (fields.find("quit") != fields.end()) {
193 m_client->sendRespawn();
198 // don't show error message for unhandled cursor keys
199 if ( (fields.find("key_up") != fields.end()) ||
200 (fields.find("key_down") != fields.end()) ||
201 (fields.find("key_left") != fields.end()) ||
202 (fields.find("key_right") != fields.end())) {
206 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
208 for (std::map<std::string,std::string>::iterator iter = fields.begin();
209 iter != fields.end(); iter++) {
210 errorstream << "\t"<< i << ": " << iter->first << "=" << iter->second << std::endl;
218 /* Form update callback */
220 class NodeMetadataFormSource: public IFormSource
223 NodeMetadataFormSource(ClientMap *map, v3s16 p):
228 std::string getForm()
230 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
233 return meta->getString("formspec");
235 std::string resolveText(std::string str)
237 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
240 return meta->resolveString(str);
247 class PlayerInventoryFormSource: public IFormSource
250 PlayerInventoryFormSource(Client *client):
254 std::string getForm()
256 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
257 return player->inventory_formspec;
264 Check if a node is pointable
266 inline bool isPointableNode(const MapNode& n,
267 Client *client, bool liquids_pointable)
269 const ContentFeatures &features = client->getNodeDefManager()->get(n);
270 return features.pointable ||
271 (liquids_pointable && features.isLiquid());
275 Find what the player is pointing at
277 PointedThing getPointedThing(Client *client, v3f player_position,
278 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
279 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
280 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
284 hilightboxes.clear();
285 selected_object = NULL;
287 INodeDefManager *nodedef = client->getNodeDefManager();
288 ClientMap &map = client->getEnv().getClientMap();
290 f32 mindistance = BS * 1001;
292 // First try to find a pointed at active object
295 selected_object = client->getSelectedActiveObject(d*BS,
296 camera_position, shootline);
298 if(selected_object != NULL)
300 if(selected_object->doShowSelectionBox())
302 aabb3f *selection_box = selected_object->getSelectionBox();
303 // Box should exist because object was
304 // returned in the first place
305 assert(selection_box);
307 v3f pos = selected_object->getPosition();
308 hilightboxes.push_back(aabb3f(
309 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
310 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
313 mindistance = (selected_object->getPosition() - camera_position).getLength();
315 result.type = POINTEDTHING_OBJECT;
316 result.object_id = selected_object->getId();
320 // That didn't work, try to find a pointed at node
323 v3s16 pos_i = floatToInt(player_position, BS);
325 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
329 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
330 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
331 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
332 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
333 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
334 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
336 // Prevent signed number overflow
344 for(s16 y = ystart; y <= yend; y++)
345 for(s16 z = zstart; z <= zend; z++)
346 for(s16 x = xstart; x <= xend; x++)
351 n = map.getNode(v3s16(x,y,z));
353 catch(InvalidPositionException &e)
357 if(!isPointableNode(n, client, liquids_pointable))
360 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
363 v3f npf = intToFloat(np, BS);
365 for(std::vector<aabb3f>::const_iterator
367 i != boxes.end(); i++)
373 for(u16 j=0; j<6; j++)
375 v3s16 facedir = g_6dirs[j];
376 aabb3f facebox = box;
380 facebox.MinEdge.X = facebox.MaxEdge.X-d;
381 else if(facedir.X < 0)
382 facebox.MaxEdge.X = facebox.MinEdge.X+d;
383 else if(facedir.Y > 0)
384 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
385 else if(facedir.Y < 0)
386 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
387 else if(facedir.Z > 0)
388 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
389 else if(facedir.Z < 0)
390 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
392 v3f centerpoint = facebox.getCenter();
393 f32 distance = (centerpoint - camera_position).getLength();
394 if(distance >= mindistance)
396 if(!facebox.intersectsWithLine(shootline))
399 v3s16 np_above = np + facedir;
401 result.type = POINTEDTHING_NODE;
402 result.node_undersurface = np;
403 result.node_abovesurface = np_above;
404 mindistance = distance;
406 hilightboxes.clear();
407 for(std::vector<aabb3f>::const_iterator
409 i2 != boxes.end(); i2++)
412 box.MinEdge += npf + v3f(-d,-d,-d) - intToFloat(camera_offset, BS);
413 box.MaxEdge += npf + v3f(d,d,d) - intToFloat(camera_offset, BS);
414 hilightboxes.push_back(box);
423 /* Profiler display */
425 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
426 gui::IGUIFont *font, u32 text_height, u32 show_profiler,
427 u32 show_profiler_max)
429 if(show_profiler == 0)
431 guitext_profiler->setVisible(false);
436 std::ostringstream os(std::ios_base::binary);
437 g_profiler->printPage(os, show_profiler, show_profiler_max);
438 std::wstring text = narrow_to_wide(os.str());
439 guitext_profiler->setText(text.c_str());
440 guitext_profiler->setVisible(true);
442 s32 w = font->getDimension(text.c_str()).Width;
445 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
446 8+(text_height+5)*2 +
447 font->getDimension(text.c_str()).Height);
448 guitext_profiler->setRelativePosition(rect);
449 guitext_profiler->setVisible(true);
457 Profiler::GraphValues values;
463 Meta(float initial=0, video::SColor color=
464 video::SColor(255,255,255,255)):
470 std::list<Piece> m_log;
478 void put(const Profiler::GraphValues &values)
481 piece.values = values;
482 m_log.push_back(piece);
483 while(m_log.size() > m_log_max_size)
484 m_log.erase(m_log.begin());
487 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
488 gui::IGUIFont* font) const
490 std::map<std::string, Meta> m_meta;
491 for(std::list<Piece>::const_iterator k = m_log.begin();
492 k != m_log.end(); k++)
494 const Piece &piece = *k;
495 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
496 i != piece.values.end(); i++){
497 const std::string &id = i->first;
498 const float &value = i->second;
499 std::map<std::string, Meta>::iterator j =
501 if(j == m_meta.end()){
502 m_meta[id] = Meta(value);
505 if(value < j->second.min)
506 j->second.min = value;
507 if(value > j->second.max)
508 j->second.max = value;
513 static const video::SColor usable_colors[] = {
514 video::SColor(255,255,100,100),
515 video::SColor(255,90,225,90),
516 video::SColor(255,100,100,255),
517 video::SColor(255,255,150,50),
518 video::SColor(255,220,220,100)
520 static const u32 usable_colors_count =
521 sizeof(usable_colors) / sizeof(*usable_colors);
522 u32 next_color_i = 0;
523 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
524 i != m_meta.end(); i++){
525 Meta &meta = i->second;
526 video::SColor color(255,200,200,200);
527 if(next_color_i < usable_colors_count)
528 color = usable_colors[next_color_i++];
533 s32 textx = x_left + m_log_max_size + 15;
534 s32 textx2 = textx + 200 - 15;
538 u32 num_graphs = m_meta.size();
539 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
541 video::SColor bgcolor(120,0,0,0);
542 driver->draw2DRectangle(bgcolor, rect, NULL);
546 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
547 i != m_meta.end(); i++){
548 const std::string &id = i->first;
549 const Meta &meta = i->second;
551 s32 y = y_bottom - meta_i * 50;
552 float show_min = meta.min;
553 float show_max = meta.max;
554 if(show_min >= -0.0001 && show_max >= -0.0001){
555 if(show_min <= show_max * 0.5)
560 snprintf(buf, 10, "%.3g", show_max);
561 font->draw(narrow_to_wide(buf).c_str(),
562 core::rect<s32>(textx, y - graphh,
563 textx2, y - graphh + texth),
565 snprintf(buf, 10, "%.3g", show_min);
566 font->draw(narrow_to_wide(buf).c_str(),
567 core::rect<s32>(textx, y - texth,
570 font->draw(narrow_to_wide(id).c_str(),
571 core::rect<s32>(textx, y - graphh/2 - texth/2,
572 textx2, y - graphh/2 + texth/2),
575 s32 graph1h = graphh;
576 bool relativegraph = (show_min != 0 && show_min != show_max);
577 float lastscaledvalue = 0.0;
578 bool lastscaledvalue_exists = false;
579 for(std::list<Piece>::const_iterator j = m_log.begin();
580 j != m_log.end(); j++)
582 const Piece &piece = *j;
584 bool value_exists = false;
585 Profiler::GraphValues::const_iterator k =
586 piece.values.find(id);
587 if(k != piece.values.end()){
593 lastscaledvalue_exists = false;
596 float scaledvalue = 1.0;
597 if(show_max != show_min)
598 scaledvalue = (value - show_min) / (show_max - show_min);
599 if(scaledvalue == 1.0 && value == 0){
601 lastscaledvalue_exists = false;
605 if(lastscaledvalue_exists){
606 s32 ivalue1 = lastscaledvalue * graph1h;
607 s32 ivalue2 = scaledvalue * graph1h;
608 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
609 v2s32(x, graph1y - ivalue2), meta.color);
611 lastscaledvalue = scaledvalue;
612 lastscaledvalue_exists = true;
614 s32 ivalue = scaledvalue * graph1h;
615 driver->draw2DLine(v2s32(x, graph1y),
616 v2s32(x, graph1y - ivalue), meta.color);
625 class NodeDugEvent: public MtEvent
631 NodeDugEvent(v3s16 p, MapNode n):
635 const char* getType() const
641 ISoundManager *m_sound;
642 INodeDefManager *m_ndef;
644 float m_player_step_timer;
646 SimpleSoundSpec m_player_step_sound;
647 SimpleSoundSpec m_player_leftpunch_sound;
648 SimpleSoundSpec m_player_rightpunch_sound;
650 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
653 m_player_step_timer(0)
657 void playPlayerStep()
659 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
660 m_player_step_timer = 0.03;
661 m_sound->playSound(m_player_step_sound, false);
665 static void viewBobbingStep(MtEvent *e, void *data)
667 SoundMaker *sm = (SoundMaker*)data;
668 sm->playPlayerStep();
671 static void playerRegainGround(MtEvent *e, void *data)
673 SoundMaker *sm = (SoundMaker*)data;
674 sm->playPlayerStep();
677 static void playerJump(MtEvent *e, void *data)
679 //SoundMaker *sm = (SoundMaker*)data;
682 static void cameraPunchLeft(MtEvent *e, void *data)
684 SoundMaker *sm = (SoundMaker*)data;
685 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
688 static void cameraPunchRight(MtEvent *e, void *data)
690 SoundMaker *sm = (SoundMaker*)data;
691 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
694 static void nodeDug(MtEvent *e, void *data)
696 SoundMaker *sm = (SoundMaker*)data;
697 NodeDugEvent *nde = (NodeDugEvent*)e;
698 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
701 static void playerDamage(MtEvent *e, void *data)
703 SoundMaker *sm = (SoundMaker*)data;
704 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
707 static void playerFallingDamage(MtEvent *e, void *data)
709 SoundMaker *sm = (SoundMaker*)data;
710 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
713 void registerReceiver(MtEventManager *mgr)
715 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
716 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
717 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
718 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
719 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
720 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
721 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
722 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
725 void step(float dtime)
727 m_player_step_timer -= dtime;
731 // Locally stored sounds don't need to be preloaded because of this
732 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
734 std::set<std::string> m_fetched;
737 void fetchSounds(const std::string &name,
738 std::set<std::string> &dst_paths,
739 std::set<std::string> &dst_datas)
741 if(m_fetched.count(name))
743 m_fetched.insert(name);
744 std::string base = porting::path_share + DIR_DELIM + "testsounds";
745 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
746 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
747 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
748 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
749 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
750 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
751 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
752 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
753 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
754 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
755 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
759 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
762 bool *m_force_fog_off;
767 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
768 f32 *fog_range, Client *client):
770 m_force_fog_off(force_fog_off),
771 m_fog_range(fog_range),
774 ~GameGlobalShaderConstantSetter() {}
776 virtual void onSetConstants(video::IMaterialRendererServices *services,
783 video::SColor bgcolor = m_sky->getBgColor();
784 video::SColorf bgcolorf(bgcolor);
785 float bgcolorfa[4] = {
791 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
794 float fog_distance = 10000*BS;
795 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
796 fog_distance = *m_fog_range;
797 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
800 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
801 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
802 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
804 u32 animation_timer = porting::getTimeMs() % 100000;
805 float animation_timer_f = (float)animation_timer / 100000.0;
806 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
807 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
809 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
810 v3f eye_position = player->getEyePosition();
811 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
812 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
814 // Uniform sampler layers
818 // before 1.8 there isn't a "integer interface", only float
819 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
820 services->setPixelShaderConstant("baseTexture" , (irr::f32*)&layer0, 1);
821 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
822 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
824 services->setPixelShaderConstant("baseTexture" , (irr::s32*)&layer0, 1);
825 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
826 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
831 bool nodePlacementPrediction(Client &client,
832 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
834 std::string prediction = playeritem_def.node_placement_prediction;
835 INodeDefManager *nodedef = client.ndef();
836 ClientMap &map = client.getEnv().getClientMap();
838 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
840 verbosestream<<"Node placement prediction for "
841 <<playeritem_def.name<<" is "
842 <<prediction<<std::endl;
843 v3s16 p = neighbourpos;
844 // Place inside node itself if buildable_to
846 MapNode n_under = map.getNode(nodepos);
847 if(nodedef->get(n_under).buildable_to)
849 else if (!nodedef->get(map.getNode(p)).buildable_to)
851 }catch(InvalidPositionException &e){}
852 // Find id of predicted node
854 bool found = nodedef->getId(prediction, id);
856 errorstream<<"Node placement prediction failed for "
857 <<playeritem_def.name<<" (places "
859 <<") - Name not known"<<std::endl;
862 // Predict param2 for facedir and wallmounted nodes
864 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
865 v3s16 dir = nodepos - neighbourpos;
866 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
867 param2 = dir.Y < 0 ? 1 : 0;
868 } else if(abs(dir.X) > abs(dir.Z)){
869 param2 = dir.X < 0 ? 3 : 2;
871 param2 = dir.Z < 0 ? 5 : 4;
874 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
875 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
876 if(abs(dir.X) > abs(dir.Z)){
877 param2 = dir.X < 0 ? 3 : 1;
879 param2 = dir.Z < 0 ? 2 : 0;
882 assert(param2 >= 0 && param2 <= 5);
883 //Check attachment if node is in group attached_node
884 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
885 static v3s16 wallmounted_dirs[8] = {
894 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
895 pp = p + wallmounted_dirs[param2];
897 pp = p + v3s16(0,-1,0);
898 if(!nodedef->get(map.getNode(pp)).walkable)
901 // Add node to client map
902 MapNode n(id, 0, param2);
904 LocalPlayer* player = client.getEnv().getLocalPlayer();
906 // Dont place node when player would be inside new node
907 // NOTE: This is to be eventually implemented by a mod as client-side Lua
908 if (!nodedef->get(n).walkable ||
909 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
910 (nodedef->get(n).walkable &&
911 neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
912 neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
914 // This triggers the required mesh update too
915 client.addNode(p, n);
918 }catch(InvalidPositionException &e){
919 errorstream<<"Node placement prediction failed for "
920 <<playeritem_def.name<<" (places "
922 <<") - Position not loaded"<<std::endl;
928 static inline void create_formspec_menu(GUIFormSpecMenu** cur_formspec,
929 InventoryManager *invmgr, IGameDef *gamedef,
930 IWritableTextureSource* tsrc, IrrlichtDevice * device,
931 IFormSource* fs_src, TextDest* txt_dest
934 if (*cur_formspec == 0) {
935 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
936 invmgr, gamedef, tsrc, fs_src, txt_dest, cur_formspec );
937 (*cur_formspec)->doPause = false;
938 (*cur_formspec)->drop();
941 (*cur_formspec)->setFormSource(fs_src);
942 (*cur_formspec)->setTextDest(txt_dest);
946 static void show_chat_menu(GUIFormSpecMenu** cur_formspec,
947 InventoryManager *invmgr, IGameDef *gamedef,
948 IWritableTextureSource* tsrc, IrrlichtDevice * device,
949 Client* client, std::string text)
951 std::string formspec =
953 "field[3,2.35;6,0.5;f_text;;" + text + "]"
954 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
958 /* Note: FormspecFormSource and LocalFormspecHandler
959 * are deleted by guiFormSpecMenu */
960 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
961 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
963 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst);
966 static void show_deathscreen(GUIFormSpecMenu** cur_formspec,
967 InventoryManager *invmgr, IGameDef *gamedef,
968 IWritableTextureSource* tsrc, IrrlichtDevice * device, Client* client)
970 std::string formspec =
973 "bgcolor[#320000b4;true]"
974 "label[4.85,1.35;You died.]"
975 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
979 /* Note: FormspecFormSource and LocalFormspecHandler
980 * are deleted by guiFormSpecMenu */
981 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
982 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
984 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst);
987 /******************************************************************************/
988 static void show_pause_menu(GUIFormSpecMenu** cur_formspec,
989 InventoryManager *invmgr, IGameDef *gamedef,
990 IWritableTextureSource* tsrc, IrrlichtDevice * device,
991 bool singleplayermode)
993 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
995 "- Space: jump/climb\n"
996 "- Shift: sneak/go down\n"
999 "- Mouse: turn/look\n"
1000 "- Mouse left: dig/punch\n"
1001 "- Mouse right: place/use\n"
1002 "- Mouse wheel: select item\n"
1006 float ypos = singleplayermode ? 1.0 : 0.5;
1007 std::ostringstream os;
1009 os << "size[11,5.5,true]"
1010 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1011 << wide_to_narrow(wstrgettext("Continue")) << "]";
1013 if (!singleplayermode) {
1014 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1015 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1018 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1019 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1020 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1021 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1022 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1023 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1024 << "textarea[7.5,0.25;3.75,6;;" << control_text << ";]"
1025 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1026 << minetest_build_info << "\n"
1027 << "path_user = " << wrap_rows(porting::path_user, 20)
1031 /* Note: FormspecFormSource and LocalFormspecHandler *
1032 * are deleted by guiFormSpecMenu */
1033 FormspecFormSource* fs_src = new FormspecFormSource(os.str());
1034 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1036 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst);
1038 if (singleplayermode) {
1039 (*cur_formspec)->doPause = true;
1043 /******************************************************************************/
1044 void the_game(bool &kill, bool random_input, InputHandler *input,
1045 IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1046 std::string playername, std::string password,
1047 std::string address /* If "", local server is used */,
1048 u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1049 const SubgameSpec &gamespec /* Used for local game */,
1050 bool simple_singleplayer_mode)
1052 GUIFormSpecMenu* current_formspec = 0;
1053 video::IVideoDriver* driver = device->getVideoDriver();
1054 scene::ISceneManager* smgr = device->getSceneManager();
1056 // Calculate text height using the font
1057 u32 text_height = font->getDimension(L"Random test string").Height;
1060 Draw "Loading" screen
1064 wchar_t* text = wgettext("Loading...");
1065 draw_load_screen(text, device, guienv, font, 0, 0);
1069 // Create texture source
1070 IWritableTextureSource *tsrc = createTextureSource(device);
1072 // Create shader source
1073 IWritableShaderSource *shsrc = createShaderSource(device);
1075 // These will be filled by data received from the server
1076 // Create item definition manager
1077 IWritableItemDefManager *itemdef = createItemDefManager();
1078 // Create node definition manager
1079 IWritableNodeDefManager *nodedef = createNodeDefManager();
1081 // Sound fetcher (useful when testing)
1082 GameOnDemandSoundFetcher soundfetcher;
1085 ISoundManager *sound = NULL;
1086 bool sound_is_dummy = false;
1088 if(g_settings->getBool("enable_sound")){
1089 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1090 sound = createOpenALSoundManager(&soundfetcher);
1092 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1094 infostream<<"Sound disabled."<<std::endl;
1098 infostream<<"Using dummy audio."<<std::endl;
1099 sound = &dummySoundManager;
1100 sound_is_dummy = true;
1103 Server *server = NULL;
1107 EventManager eventmgr;
1110 SoundMaker soundmaker(sound, nodedef);
1111 soundmaker.registerReceiver(&eventmgr);
1113 // Add chat log output for errors to be shown in chat
1114 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1116 // Create UI for modifying quicktune values
1117 QuicktuneShortcutter quicktune;
1124 wchar_t* text = wgettext("Creating server....");
1125 draw_load_screen(text, device, guienv, font, 0, 25);
1127 infostream<<"Creating server"<<std::endl;
1129 std::string bind_str = g_settings->get("bind_address");
1130 Address bind_addr(0,0,0,0, port);
1132 if (g_settings->getBool("ipv6_server")) {
1133 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1136 bind_addr.Resolve(bind_str.c_str());
1138 } catch (ResolveError &e) {
1139 infostream << "Resolving bind address \"" << bind_str
1140 << "\" failed: " << e.what()
1141 << " -- Listening on all addresses." << std::endl;
1144 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1145 error_message = L"Unable to listen on " +
1146 narrow_to_wide(bind_addr.serializeString()) +
1147 L" because IPv6 is disabled";
1148 errorstream<<wide_to_narrow(error_message)<<std::endl;
1149 // Break out of client scope
1153 server = new Server(map_dir, gamespec,
1154 simple_singleplayer_mode,
1155 bind_addr.isIPv6());
1157 server->start(bind_addr);
1160 do{ // Client scope (breakable do-while(0))
1167 wchar_t* text = wgettext("Creating client...");
1168 draw_load_screen(text, device, guienv, font, 0, 50);
1171 infostream<<"Creating client"<<std::endl;
1173 MapDrawControl draw_control;
1176 wchar_t* text = wgettext("Resolving address...");
1177 draw_load_screen(text, device, guienv, font, 0, 75);
1180 Address connect_address(0,0,0,0, port);
1182 connect_address.Resolve(address.c_str());
1183 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1184 //connect_address.Resolve("localhost");
1185 if (connect_address.isIPv6()) {
1186 IPv6AddressBytes addr_bytes;
1187 addr_bytes.bytes[15] = 1;
1188 connect_address.setAddress(&addr_bytes);
1190 connect_address.setAddress(127,0,0,1);
1194 catch(ResolveError &e) {
1195 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1196 errorstream<<wide_to_narrow(error_message)<<std::endl;
1197 // Break out of client scope
1200 if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1201 error_message = L"Unable to connect to " +
1202 narrow_to_wide(connect_address.serializeString()) +
1203 L" because IPv6 is disabled";
1204 errorstream<<wide_to_narrow(error_message)<<std::endl;
1205 // Break out of client scope
1212 Client client(device, playername.c_str(), password, draw_control,
1213 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1214 connect_address.isIPv6());
1216 // Client acts as our GameDef
1217 IGameDef *gamedef = &client;
1220 Attempt to connect to the server
1223 infostream<<"Connecting to server at ";
1224 connect_address.print(&infostream);
1225 infostream<<std::endl;
1226 client.connect(connect_address);
1229 Wait for server to accept connection
1231 bool could_connect = false;
1232 bool connect_aborted = false;
1234 float time_counter = 0.0;
1236 float fps_max = g_settings->getFloat("fps_max");
1237 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1238 u32 lasttime = device->getTimer()->getTime();
1239 while(device->run())
1241 f32 dtime = 0.033; // in seconds
1242 if (cloud_menu_background) {
1243 u32 time = device->getTimer()->getTime();
1245 dtime = (time - lasttime) / 1000.0;
1250 // Update client and server
1253 server->step(dtime);
1256 if(client.getState() == LC_Init){
1257 could_connect = true;
1261 if(client.accessDenied()){
1262 error_message = L"Access denied. Reason: "
1263 +client.accessDeniedReason();
1264 errorstream<<wide_to_narrow(error_message)<<std::endl;
1267 if(input->wasKeyDown(EscapeKey)){
1268 connect_aborted = true;
1269 infostream<<"Connect aborted [Escape]"<<std::endl;
1275 wchar_t* text = wgettext("Connecting to server...");
1276 draw_load_screen(text, device, guienv, font, dtime, 100);
1280 // On some computers framerate doesn't seem to be
1281 // automatically limited
1282 if (cloud_menu_background) {
1283 // Time of frame without fps limit
1286 // not using getRealTime is necessary for wine
1287 u32 time = device->getTimer()->getTime();
1289 busytime_u32 = time - lasttime;
1292 busytime = busytime_u32 / 1000.0;
1295 u32 frametime_min = 1000./fps_max;
1297 if(busytime_u32 < frametime_min) {
1298 u32 sleeptime = frametime_min - busytime_u32;
1299 device->sleep(sleeptime);
1304 time_counter += dtime;
1307 catch(con::PeerNotFoundException &e)
1311 Handle failure to connect
1314 if(error_message == L"" && !connect_aborted){
1315 error_message = L"Connection failed";
1316 errorstream<<wide_to_narrow(error_message)<<std::endl;
1318 // Break out of client scope
1323 Wait until content has been received
1325 bool got_content = false;
1326 bool content_aborted = false;
1328 float time_counter = 0.0;
1330 float fps_max = g_settings->getFloat("fps_max");
1331 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1332 u32 lasttime = device->getTimer()->getTime();
1333 while(device->run())
1335 f32 dtime = 0.033; // in seconds
1336 if (cloud_menu_background) {
1337 u32 time = device->getTimer()->getTime();
1339 dtime = (time - lasttime) / 1000.0;
1344 // Update client and server
1347 server->step(dtime);
1350 if(client.mediaReceived() &&
1351 client.itemdefReceived() &&
1352 client.nodedefReceived()){
1357 if(client.accessDenied()){
1358 error_message = L"Access denied. Reason: "
1359 +client.accessDeniedReason();
1360 errorstream<<wide_to_narrow(error_message)<<std::endl;
1363 if(client.getState() < LC_Init){
1364 error_message = L"Client disconnected";
1365 errorstream<<wide_to_narrow(error_message)<<std::endl;
1368 if(input->wasKeyDown(EscapeKey)){
1369 content_aborted = true;
1370 infostream<<"Connect aborted [Escape]"<<std::endl;
1376 if (!client.itemdefReceived())
1378 wchar_t* text = wgettext("Item definitions...");
1380 draw_load_screen(text, device, guienv, font, dtime, progress);
1383 else if (!client.nodedefReceived())
1385 wchar_t* text = wgettext("Node definitions...");
1387 draw_load_screen(text, device, guienv, font, dtime, progress);
1393 std::stringstream message;
1394 message.precision(3);
1395 message << gettext("Media...");
1397 if ( ( USE_CURL == 0) ||
1398 (!g_settings->getBool("enable_remote_media_server"))) {
1399 float cur = client.getCurRate();
1400 std::string cur_unit = gettext(" KB/s");
1404 cur_unit = gettext(" MB/s");
1406 message << " ( " << cur << cur_unit << " )";
1408 progress = 50+client.mediaReceiveProgress()*50+0.5;
1409 draw_load_screen(narrow_to_wide(message.str().c_str()), device,
1410 guienv, font, dtime, progress);
1413 // On some computers framerate doesn't seem to be
1414 // automatically limited
1415 if (cloud_menu_background) {
1416 // Time of frame without fps limit
1419 // not using getRealTime is necessary for wine
1420 u32 time = device->getTimer()->getTime();
1422 busytime_u32 = time - lasttime;
1425 busytime = busytime_u32 / 1000.0;
1428 u32 frametime_min = 1000./fps_max;
1430 if(busytime_u32 < frametime_min) {
1431 u32 sleeptime = frametime_min - busytime_u32;
1432 device->sleep(sleeptime);
1437 time_counter += dtime;
1442 if(error_message == L"" && !content_aborted){
1443 error_message = L"Something failed";
1444 errorstream<<wide_to_narrow(error_message)<<std::endl;
1446 // Break out of client scope
1451 After all content has been received:
1452 Update cached textures, meshes and materials
1454 client.afterContentReceived(device,font);
1457 Create the camera node
1459 Camera camera(smgr, draw_control, gamedef);
1460 if (!camera.successfullyCreated(error_message))
1463 f32 camera_yaw = 0; // "right/left"
1464 f32 camera_pitch = 0; // "up/down"
1470 Clouds *clouds = NULL;
1471 if(g_settings->getBool("enable_clouds"))
1473 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1481 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1483 scene::ISceneNode* skybox = NULL;
1486 A copy of the local inventory
1488 Inventory local_inventory(itemdef);
1491 Find out size of crack animation
1493 int crack_animation_length = 5;
1495 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1496 v2u32 size = t->getOriginalSize();
1497 crack_animation_length = size.Y / size.X;
1504 // First line of debug text
1505 gui::IGUIStaticText *guitext = guienv->addStaticText(
1507 core::rect<s32>(0, 0, 0, 0),
1509 // Second line of debug text
1510 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1512 core::rect<s32>(0, 0, 0, 0),
1514 // At the middle of the screen
1515 // Object infos are shown in this
1516 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1518 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1521 // Status text (displays info when showing and hiding GUI stuff, etc.)
1522 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1524 core::rect<s32>(0,0,0,0),
1526 guitext_status->setVisible(false);
1528 std::wstring statustext;
1529 float statustext_time = 0;
1532 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1534 core::rect<s32>(0,0,0,0),
1535 //false, false); // Disable word wrap as of now
1537 // Remove stale "recent" chat messages from previous connections
1538 chat_backend.clearRecentChat();
1539 // Chat backend and console
1540 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1542 // Profiler text (size is updated when text is updated)
1543 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1545 core::rect<s32>(0,0,0,0),
1547 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1548 guitext_profiler->setVisible(false);
1549 guitext_profiler->setWordWrap(true);
1552 Some statistics are collected in these
1555 u32 beginscenetime = 0;
1556 u32 endscenetime = 0;
1558 float recent_turn_speed = 0.0;
1560 ProfilerGraph graph;
1561 // Initially clear the profiler
1562 Profiler::GraphValues dummyvalues;
1563 g_profiler->graphGet(dummyvalues);
1565 float nodig_delay_timer = 0.0;
1566 float dig_time = 0.0;
1568 PointedThing pointed_old;
1569 bool digging = false;
1570 bool ldown_for_dig = false;
1572 float damage_flash = 0;
1574 float jump_timer = 0;
1575 bool reset_jump_timer = false;
1577 const float object_hit_delay = 0.2;
1578 float object_hit_delay_timer = 0.0;
1579 float time_from_last_punch = 10;
1581 float update_draw_list_timer = 0.0;
1582 v3f update_draw_list_last_cam_dir;
1584 bool invert_mouse = g_settings->getBool("invert_mouse");
1586 bool update_wielded_item_trigger = true;
1588 bool show_hud = true;
1589 bool show_chat = true;
1590 bool force_fog_off = false;
1591 f32 fog_range = 100*BS;
1592 bool disable_camera_update = false;
1593 bool show_debug = g_settings->getBool("show_debug");
1594 bool show_profiler_graph = false;
1595 u32 show_profiler = 0;
1596 u32 show_profiler_max = 3; // Number of pages
1598 float time_of_day = 0;
1599 float time_of_day_smooth = 0;
1601 float repeat_rightclick_timer = 0;
1606 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1607 sky, &force_fog_off, &fog_range, &client));
1613 bool first_loop_after_window_activation = true;
1615 // TODO: Convert the static interval timers to these
1616 // Interval limiter for profiler
1617 IntervalLimiter m_profiler_interval;
1619 // Time is in milliseconds
1620 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1621 // NOTE: So we have to use getTime() and call run()s between them
1622 u32 lasttime = device->getTimer()->getTime();
1624 LocalPlayer* player = client.getEnv().getLocalPlayer();
1625 player->hurt_tilt_timer = 0;
1626 player->hurt_tilt_strength = 0;
1631 Hud hud(driver, smgr, guienv, font, text_height,
1632 gamedef, player, &local_inventory);
1634 core::stringw str = L"Minetest [";
1635 str += driver->getName();
1637 device->setWindowCaption(str.c_str());
1640 std::wstring infotext;
1644 if(device->run() == false || kill == true)
1647 v2u32 screensize = driver->getScreenSize();
1649 // Time of frame without fps limit
1653 // not using getRealTime is necessary for wine
1654 u32 time = device->getTimer()->getTime();
1656 busytime_u32 = time - lasttime;
1659 busytime = busytime_u32 / 1000.0;
1662 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1664 // Necessary for device->getTimer()->getTime()
1672 float fps_max = g_menumgr.pausesGame() ?
1673 g_settings->getFloat("pause_fps_max") :
1674 g_settings->getFloat("fps_max");
1675 u32 frametime_min = 1000./fps_max;
1677 if(busytime_u32 < frametime_min)
1679 u32 sleeptime = frametime_min - busytime_u32;
1680 device->sleep(sleeptime);
1681 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1685 // Necessary for device->getTimer()->getTime()
1689 Time difference calculation
1691 f32 dtime; // in seconds
1693 u32 time = device->getTimer()->getTime();
1695 dtime = (time - lasttime) / 1000.0;
1700 g_profiler->graphAdd("mainloop_dtime", dtime);
1704 if(nodig_delay_timer >= 0)
1705 nodig_delay_timer -= dtime;
1706 if(object_hit_delay_timer >= 0)
1707 object_hit_delay_timer -= dtime;
1708 time_from_last_punch += dtime;
1710 g_profiler->add("Elapsed time", dtime);
1711 g_profiler->avg("FPS", 1./dtime);
1714 Time average and jitter calculation
1717 static f32 dtime_avg1 = 0.0;
1718 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1719 f32 dtime_jitter1 = dtime - dtime_avg1;
1721 static f32 dtime_jitter1_max_sample = 0.0;
1722 static f32 dtime_jitter1_max_fraction = 0.0;
1724 static f32 jitter1_max = 0.0;
1725 static f32 counter = 0.0;
1726 if(dtime_jitter1 > jitter1_max)
1727 jitter1_max = dtime_jitter1;
1732 dtime_jitter1_max_sample = jitter1_max;
1733 dtime_jitter1_max_fraction
1734 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1740 Busytime average and jitter calculation
1743 static f32 busytime_avg1 = 0.0;
1744 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1745 f32 busytime_jitter1 = busytime - busytime_avg1;
1747 static f32 busytime_jitter1_max_sample = 0.0;
1748 static f32 busytime_jitter1_min_sample = 0.0;
1750 static f32 jitter1_max = 0.0;
1751 static f32 jitter1_min = 0.0;
1752 static f32 counter = 0.0;
1753 if(busytime_jitter1 > jitter1_max)
1754 jitter1_max = busytime_jitter1;
1755 if(busytime_jitter1 < jitter1_min)
1756 jitter1_min = busytime_jitter1;
1760 busytime_jitter1_max_sample = jitter1_max;
1761 busytime_jitter1_min_sample = jitter1_min;
1768 Handle miscellaneous stuff
1771 if(client.accessDenied())
1773 error_message = L"Access denied. Reason: "
1774 +client.accessDeniedReason();
1775 errorstream<<wide_to_narrow(error_message)<<std::endl;
1779 if(g_gamecallback->disconnect_requested)
1781 g_gamecallback->disconnect_requested = false;
1785 if(g_gamecallback->changepassword_requested)
1787 (new GUIPasswordChange(guienv, guiroot, -1,
1788 &g_menumgr, &client))->drop();
1789 g_gamecallback->changepassword_requested = false;
1792 if(g_gamecallback->changevolume_requested)
1794 (new GUIVolumeChange(guienv, guiroot, -1,
1795 &g_menumgr, &client))->drop();
1796 g_gamecallback->changevolume_requested = false;
1799 /* Process TextureSource's queue */
1800 tsrc->processQueue();
1802 /* Process ItemDefManager's queue */
1803 itemdef->processQueue(gamedef);
1806 Process ShaderSource's queue
1808 shsrc->processQueue();
1815 // Hilight boxes collected during the loop and displayed
1816 std::vector<aabb3f> hilightboxes;
1818 /* reset infotext */
1823 float profiler_print_interval =
1824 g_settings->getFloat("profiler_print_interval");
1825 bool print_to_log = true;
1826 if(profiler_print_interval == 0){
1827 print_to_log = false;
1828 profiler_print_interval = 5;
1830 if(m_profiler_interval.step(dtime, profiler_print_interval))
1833 infostream<<"Profiler:"<<std::endl;
1834 g_profiler->print(infostream);
1837 update_profiler_gui(guitext_profiler, font, text_height,
1838 show_profiler, show_profiler_max);
1840 g_profiler->clear();
1844 Direct handling of user input
1847 // Reset input if window not active or some menu is active
1848 if(device->isWindowActive() == false
1849 || noMenuActive() == false
1850 || guienv->hasFocus(gui_chat_console))
1854 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1856 gui_chat_console->closeConsoleAtOnce();
1859 // Input handler step() (used by the random input generator)
1862 // Increase timer for doubleclick of "jump"
1863 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1864 jump_timer += dtime;
1867 Launch menus and trigger stuff according to keys
1869 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1871 // drop selected item
1872 IDropAction *a = new IDropAction();
1874 a->from_inv.setCurrentPlayer();
1875 a->from_list = "main";
1876 a->from_i = client.getPlayerItem();
1877 client.inventoryAction(a);
1879 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1881 infostream<<"the_game: "
1882 <<"Launching inventory"<<std::endl;
1884 PlayerInventoryFormSource* fs_src = new PlayerInventoryFormSource(&client);
1885 TextDest* txt_dst = new TextDestPlayerInventory(&client);
1887 create_formspec_menu(¤t_formspec, &client, gamedef, tsrc, device, fs_src, txt_dst);
1889 InventoryLocation inventoryloc;
1890 inventoryloc.setCurrentPlayer();
1891 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
1893 else if(input->wasKeyDown(EscapeKey))
1895 show_pause_menu(¤t_formspec, &client, gamedef, tsrc, device,
1896 simple_singleplayer_mode);
1898 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1900 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
1903 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1905 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
1908 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1910 if (!gui_chat_console->isOpenInhibited())
1912 // Open up to over half of the screen
1913 gui_chat_console->openConsole(0.6);
1914 guienv->setFocus(gui_chat_console);
1917 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1919 if(g_settings->getBool("free_move"))
1921 g_settings->set("free_move","false");
1922 statustext = L"free_move disabled";
1923 statustext_time = 0;
1927 g_settings->set("free_move","true");
1928 statustext = L"free_move enabled";
1929 statustext_time = 0;
1930 if(!client.checkPrivilege("fly"))
1931 statustext += L" (note: no 'fly' privilege)";
1934 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
1936 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
1938 if(g_settings->getBool("free_move"))
1940 g_settings->set("free_move","false");
1941 statustext = L"free_move disabled";
1942 statustext_time = 0;
1946 g_settings->set("free_move","true");
1947 statustext = L"free_move enabled";
1948 statustext_time = 0;
1949 if(!client.checkPrivilege("fly"))
1950 statustext += L" (note: no 'fly' privilege)";
1953 reset_jump_timer = true;
1955 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1957 if(g_settings->getBool("fast_move"))
1959 g_settings->set("fast_move","false");
1960 statustext = L"fast_move disabled";
1961 statustext_time = 0;
1965 g_settings->set("fast_move","true");
1966 statustext = L"fast_move enabled";
1967 statustext_time = 0;
1968 if(!client.checkPrivilege("fast"))
1969 statustext += L" (note: no 'fast' privilege)";
1972 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
1974 if(g_settings->getBool("noclip"))
1976 g_settings->set("noclip","false");
1977 statustext = L"noclip disabled";
1978 statustext_time = 0;
1982 g_settings->set("noclip","true");
1983 statustext = L"noclip enabled";
1984 statustext_time = 0;
1985 if(!client.checkPrivilege("noclip"))
1986 statustext += L" (note: no 'noclip' privilege)";
1989 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1991 irr::video::IImage* const image = driver->createScreenShot();
1993 irr::c8 filename[256];
1994 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1995 g_settings->get("screenshot_path").c_str(),
1996 device->getTimer()->getRealTime());
1997 if (driver->writeImageToFile(image, filename)) {
1998 std::wstringstream sstr;
1999 sstr<<"Saved screenshot to '"<<filename<<"'";
2000 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
2001 statustext = sstr.str();
2002 statustext_time = 0;
2004 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
2009 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2011 show_hud = !show_hud;
2013 statustext = L"HUD shown";
2015 statustext = L"HUD hidden";
2016 statustext_time = 0;
2018 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2020 show_chat = !show_chat;
2022 statustext = L"Chat shown";
2024 statustext = L"Chat hidden";
2025 statustext_time = 0;
2027 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2029 force_fog_off = !force_fog_off;
2031 statustext = L"Fog disabled";
2033 statustext = L"Fog enabled";
2034 statustext_time = 0;
2036 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2038 disable_camera_update = !disable_camera_update;
2039 if(disable_camera_update)
2040 statustext = L"Camera update disabled";
2042 statustext = L"Camera update enabled";
2043 statustext_time = 0;
2045 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2047 // Initial / 3x toggle: Chat only
2048 // 1x toggle: Debug text with chat
2049 // 2x toggle: Debug text with profiler graph
2053 show_profiler_graph = false;
2054 statustext = L"Debug info shown";
2055 statustext_time = 0;
2057 else if(show_profiler_graph)
2060 show_profiler_graph = false;
2061 statustext = L"Debug info and profiler graph hidden";
2062 statustext_time = 0;
2066 show_profiler_graph = true;
2067 statustext = L"Profiler graph shown";
2068 statustext_time = 0;
2071 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2073 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2075 // FIXME: This updates the profiler with incomplete values
2076 update_profiler_gui(guitext_profiler, font, text_height,
2077 show_profiler, show_profiler_max);
2079 if(show_profiler != 0)
2081 std::wstringstream sstr;
2082 sstr<<"Profiler shown (page "<<show_profiler
2083 <<" of "<<show_profiler_max<<")";
2084 statustext = sstr.str();
2085 statustext_time = 0;
2089 statustext = L"Profiler hidden";
2090 statustext_time = 0;
2093 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2095 s16 range = g_settings->getS16("viewing_range_nodes_min");
2096 s16 range_new = range + 10;
2097 g_settings->set("viewing_range_nodes_min", itos(range_new));
2098 statustext = narrow_to_wide(
2099 "Minimum viewing range changed to "
2101 statustext_time = 0;
2103 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2105 s16 range = g_settings->getS16("viewing_range_nodes_min");
2106 s16 range_new = range - 10;
2109 g_settings->set("viewing_range_nodes_min",
2111 statustext = narrow_to_wide(
2112 "Minimum viewing range changed to "
2114 statustext_time = 0;
2118 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2120 reset_jump_timer = false;
2124 // Handle QuicktuneShortcutter
2125 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2127 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2129 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2131 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2134 std::string msg = quicktune.getMessage();
2136 statustext = narrow_to_wide(msg);
2137 statustext_time = 0;
2141 // Item selection with mouse wheel
2142 u16 new_playeritem = client.getPlayerItem();
2144 s32 wheel = input->getMouseWheel();
2145 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2146 player->hud_hotbar_itemcount-1);
2150 if(new_playeritem < max_item)
2157 if(new_playeritem > 0)
2160 new_playeritem = max_item;
2165 for(u16 i=0; i<10; i++)
2167 const KeyPress *kp = NumberKey + (i + 1) % 10;
2168 if(input->wasKeyDown(*kp))
2170 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2174 infostream<<"Selected item: "
2175 <<new_playeritem<<std::endl;
2180 // Viewing range selection
2181 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2183 draw_control.range_all = !draw_control.range_all;
2184 if(draw_control.range_all)
2186 infostream<<"Enabled full viewing range"<<std::endl;
2187 statustext = L"Enabled full viewing range";
2188 statustext_time = 0;
2192 infostream<<"Disabled full viewing range"<<std::endl;
2193 statustext = L"Disabled full viewing range";
2194 statustext_time = 0;
2198 // Print debug stacks
2199 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2201 dstream<<"-----------------------------------------"
2203 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2204 dstream<<"-----------------------------------------"
2206 debug_stacks_print();
2210 Mouse and camera control
2211 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2214 float turn_amount = 0;
2215 if((device->isWindowActive() && noMenuActive()) || random_input)
2219 // Mac OSX gets upset if this is set every frame
2220 if(device->getCursorControl()->isVisible())
2221 device->getCursorControl()->setVisible(false);
2224 if(first_loop_after_window_activation){
2225 //infostream<<"window active, first loop"<<std::endl;
2226 first_loop_after_window_activation = false;
2229 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width/2);
2230 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height/2);
2231 if(invert_mouse || camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT) {
2234 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2236 /*const float keyspeed = 500;
2237 if(input->isKeyDown(irr::KEY_UP))
2238 dy -= dtime * keyspeed;
2239 if(input->isKeyDown(irr::KEY_DOWN))
2240 dy += dtime * keyspeed;
2241 if(input->isKeyDown(irr::KEY_LEFT))
2242 dx -= dtime * keyspeed;
2243 if(input->isKeyDown(irr::KEY_RIGHT))
2244 dx += dtime * keyspeed;*/
2246 float d = g_settings->getFloat("mouse_sensitivity");
2247 d = rangelim(d, 0.01, 100.0);
2249 camera_pitch += dy*d;
2250 if(camera_pitch < -89.5) camera_pitch = -89.5;
2251 if(camera_pitch > 89.5) camera_pitch = 89.5;
2253 turn_amount = v2f(dx, dy).getLength() * d;
2255 input->setMousePos((driver->getScreenSize().Width/2),
2256 (driver->getScreenSize().Height/2));
2259 // Mac OSX gets upset if this is set every frame
2260 if(device->getCursorControl()->isVisible() == false)
2261 device->getCursorControl()->setVisible(true);
2263 //infostream<<"window inactive"<<std::endl;
2264 first_loop_after_window_activation = true;
2266 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2267 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2270 Player speed control
2284 PlayerControl control(
2285 input->isKeyDown(getKeySetting("keymap_forward")),
2286 input->isKeyDown(getKeySetting("keymap_backward")),
2287 input->isKeyDown(getKeySetting("keymap_left")),
2288 input->isKeyDown(getKeySetting("keymap_right")),
2289 input->isKeyDown(getKeySetting("keymap_jump")),
2290 input->isKeyDown(getKeySetting("keymap_special1")),
2291 input->isKeyDown(getKeySetting("keymap_sneak")),
2292 input->getLeftState(),
2293 input->getRightState(),
2297 client.setPlayerControl(control);
2298 LocalPlayer* player = client.getEnv().getLocalPlayer();
2300 (((int)input->isKeyDown(getKeySetting("keymap_forward")) & 0x1) << 0) |
2301 (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2302 (((int)input->isKeyDown(getKeySetting("keymap_left")) & 0x1) << 2) |
2303 (((int)input->isKeyDown(getKeySetting("keymap_right")) & 0x1) << 3) |
2304 (((int)input->isKeyDown(getKeySetting("keymap_jump")) & 0x1) << 4) |
2305 (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2306 (((int)input->isKeyDown(getKeySetting("keymap_sneak")) & 0x1) << 6) |
2307 (((int)input->getLeftState() & 0x1) << 7) |
2308 (((int)input->getRightState() & 0x1) << 8);
2312 Run server, client (and process environments)
2314 bool can_be_and_is_paused =
2315 (simple_singleplayer_mode && g_menumgr.pausesGame());
2316 if(can_be_and_is_paused)
2325 //TimeTaker timer("server->step(dtime)");
2326 server->step(dtime);
2329 //TimeTaker timer("client.step(dtime)");
2335 // Read client events
2338 ClientEvent event = client.getClientEvent();
2339 if(event.type == CE_NONE)
2343 else if(event.type == CE_PLAYER_DAMAGE &&
2344 client.getHP() != 0)
2346 //u16 damage = event.player_damage.amount;
2347 //infostream<<"Player damage: "<<damage<<std::endl;
2349 damage_flash += 100.0;
2350 damage_flash += 8.0 * event.player_damage.amount;
2352 player->hurt_tilt_timer = 1.5;
2353 player->hurt_tilt_strength = event.player_damage.amount/2;
2354 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 2.0, 10.0);
2356 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2357 gamedef->event()->put(e);
2359 else if(event.type == CE_PLAYER_FORCE_MOVE)
2361 camera_yaw = event.player_force_move.yaw;
2362 camera_pitch = event.player_force_move.pitch;
2364 else if(event.type == CE_DEATHSCREEN)
2366 show_deathscreen(¤t_formspec, &client, gamedef, tsrc,
2369 chat_backend.addMessage(L"", L"You died.");
2371 /* Handle visualization */
2374 LocalPlayer* player = client.getEnv().getLocalPlayer();
2375 player->hurt_tilt_timer = 0;
2376 player->hurt_tilt_strength = 0;
2379 else if (event.type == CE_SHOW_FORMSPEC)
2381 FormspecFormSource* fs_src =
2382 new FormspecFormSource(*(event.show_formspec.formspec));
2383 TextDestPlayerInventory* txt_dst =
2384 new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2386 create_formspec_menu(¤t_formspec, &client, gamedef,
2387 tsrc, device, fs_src, txt_dst);
2389 delete(event.show_formspec.formspec);
2390 delete(event.show_formspec.formname);
2392 else if(event.type == CE_SPAWN_PARTICLE)
2394 LocalPlayer* player = client.getEnv().getLocalPlayer();
2395 video::ITexture *texture =
2396 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2398 new Particle(gamedef, smgr, player, client.getEnv(),
2399 *event.spawn_particle.pos,
2400 *event.spawn_particle.vel,
2401 *event.spawn_particle.acc,
2402 event.spawn_particle.expirationtime,
2403 event.spawn_particle.size,
2404 event.spawn_particle.collisiondetection,
2405 event.spawn_particle.vertical,
2410 else if(event.type == CE_ADD_PARTICLESPAWNER)
2412 LocalPlayer* player = client.getEnv().getLocalPlayer();
2413 video::ITexture *texture =
2414 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2416 new ParticleSpawner(gamedef, smgr, player,
2417 event.add_particlespawner.amount,
2418 event.add_particlespawner.spawntime,
2419 *event.add_particlespawner.minpos,
2420 *event.add_particlespawner.maxpos,
2421 *event.add_particlespawner.minvel,
2422 *event.add_particlespawner.maxvel,
2423 *event.add_particlespawner.minacc,
2424 *event.add_particlespawner.maxacc,
2425 event.add_particlespawner.minexptime,
2426 event.add_particlespawner.maxexptime,
2427 event.add_particlespawner.minsize,
2428 event.add_particlespawner.maxsize,
2429 event.add_particlespawner.collisiondetection,
2430 event.add_particlespawner.vertical,
2432 event.add_particlespawner.id);
2434 else if(event.type == CE_DELETE_PARTICLESPAWNER)
2436 delete_particlespawner (event.delete_particlespawner.id);
2438 else if (event.type == CE_HUDADD)
2440 u32 id = event.hudadd.id;
2441 size_t nhudelem = player->hud.size();
2442 if (id > nhudelem || (id < nhudelem && player->hud[id])) {
2443 delete event.hudadd.pos;
2444 delete event.hudadd.name;
2445 delete event.hudadd.scale;
2446 delete event.hudadd.text;
2447 delete event.hudadd.align;
2448 delete event.hudadd.offset;
2449 delete event.hudadd.world_pos;
2450 delete event.hudadd.size;
2454 HudElement *e = new HudElement;
2455 e->type = (HudElementType)event.hudadd.type;
2456 e->pos = *event.hudadd.pos;
2457 e->name = *event.hudadd.name;
2458 e->scale = *event.hudadd.scale;
2459 e->text = *event.hudadd.text;
2460 e->number = event.hudadd.number;
2461 e->item = event.hudadd.item;
2462 e->dir = event.hudadd.dir;
2463 e->align = *event.hudadd.align;
2464 e->offset = *event.hudadd.offset;
2465 e->world_pos = *event.hudadd.world_pos;
2466 e->size = *event.hudadd.size;
2469 player->hud.push_back(e);
2471 player->hud[id] = e;
2473 delete event.hudadd.pos;
2474 delete event.hudadd.name;
2475 delete event.hudadd.scale;
2476 delete event.hudadd.text;
2477 delete event.hudadd.align;
2478 delete event.hudadd.offset;
2479 delete event.hudadd.world_pos;
2480 delete event.hudadd.size;
2482 else if (event.type == CE_HUDRM)
2484 u32 id = event.hudrm.id;
2485 if (id < player->hud.size() && player->hud[id]) {
2486 delete player->hud[id];
2487 player->hud[id] = NULL;
2490 else if (event.type == CE_HUDCHANGE)
2492 u32 id = event.hudchange.id;
2493 if (id >= player->hud.size() || !player->hud[id]) {
2494 delete event.hudchange.v3fdata;
2495 delete event.hudchange.v2fdata;
2496 delete event.hudchange.sdata;
2497 delete event.hudchange.v2s32data;
2501 HudElement* e = player->hud[id];
2502 switch (event.hudchange.stat) {
2504 e->pos = *event.hudchange.v2fdata;
2507 e->name = *event.hudchange.sdata;
2509 case HUD_STAT_SCALE:
2510 e->scale = *event.hudchange.v2fdata;
2513 e->text = *event.hudchange.sdata;
2515 case HUD_STAT_NUMBER:
2516 e->number = event.hudchange.data;
2519 e->item = event.hudchange.data;
2522 e->dir = event.hudchange.data;
2524 case HUD_STAT_ALIGN:
2525 e->align = *event.hudchange.v2fdata;
2527 case HUD_STAT_OFFSET:
2528 e->offset = *event.hudchange.v2fdata;
2530 case HUD_STAT_WORLD_POS:
2531 e->world_pos = *event.hudchange.v3fdata;
2534 e->size = *event.hudchange.v2s32data;
2538 delete event.hudchange.v3fdata;
2539 delete event.hudchange.v2fdata;
2540 delete event.hudchange.sdata;
2541 delete event.hudchange.v2s32data;
2543 else if (event.type == CE_SET_SKY)
2545 sky->setVisible(false);
2550 // Handle according to type
2551 if(*event.set_sky.type == "regular"){
2552 sky->setVisible(true);
2554 else if(*event.set_sky.type == "skybox" &&
2555 event.set_sky.params->size() == 6){
2556 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2557 skybox = smgr->addSkyBoxSceneNode(
2558 tsrc->getTexture((*event.set_sky.params)[0]),
2559 tsrc->getTexture((*event.set_sky.params)[1]),
2560 tsrc->getTexture((*event.set_sky.params)[2]),
2561 tsrc->getTexture((*event.set_sky.params)[3]),
2562 tsrc->getTexture((*event.set_sky.params)[4]),
2563 tsrc->getTexture((*event.set_sky.params)[5]));
2565 // Handle everything else as plain color
2567 if(*event.set_sky.type != "plain")
2568 infostream<<"Unknown sky type: "
2569 <<(*event.set_sky.type)<<std::endl;
2570 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2573 delete event.set_sky.bgcolor;
2574 delete event.set_sky.type;
2575 delete event.set_sky.params;
2577 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO)
2579 bool enable = event.override_day_night_ratio.do_override;
2580 u32 value = event.override_day_night_ratio.ratio_f * 1000;
2581 client.getEnv().setDayNightRatioOverride(enable, value);
2586 //TimeTaker //timer2("//timer2");
2589 For interaction purposes, get info about the held item
2591 - Is it a usable item?
2592 - Can it point to liquids?
2594 ItemStack playeritem;
2596 InventoryList *mlist = local_inventory.getList("main");
2599 playeritem = mlist->getItem(client.getPlayerItem());
2602 const ItemDefinition &playeritem_def =
2603 playeritem.getDefinition(itemdef);
2604 ToolCapabilities playeritem_toolcap =
2605 playeritem.getToolCapabilities(itemdef);
2611 v3s16 old_camera_offset = camera.getOffset();
2613 LocalPlayer* player = client.getEnv().getLocalPlayer();
2614 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2615 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2617 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2618 camera.toggleCameraMode();
2619 GenericCAO* playercao = player->getCAO();
2621 assert( playercao != NULL );
2622 if (camera.getCameraMode() > CAMERA_MODE_FIRST) {
2623 playercao->setVisible(true);
2626 playercao->setVisible(false);
2629 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2630 camera.update(player, dtime, busytime, tool_reload_ratio,
2634 v3f player_position = player->getPosition();
2635 v3f camera_position = camera.getPosition();
2636 v3f camera_direction = camera.getDirection();
2637 f32 camera_fov = camera.getFovMax();
2638 v3s16 camera_offset = camera.getOffset();
2640 bool camera_offset_changed = (camera_offset != old_camera_offset);
2642 if(!disable_camera_update){
2643 client.getEnv().getClientMap().updateCamera(camera_position,
2644 camera_direction, camera_fov, camera_offset);
2645 if (camera_offset_changed){
2646 client.updateCameraOffset(camera_offset);
2647 client.getEnv().updateCameraOffset(camera_offset);
2649 clouds->updateCameraOffset(camera_offset);
2653 // Update sound listener
2654 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2655 v3f(0,0,0), // velocity
2656 camera.getDirection(),
2657 camera.getCameraNode()->getUpVector());
2658 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2664 soundmaker.step(dtime);
2666 ClientMap &map = client.getEnv().getClientMap();
2667 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2668 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2672 Calculate what block is the crosshair pointing to
2675 //u32 t1 = device->getTimer()->getRealTime();
2677 f32 d = playeritem_def.range; // max. distance
2678 f32 d_hand = itemdef->get("").range;
2679 if(d < 0 && d_hand >= 0)
2683 core::line3d<f32> shootline(camera_position,
2684 camera_position + camera_direction * BS * (d+1));
2686 // prevent player pointing anything in front-view
2687 if (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)
2688 shootline = core::line3d<f32>(0,0,0,0,0,0);
2690 ClientActiveObject *selected_object = NULL;
2692 PointedThing pointed = getPointedThing(
2694 &client, player_position, camera_direction,
2695 camera_position, shootline, d,
2696 playeritem_def.liquids_pointable, !ldown_for_dig,
2702 if(pointed != pointed_old)
2704 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2705 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2710 - releasing left mouse button
2711 - pointing away from node
2715 if(input->getLeftReleased())
2717 infostream<<"Left button released"
2718 <<" (stopped digging)"<<std::endl;
2721 else if(pointed != pointed_old)
2723 if (pointed.type == POINTEDTHING_NODE
2724 && pointed_old.type == POINTEDTHING_NODE
2725 && pointed.node_undersurface == pointed_old.node_undersurface)
2727 // Still pointing to the same node,
2728 // but a different face. Don't reset.
2732 infostream<<"Pointing away from node"
2733 <<" (stopped digging)"<<std::endl;
2739 client.interact(1, pointed_old);
2740 client.setCrack(-1, v3s16(0,0,0));
2744 if(!digging && ldown_for_dig && !input->getLeftState())
2746 ldown_for_dig = false;
2749 bool left_punch = false;
2750 soundmaker.m_player_leftpunch_sound.name = "";
2752 if(input->getRightState())
2753 repeat_rightclick_timer += dtime;
2755 repeat_rightclick_timer = 0;
2757 if(playeritem_def.usable && input->getLeftState())
2759 if(input->getLeftClicked())
2760 client.interact(4, pointed);
2762 else if(pointed.type == POINTEDTHING_NODE)
2764 v3s16 nodepos = pointed.node_undersurface;
2765 v3s16 neighbourpos = pointed.node_abovesurface;
2768 Check information text of node
2771 ClientMap &map = client.getEnv().getClientMap();
2772 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2774 infotext = narrow_to_wide(meta->getString("infotext"));
2776 MapNode n = map.getNode(nodepos);
2777 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2778 infotext = L"Unknown node: ";
2779 infotext += narrow_to_wide(nodedef->get(n).name);
2787 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2788 && client.checkPrivilege("interact"))
2792 infostream<<"Started digging"<<std::endl;
2793 client.interact(0, pointed);
2795 ldown_for_dig = true;
2797 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2799 // NOTE: Similar piece of code exists on the server side for
2801 // Get digging parameters
2802 DigParams params = getDigParams(nodedef->get(n).groups,
2803 &playeritem_toolcap);
2804 // If can't dig, try hand
2805 if(!params.diggable){
2806 const ItemDefinition &hand = itemdef->get("");
2807 const ToolCapabilities *tp = hand.tool_capabilities;
2809 params = getDigParams(nodedef->get(n).groups, tp);
2812 float dig_time_complete = 0.0;
2814 if(params.diggable == false)
2816 // I guess nobody will wait for this long
2817 dig_time_complete = 10000000.0;
2821 dig_time_complete = params.time;
2822 if (g_settings->getBool("enable_particles"))
2824 const ContentFeatures &features =
2825 client.getNodeDefManager()->get(n);
2826 addPunchingParticles
2827 (gamedef, smgr, player, client.getEnv(),
2828 nodepos, features.tiles);
2832 if(dig_time_complete >= 0.001)
2834 dig_index = (u16)((float)crack_animation_length
2835 * dig_time/dig_time_complete);
2837 // This is for torches
2840 dig_index = crack_animation_length;
2843 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2844 if(sound_dig.exists() && params.diggable){
2845 if(sound_dig.name == "__group"){
2846 if(params.main_group != ""){
2847 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2848 soundmaker.m_player_leftpunch_sound.name =
2849 std::string("default_dig_") +
2853 soundmaker.m_player_leftpunch_sound = sound_dig;
2857 // Don't show cracks if not diggable
2858 if(dig_time_complete >= 100000.0)
2861 else if(dig_index < crack_animation_length)
2863 //TimeTaker timer("client.setTempMod");
2864 //infostream<<"dig_index="<<dig_index<<std::endl;
2865 client.setCrack(dig_index, nodepos);
2869 infostream<<"Digging completed"<<std::endl;
2870 client.interact(2, pointed);
2871 client.setCrack(-1, v3s16(0,0,0));
2872 MapNode wasnode = map.getNode(nodepos);
2873 client.removeNode(nodepos);
2875 if (g_settings->getBool("enable_particles"))
2877 const ContentFeatures &features =
2878 client.getNodeDefManager()->get(wasnode);
2880 (gamedef, smgr, player, client.getEnv(),
2881 nodepos, features.tiles);
2887 nodig_delay_timer = dig_time_complete
2888 / (float)crack_animation_length;
2890 // We don't want a corresponding delay to
2891 // very time consuming nodes
2892 if(nodig_delay_timer > 0.3)
2893 nodig_delay_timer = 0.3;
2894 // We want a slight delay to very little
2895 // time consuming nodes
2896 float mindelay = 0.15;
2897 if(nodig_delay_timer < mindelay)
2898 nodig_delay_timer = mindelay;
2900 // Send event to trigger sound
2901 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2902 gamedef->event()->put(e);
2905 if(dig_time_complete < 100000.0)
2909 client.setCrack(-1, nodepos);
2912 camera.setDigging(0); // left click animation
2915 if((input->getRightClicked() ||
2916 repeat_rightclick_timer >=
2917 g_settings->getFloat("repeat_rightclick_time")) &&
2918 client.checkPrivilege("interact"))
2920 repeat_rightclick_timer = 0;
2921 infostream<<"Ground right-clicked"<<std::endl;
2923 // Sign special case, at least until formspec is properly implemented.
2925 if(meta && meta->getString("formspec") == "hack:sign_text_input"
2927 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2929 infostream<<"Launching metadata text input"<<std::endl;
2931 // Get a new text for it
2933 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2935 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2937 (new GUITextInputMenu(guienv, guiroot, -1,
2941 // If metadata provides an inventory view, activate it
2942 else if(meta && meta->getString("formspec") != "" && !random_input
2943 && !input->isKeyDown(getKeySetting("keymap_sneak")))
2945 infostream<<"Launching custom inventory view"<<std::endl;
2947 InventoryLocation inventoryloc;
2948 inventoryloc.setNodeMeta(nodepos);
2950 NodeMetadataFormSource* fs_src = new NodeMetadataFormSource(
2951 &client.getEnv().getClientMap(), nodepos);
2952 TextDest* txt_dst = new TextDestNodeMetadata(nodepos, &client);
2954 create_formspec_menu(¤t_formspec, &client, gamedef,
2955 tsrc, device, fs_src, txt_dst);
2957 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
2959 // Otherwise report right click to server
2962 camera.setDigging(1); // right click animation (always shown for feedback)
2964 // If the wielded item has node placement prediction,
2966 bool placed = nodePlacementPrediction(client,
2968 nodepos, neighbourpos);
2972 client.interact(3, pointed);
2974 soundmaker.m_player_rightpunch_sound =
2975 playeritem_def.sound_place;
2977 soundmaker.m_player_rightpunch_sound =
2981 if (playeritem_def.node_placement_prediction == "" ||
2982 nodedef->get(map.getNode(nodepos)).rightclickable)
2983 client.interact(3, pointed); // Report to server
2987 else if(pointed.type == POINTEDTHING_OBJECT)
2989 infotext = narrow_to_wide(selected_object->infoText());
2991 if(infotext == L"" && show_debug){
2992 infotext = narrow_to_wide(selected_object->debugInfoText());
2995 //if(input->getLeftClicked())
2996 if(input->getLeftState())
2998 bool do_punch = false;
2999 bool do_punch_damage = false;
3000 if(object_hit_delay_timer <= 0.0){
3002 do_punch_damage = true;
3003 object_hit_delay_timer = object_hit_delay;
3005 if(input->getLeftClicked()){
3009 infostream<<"Left-clicked object"<<std::endl;
3012 if(do_punch_damage){
3013 // Report direct punch
3014 v3f objpos = selected_object->getPosition();
3015 v3f dir = (objpos - player_position).normalize();
3017 bool disable_send = selected_object->directReportPunch(
3018 dir, &playeritem, time_from_last_punch);
3019 time_from_last_punch = 0;
3021 client.interact(0, pointed);
3024 else if(input->getRightClicked())
3026 infostream<<"Right-clicked object"<<std::endl;
3027 client.interact(3, pointed); // place
3030 else if(input->getLeftState())
3032 // When button is held down in air, show continuous animation
3036 pointed_old = pointed;
3038 if(left_punch || input->getLeftClicked())
3040 camera.setDigging(0); // left click animation
3043 input->resetLeftClicked();
3044 input->resetRightClicked();
3046 input->resetLeftReleased();
3047 input->resetRightReleased();
3050 Calculate stuff for drawing
3057 if(draw_control.range_all)
3058 fog_range = 100000*BS;
3060 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3061 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3066 Calculate general brightness
3068 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3069 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3070 float direct_brightness = 0;
3071 bool sunlight_seen = false;
3072 if(g_settings->getBool("free_move")){
3073 direct_brightness = time_brightness;
3074 sunlight_seen = true;
3076 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3077 float old_brightness = sky->getBrightness();
3078 direct_brightness = (float)client.getEnv().getClientMap()
3079 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3080 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3084 time_of_day = client.getEnv().getTimeOfDayF();
3086 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3087 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3088 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3089 time_of_day_smooth = time_of_day;
3091 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3092 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3093 + (time_of_day+1.0) * todsm;
3095 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3096 + time_of_day * todsm;
3098 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3099 sunlight_seen,camera.getCameraMode(), player->getYaw(),
3100 player->getPitch());
3102 video::SColor bgcolor = sky->getBgColor();
3103 video::SColor skycolor = sky->getSkyColor();
3109 if(sky->getCloudsVisible()){
3110 clouds->setVisible(true);
3111 clouds->step(dtime);
3112 clouds->update(v2f(player_position.X, player_position.Z),
3113 sky->getCloudColor());
3115 clouds->setVisible(false);
3123 allparticles_step(dtime);
3124 allparticlespawners_step(dtime, client.getEnv());
3130 if(g_settings->getBool("enable_fog") && !force_fog_off)
3134 video::EFT_FOG_LINEAR,
3146 video::EFT_FOG_LINEAR,
3156 Update gui stuff (0ms)
3159 //TimeTaker guiupdatetimer("Gui updating");
3163 static float drawtime_avg = 0;
3164 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3165 /*static float beginscenetime_avg = 0;
3166 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3167 static float scenetime_avg = 0;
3168 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3169 static float endscenetime_avg = 0;
3170 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3172 u16 fps = (1.0/dtime_avg1);
3174 std::ostringstream os(std::ios_base::binary);
3176 <<"Minetest "<<minetest_version_hash
3178 <<" (R: range_all="<<draw_control.range_all<<")"
3179 <<std::setprecision(0)
3180 <<" drawtime = "<<drawtime_avg
3181 <<std::setprecision(1)
3182 <<", dtime_jitter = "
3183 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3184 <<std::setprecision(1)
3185 <<", v_range = "<<draw_control.wanted_range
3186 <<std::setprecision(3)
3187 <<", RTT = "<<client.getRTT();
3188 guitext->setText(narrow_to_wide(os.str()).c_str());
3189 guitext->setVisible(true);
3191 else if(show_hud || show_chat)
3193 std::ostringstream os(std::ios_base::binary);
3194 os<<"Minetest "<<minetest_version_hash;
3195 guitext->setText(narrow_to_wide(os.str()).c_str());
3196 guitext->setVisible(true);
3200 guitext->setVisible(false);
3203 if (guitext->isVisible())
3205 core::rect<s32> rect(
3211 guitext->setRelativePosition(rect);
3216 std::ostringstream os(std::ios_base::binary);
3217 os<<std::setprecision(1)<<std::fixed
3218 <<"(" <<(player_position.X/BS)
3219 <<", "<<(player_position.Y/BS)
3220 <<", "<<(player_position.Z/BS)
3221 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3222 <<") (seed = "<<((u64)client.getMapSeed())
3224 guitext2->setText(narrow_to_wide(os.str()).c_str());
3225 guitext2->setVisible(true);
3227 core::rect<s32> rect(
3231 5 + (text_height * 2)
3233 guitext2->setRelativePosition(rect);
3237 guitext2->setVisible(false);
3241 guitext_info->setText(infotext.c_str());
3242 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3246 float statustext_time_max = 1.5;
3247 if(!statustext.empty())
3249 statustext_time += dtime;
3250 if(statustext_time >= statustext_time_max)
3253 statustext_time = 0;
3256 guitext_status->setText(statustext.c_str());
3257 guitext_status->setVisible(!statustext.empty());
3259 if(!statustext.empty())
3261 s32 status_y = screensize.Y - 130;
3262 core::rect<s32> rect(
3264 status_y - guitext_status->getTextHeight(),
3268 guitext_status->setRelativePosition(rect);
3271 video::SColor initial_color(255,0,0,0);
3272 if(guienv->getSkin())
3273 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3274 video::SColor final_color = initial_color;
3275 final_color.setAlpha(0);
3276 video::SColor fade_color =
3277 initial_color.getInterpolated_quadratic(
3280 pow(statustext_time / (float)statustext_time_max, 2.0f));
3281 guitext_status->setOverrideColor(fade_color);
3282 guitext_status->enableOverrideColor(true);
3287 Get chat messages from client
3290 // Get new messages from error log buffer
3291 while(!chat_log_error_buf.empty())
3293 chat_backend.addMessage(L"", narrow_to_wide(
3294 chat_log_error_buf.get()));
3296 // Get new messages from client
3297 std::wstring message;
3298 while(client.getChatMessage(message))
3300 chat_backend.addUnparsedMessage(message);
3302 // Remove old messages
3303 chat_backend.step(dtime);
3305 // Display all messages in a static text element
3306 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
3307 std::wstring recent_chat = chat_backend.getRecentChat();
3308 guitext_chat->setText(recent_chat.c_str());
3310 // Update gui element size and position
3311 s32 chat_y = 5+(text_height+5);
3313 chat_y += (text_height+5);
3314 core::rect<s32> rect(
3318 chat_y + guitext_chat->getTextHeight()
3320 guitext_chat->setRelativePosition(rect);
3322 // Don't show chat if disabled or empty or profiler is enabled
3323 guitext_chat->setVisible(show_chat && recent_chat_count != 0
3331 if(client.getPlayerItem() != new_playeritem)
3333 client.selectPlayerItem(new_playeritem);
3335 if(client.getLocalInventoryUpdated())
3337 //infostream<<"Updating local inventory"<<std::endl;
3338 client.getLocalInventory(local_inventory);
3340 update_wielded_item_trigger = true;
3342 if(update_wielded_item_trigger)
3344 update_wielded_item_trigger = false;
3345 // Update wielded tool
3346 InventoryList *mlist = local_inventory.getList("main");
3349 item = mlist->getItem(client.getPlayerItem());
3350 camera.wield(item, client.getPlayerItem());
3354 Update block draw list every 200ms or when camera direction has
3357 update_draw_list_timer += dtime;
3358 if(update_draw_list_timer >= 0.2 ||
3359 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3360 camera_offset_changed){
3361 update_draw_list_timer = 0;
3362 client.getEnv().getClientMap().updateDrawList(driver);
3363 update_draw_list_last_cam_dir = camera_direction;
3369 TimeTaker tt_draw("mainloop: draw");
3371 TimeTaker timer("beginScene");
3372 driver->beginScene(true, true, skycolor);
3373 beginscenetime = timer.stop(true);
3377 draw_scene(driver, smgr, camera, client, player, hud, guienv,
3378 hilightboxes, screensize, skycolor, show_hud);
3384 client.getEnv().getClientMap().renderPostFx(camera.getCameraMode());
3390 if(show_profiler_graph)
3392 graph.draw(10, screensize.Y - 10, driver, font);
3398 if(damage_flash > 0.0)
3400 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3401 driver->draw2DRectangle(color,
3402 core::rect<s32>(0,0,screensize.X,screensize.Y),
3405 damage_flash -= 100.0*dtime;
3411 if(player->hurt_tilt_timer > 0.0)
3413 player->hurt_tilt_timer -= dtime*5;
3414 if(player->hurt_tilt_timer < 0)
3415 player->hurt_tilt_strength = 0;
3422 TimeTaker timer("endScene");
3424 endscenetime = timer.stop(true);
3427 drawtime = tt_draw.stop(true);
3428 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3435 Log times and stuff for visualization
3437 Profiler::GraphValues values;
3438 g_profiler->graphGet(values);
3447 if (gui_chat_console)
3448 gui_chat_console->drop();
3454 while (g_menumgr.menuCount() > 0)
3456 g_menumgr.m_stack.front()->setVisible(false);
3457 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
3460 Draw a "shutting down" screen, which will be shown while the map
3461 generator and other stuff quits
3464 wchar_t* text = wgettext("Shutting down stuff...");
3465 draw_load_screen(text, device, guienv, font, 0, -1, false);
3469 chat_backend.addMessage(L"", L"# Disconnected.");
3470 chat_backend.addMessage(L"", L"");
3474 //force answer all texture and shader jobs (TODO return empty values)
3476 while(!client.isShutdown()) {
3477 tsrc->processQueue();
3478 shsrc->processQueue();
3482 // Client scope (client is destructed before destructing *def and tsrc)
3485 catch(SerializationError &e)
3487 error_message = L"A serialization error occurred:\n"
3488 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3489 L" running a different version of Minetest.";
3490 errorstream<<wide_to_narrow(error_message)<<std::endl;
3492 catch(ServerError &e) {
3493 error_message = narrow_to_wide(e.what());
3494 errorstream << "ServerError: " << e.what() << std::endl;
3496 catch(ModError &e) {
3497 errorstream << "ModError: " << e.what() << std::endl;
3498 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3506 //has to be deleted first to stop all server threads
3514 //extended resource accounting
3515 infostream << "Irrlicht resources after cleanup:" << std::endl;
3516 infostream << "\tRemaining meshes : "
3517 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3518 infostream << "\tRemaining textures : "
3519 << driver->getTextureCount() << std::endl;
3520 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3521 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3522 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3525 clearTextureNameCache();
3526 infostream << "\tRemaining materials: "
3527 << driver-> getMaterialRendererCount ()
3528 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;