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"
35 #include "guiChatConsole.h"
39 #include "particles.h"
44 #include "mainmenumanager.h"
48 // Needed for determining pointing to nodes
50 #include "nodemetadata.h"
51 #include "main.h" // For g_settings
53 #include "tile.h" // For TextureSource
54 #include "shader.h" // For ShaderSource
55 #include "logoutputbuffer.h"
57 #include "quicktune_shortcutter.h"
58 #include "clientmap.h"
63 #include "sound_openal.h"
65 #include "event_manager.h"
68 #include "util/directiontables.h"
69 #include "util/pointedthing.h"
70 #include "drawscene.h"
71 #include "content_cao.h"
73 #ifdef HAVE_TOUCHSCREENGUI
74 #include "touchscreengui.h"
81 struct TextDestNodeMetadata : public TextDest
83 TextDestNodeMetadata(v3s16 p, Client *client)
88 // This is deprecated I guess? -celeron55
89 void gotText(std::wstring text)
91 std::string ntext = wide_to_narrow(text);
92 infostream<<"Submitting 'text' field of node at ("<<m_p.X<<","
93 <<m_p.Y<<","<<m_p.Z<<"): "<<ntext<<std::endl;
94 std::map<std::string, std::string> fields;
95 fields["text"] = ntext;
96 m_client->sendNodemetaFields(m_p, "", fields);
98 void gotText(std::map<std::string, std::string> fields)
100 m_client->sendNodemetaFields(m_p, "", fields);
107 struct TextDestPlayerInventory : public TextDest
109 TextDestPlayerInventory(Client *client)
114 TextDestPlayerInventory(Client *client, std::string formname)
117 m_formname = formname;
119 void gotText(std::map<std::string, std::string> fields)
121 m_client->sendInventoryFields(m_formname, fields);
127 struct LocalFormspecHandler : public TextDest
129 LocalFormspecHandler();
130 LocalFormspecHandler(std::string formname) :
133 m_formname = formname;
136 LocalFormspecHandler(std::string formname, Client *client) :
139 m_formname = formname;
142 void gotText(std::wstring message) {
143 errorstream << "LocalFormspecHandler::gotText old style message received" << std::endl;
146 void gotText(std::map<std::string, std::string> fields)
148 if (m_formname == "MT_PAUSE_MENU") {
149 if (fields.find("btn_sound") != fields.end()) {
150 g_gamecallback->changeVolume();
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()) {
177 if (m_formname == "MT_CHAT_MENU") {
178 assert(m_client != 0);
179 if ((fields.find("btn_send") != fields.end()) ||
180 (fields.find("quit") != fields.end())) {
181 if (fields.find("f_text") != fields.end()) {
182 m_client->typeChatMessage(narrow_to_wide(fields["f_text"]));
188 if (m_formname == "MT_DEATH_SCREEN") {
189 assert(m_client != 0);
190 if ((fields.find("btn_respawn") != fields.end())) {
191 m_client->sendRespawn();
195 if (fields.find("quit") != fields.end()) {
196 m_client->sendRespawn();
201 // don't show error message for unhandled cursor keys
202 if ( (fields.find("key_up") != fields.end()) ||
203 (fields.find("key_down") != fields.end()) ||
204 (fields.find("key_left") != fields.end()) ||
205 (fields.find("key_right") != fields.end())) {
209 errorstream << "LocalFormspecHandler::gotText unhandled >" << m_formname << "< event" << std::endl;
211 for (std::map<std::string,std::string>::iterator iter = fields.begin();
212 iter != fields.end(); iter++) {
213 errorstream << "\t"<< i << ": " << iter->first << "=" << iter->second << std::endl;
221 /* Form update callback */
223 class NodeMetadataFormSource: public IFormSource
226 NodeMetadataFormSource(ClientMap *map, v3s16 p):
231 std::string getForm()
233 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
236 return meta->getString("formspec");
238 std::string resolveText(std::string str)
240 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
243 return meta->resolveString(str);
250 class PlayerInventoryFormSource: public IFormSource
253 PlayerInventoryFormSource(Client *client):
257 std::string getForm()
259 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
260 return player->inventory_formspec;
267 Check if a node is pointable
269 inline bool isPointableNode(const MapNode& n,
270 Client *client, bool liquids_pointable)
272 const ContentFeatures &features = client->getNodeDefManager()->get(n);
273 return features.pointable ||
274 (liquids_pointable && features.isLiquid());
278 Find what the player is pointing at
280 PointedThing getPointedThing(Client *client, v3f player_position,
281 v3f camera_direction, v3f camera_position, core::line3d<f32> shootline,
282 f32 d, bool liquids_pointable, bool look_for_object, v3s16 camera_offset,
283 std::vector<aabb3f> &hilightboxes, ClientActiveObject *&selected_object)
287 hilightboxes.clear();
288 selected_object = NULL;
290 INodeDefManager *nodedef = client->getNodeDefManager();
291 ClientMap &map = client->getEnv().getClientMap();
293 f32 mindistance = BS * 1001;
295 // First try to find a pointed at active object
298 selected_object = client->getSelectedActiveObject(d*BS,
299 camera_position, shootline);
301 if(selected_object != NULL)
303 if(selected_object->doShowSelectionBox())
305 aabb3f *selection_box = selected_object->getSelectionBox();
306 // Box should exist because object was
307 // returned in the first place
308 assert(selection_box);
310 v3f pos = selected_object->getPosition();
311 hilightboxes.push_back(aabb3f(
312 selection_box->MinEdge + pos - intToFloat(camera_offset, BS),
313 selection_box->MaxEdge + pos - intToFloat(camera_offset, BS)));
316 mindistance = (selected_object->getPosition() - camera_position).getLength();
318 result.type = POINTEDTHING_OBJECT;
319 result.object_id = selected_object->getId();
323 // That didn't work, try to find a pointed at node
326 v3s16 pos_i = floatToInt(player_position, BS);
328 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
332 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
333 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
334 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
335 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
336 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
337 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
339 // Prevent signed number overflow
347 for(s16 y = ystart; y <= yend; y++)
348 for(s16 z = zstart; z <= zend; z++)
349 for(s16 x = xstart; x <= xend; x++)
354 n = map.getNode(v3s16(x,y,z));
356 catch(InvalidPositionException &e)
360 if(!isPointableNode(n, client, liquids_pointable))
363 std::vector<aabb3f> boxes = n.getSelectionBoxes(nodedef);
366 v3f npf = intToFloat(np, BS);
368 for(std::vector<aabb3f>::const_iterator
370 i != boxes.end(); i++)
376 for(u16 j=0; j<6; j++)
378 v3s16 facedir = g_6dirs[j];
379 aabb3f facebox = box;
383 facebox.MinEdge.X = facebox.MaxEdge.X-d;
384 else if(facedir.X < 0)
385 facebox.MaxEdge.X = facebox.MinEdge.X+d;
386 else if(facedir.Y > 0)
387 facebox.MinEdge.Y = facebox.MaxEdge.Y-d;
388 else if(facedir.Y < 0)
389 facebox.MaxEdge.Y = facebox.MinEdge.Y+d;
390 else if(facedir.Z > 0)
391 facebox.MinEdge.Z = facebox.MaxEdge.Z-d;
392 else if(facedir.Z < 0)
393 facebox.MaxEdge.Z = facebox.MinEdge.Z+d;
395 v3f centerpoint = facebox.getCenter();
396 f32 distance = (centerpoint - camera_position).getLength();
397 if(distance >= mindistance)
399 if(!facebox.intersectsWithLine(shootline))
402 v3s16 np_above = np + facedir;
404 result.type = POINTEDTHING_NODE;
405 result.node_undersurface = np;
406 result.node_abovesurface = np_above;
407 mindistance = distance;
409 hilightboxes.clear();
410 if (!g_settings->getBool("enable_node_highlighting")) {
411 for(std::vector<aabb3f>::const_iterator
413 i2 != boxes.end(); i2++)
416 box.MinEdge += npf + v3f(-d,-d,-d) - intToFloat(camera_offset, BS);
417 box.MaxEdge += npf + v3f(d,d,d) - intToFloat(camera_offset, BS);
418 hilightboxes.push_back(box);
428 /* Profiler display */
430 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
431 gui::IGUIFont *font, u32 text_height, u32 show_profiler,
432 u32 show_profiler_max)
434 if(show_profiler == 0)
436 guitext_profiler->setVisible(false);
441 std::ostringstream os(std::ios_base::binary);
442 g_profiler->printPage(os, show_profiler, show_profiler_max);
443 std::wstring text = narrow_to_wide(os.str());
444 guitext_profiler->setText(text.c_str());
445 guitext_profiler->setVisible(true);
447 s32 w = font->getDimension(text.c_str()).Width;
450 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
451 8+(text_height+5)*2 +
452 font->getDimension(text.c_str()).Height);
453 guitext_profiler->setRelativePosition(rect);
454 guitext_profiler->setVisible(true);
462 Profiler::GraphValues values;
468 Meta(float initial=0, video::SColor color=
469 video::SColor(255,255,255,255)):
475 std::list<Piece> m_log;
483 void put(const Profiler::GraphValues &values)
486 piece.values = values;
487 m_log.push_back(piece);
488 while(m_log.size() > m_log_max_size)
489 m_log.erase(m_log.begin());
492 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
493 gui::IGUIFont* font) const
495 std::map<std::string, Meta> m_meta;
496 for(std::list<Piece>::const_iterator k = m_log.begin();
497 k != m_log.end(); k++)
499 const Piece &piece = *k;
500 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
501 i != piece.values.end(); i++){
502 const std::string &id = i->first;
503 const float &value = i->second;
504 std::map<std::string, Meta>::iterator j =
506 if(j == m_meta.end()){
507 m_meta[id] = Meta(value);
510 if(value < j->second.min)
511 j->second.min = value;
512 if(value > j->second.max)
513 j->second.max = value;
518 static const video::SColor usable_colors[] = {
519 video::SColor(255,255,100,100),
520 video::SColor(255,90,225,90),
521 video::SColor(255,100,100,255),
522 video::SColor(255,255,150,50),
523 video::SColor(255,220,220,100)
525 static const u32 usable_colors_count =
526 sizeof(usable_colors) / sizeof(*usable_colors);
527 u32 next_color_i = 0;
528 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
529 i != m_meta.end(); i++){
530 Meta &meta = i->second;
531 video::SColor color(255,200,200,200);
532 if(next_color_i < usable_colors_count)
533 color = usable_colors[next_color_i++];
538 s32 textx = x_left + m_log_max_size + 15;
539 s32 textx2 = textx + 200 - 15;
543 u32 num_graphs = m_meta.size();
544 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
546 video::SColor bgcolor(120,0,0,0);
547 driver->draw2DRectangle(bgcolor, rect, NULL);
551 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
552 i != m_meta.end(); i++){
553 const std::string &id = i->first;
554 const Meta &meta = i->second;
556 s32 y = y_bottom - meta_i * 50;
557 float show_min = meta.min;
558 float show_max = meta.max;
559 if(show_min >= -0.0001 && show_max >= -0.0001){
560 if(show_min <= show_max * 0.5)
565 snprintf(buf, 10, "%.3g", show_max);
566 font->draw(narrow_to_wide(buf).c_str(),
567 core::rect<s32>(textx, y - graphh,
568 textx2, y - graphh + texth),
570 snprintf(buf, 10, "%.3g", show_min);
571 font->draw(narrow_to_wide(buf).c_str(),
572 core::rect<s32>(textx, y - texth,
575 font->draw(narrow_to_wide(id).c_str(),
576 core::rect<s32>(textx, y - graphh/2 - texth/2,
577 textx2, y - graphh/2 + texth/2),
580 s32 graph1h = graphh;
581 bool relativegraph = (show_min != 0 && show_min != show_max);
582 float lastscaledvalue = 0.0;
583 bool lastscaledvalue_exists = false;
584 for(std::list<Piece>::const_iterator j = m_log.begin();
585 j != m_log.end(); j++)
587 const Piece &piece = *j;
589 bool value_exists = false;
590 Profiler::GraphValues::const_iterator k =
591 piece.values.find(id);
592 if(k != piece.values.end()){
598 lastscaledvalue_exists = false;
601 float scaledvalue = 1.0;
602 if(show_max != show_min)
603 scaledvalue = (value - show_min) / (show_max - show_min);
604 if(scaledvalue == 1.0 && value == 0){
606 lastscaledvalue_exists = false;
610 if(lastscaledvalue_exists){
611 s32 ivalue1 = lastscaledvalue * graph1h;
612 s32 ivalue2 = scaledvalue * graph1h;
613 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
614 v2s32(x, graph1y - ivalue2), meta.color);
616 lastscaledvalue = scaledvalue;
617 lastscaledvalue_exists = true;
619 s32 ivalue = scaledvalue * graph1h;
620 driver->draw2DLine(v2s32(x, graph1y),
621 v2s32(x, graph1y - ivalue), meta.color);
630 class NodeDugEvent: public MtEvent
636 NodeDugEvent(v3s16 p, MapNode n):
640 const char* getType() const
646 ISoundManager *m_sound;
647 INodeDefManager *m_ndef;
649 float m_player_step_timer;
651 SimpleSoundSpec m_player_step_sound;
652 SimpleSoundSpec m_player_leftpunch_sound;
653 SimpleSoundSpec m_player_rightpunch_sound;
655 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
658 m_player_step_timer(0)
662 void playPlayerStep()
664 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
665 m_player_step_timer = 0.03;
666 m_sound->playSound(m_player_step_sound, false);
670 static void viewBobbingStep(MtEvent *e, void *data)
672 SoundMaker *sm = (SoundMaker*)data;
673 sm->playPlayerStep();
676 static void playerRegainGround(MtEvent *e, void *data)
678 SoundMaker *sm = (SoundMaker*)data;
679 sm->playPlayerStep();
682 static void playerJump(MtEvent *e, void *data)
684 //SoundMaker *sm = (SoundMaker*)data;
687 static void cameraPunchLeft(MtEvent *e, void *data)
689 SoundMaker *sm = (SoundMaker*)data;
690 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
693 static void cameraPunchRight(MtEvent *e, void *data)
695 SoundMaker *sm = (SoundMaker*)data;
696 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
699 static void nodeDug(MtEvent *e, void *data)
701 SoundMaker *sm = (SoundMaker*)data;
702 NodeDugEvent *nde = (NodeDugEvent*)e;
703 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
706 static void playerDamage(MtEvent *e, void *data)
708 SoundMaker *sm = (SoundMaker*)data;
709 sm->m_sound->playSound(SimpleSoundSpec("player_damage", 0.5), false);
712 static void playerFallingDamage(MtEvent *e, void *data)
714 SoundMaker *sm = (SoundMaker*)data;
715 sm->m_sound->playSound(SimpleSoundSpec("player_falling_damage", 0.5), false);
718 void registerReceiver(MtEventManager *mgr)
720 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
721 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
722 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
723 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
724 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
725 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
726 mgr->reg("PlayerDamage", SoundMaker::playerDamage, this);
727 mgr->reg("PlayerFallingDamage", SoundMaker::playerFallingDamage, this);
730 void step(float dtime)
732 m_player_step_timer -= dtime;
736 // Locally stored sounds don't need to be preloaded because of this
737 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
739 std::set<std::string> m_fetched;
742 void fetchSounds(const std::string &name,
743 std::set<std::string> &dst_paths,
744 std::set<std::string> &dst_datas)
746 if(m_fetched.count(name))
748 m_fetched.insert(name);
749 std::string base = porting::path_share + DIR_DELIM + "testsounds";
750 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
751 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
752 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
753 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
754 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
755 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
756 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
757 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
758 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
759 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
760 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
764 class GameGlobalShaderConstantSetter : public IShaderConstantSetter
767 bool *m_force_fog_off;
772 GameGlobalShaderConstantSetter(Sky *sky, bool *force_fog_off,
773 f32 *fog_range, Client *client):
775 m_force_fog_off(force_fog_off),
776 m_fog_range(fog_range),
779 ~GameGlobalShaderConstantSetter() {}
781 virtual void onSetConstants(video::IMaterialRendererServices *services,
788 video::SColor bgcolor = m_sky->getBgColor();
789 video::SColorf bgcolorf(bgcolor);
790 float bgcolorfa[4] = {
796 services->setPixelShaderConstant("skyBgColor", bgcolorfa, 4);
799 float fog_distance = 10000*BS;
800 if(g_settings->getBool("enable_fog") && !*m_force_fog_off)
801 fog_distance = *m_fog_range;
802 services->setPixelShaderConstant("fogDistance", &fog_distance, 1);
805 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
806 float daynight_ratio_f = (float)daynight_ratio / 1000.0;
807 services->setPixelShaderConstant("dayNightRatio", &daynight_ratio_f, 1);
809 u32 animation_timer = porting::getTimeMs() % 100000;
810 float animation_timer_f = (float)animation_timer / 100000.0;
811 services->setPixelShaderConstant("animationTimer", &animation_timer_f, 1);
812 services->setVertexShaderConstant("animationTimer", &animation_timer_f, 1);
814 LocalPlayer* player = m_client->getEnv().getLocalPlayer();
815 v3f eye_position = player->getEyePosition();
816 services->setPixelShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
817 services->setVertexShaderConstant("eyePosition", (irr::f32*)&eye_position, 3);
819 // Uniform sampler layers
823 // before 1.8 there isn't a "integer interface", only float
824 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
825 services->setPixelShaderConstant("baseTexture" , (irr::f32*)&layer0, 1);
826 services->setPixelShaderConstant("normalTexture" , (irr::f32*)&layer1, 1);
827 services->setPixelShaderConstant("useNormalmap" , (irr::f32*)&layer2, 1);
829 services->setPixelShaderConstant("baseTexture" , (irr::s32*)&layer0, 1);
830 services->setPixelShaderConstant("normalTexture" , (irr::s32*)&layer1, 1);
831 services->setPixelShaderConstant("useNormalmap" , (irr::s32*)&layer2, 1);
836 bool nodePlacementPrediction(Client &client,
837 const ItemDefinition &playeritem_def, v3s16 nodepos, v3s16 neighbourpos)
839 std::string prediction = playeritem_def.node_placement_prediction;
840 INodeDefManager *nodedef = client.ndef();
841 ClientMap &map = client.getEnv().getClientMap();
843 if(prediction != "" && !nodedef->get(map.getNode(nodepos)).rightclickable)
845 verbosestream<<"Node placement prediction for "
846 <<playeritem_def.name<<" is "
847 <<prediction<<std::endl;
848 v3s16 p = neighbourpos;
849 // Place inside node itself if buildable_to
851 MapNode n_under = map.getNode(nodepos);
852 if(nodedef->get(n_under).buildable_to)
854 else if (!nodedef->get(map.getNode(p)).buildable_to)
856 }catch(InvalidPositionException &e){}
857 // Find id of predicted node
859 bool found = nodedef->getId(prediction, id);
861 errorstream<<"Node placement prediction failed for "
862 <<playeritem_def.name<<" (places "
864 <<") - Name not known"<<std::endl;
867 // Predict param2 for facedir and wallmounted nodes
869 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED){
870 v3s16 dir = nodepos - neighbourpos;
871 if(abs(dir.Y) > MYMAX(abs(dir.X), abs(dir.Z))){
872 param2 = dir.Y < 0 ? 1 : 0;
873 } else if(abs(dir.X) > abs(dir.Z)){
874 param2 = dir.X < 0 ? 3 : 2;
876 param2 = dir.Z < 0 ? 5 : 4;
879 if(nodedef->get(id).param_type_2 == CPT2_FACEDIR){
880 v3s16 dir = nodepos - floatToInt(client.getEnv().getLocalPlayer()->getPosition(), BS);
881 if(abs(dir.X) > abs(dir.Z)){
882 param2 = dir.X < 0 ? 3 : 1;
884 param2 = dir.Z < 0 ? 2 : 0;
887 assert(param2 >= 0 && param2 <= 5);
888 //Check attachment if node is in group attached_node
889 if(((ItemGroupList) nodedef->get(id).groups)["attached_node"] != 0){
890 static v3s16 wallmounted_dirs[8] = {
899 if(nodedef->get(id).param_type_2 == CPT2_WALLMOUNTED)
900 pp = p + wallmounted_dirs[param2];
902 pp = p + v3s16(0,-1,0);
903 if(!nodedef->get(map.getNode(pp)).walkable)
906 // Add node to client map
907 MapNode n(id, 0, param2);
909 LocalPlayer* player = client.getEnv().getLocalPlayer();
911 // Dont place node when player would be inside new node
912 // NOTE: This is to be eventually implemented by a mod as client-side Lua
913 if (!nodedef->get(n).walkable ||
914 (client.checkPrivilege("noclip") && g_settings->getBool("noclip")) ||
915 (nodedef->get(n).walkable &&
916 neighbourpos != player->getStandingNodePos() + v3s16(0,1,0) &&
917 neighbourpos != player->getStandingNodePos() + v3s16(0,2,0))) {
919 // This triggers the required mesh update too
920 client.addNode(p, n);
923 }catch(InvalidPositionException &e){
924 errorstream<<"Node placement prediction failed for "
925 <<playeritem_def.name<<" (places "
927 <<") - Position not loaded"<<std::endl;
933 static inline void create_formspec_menu(GUIFormSpecMenu** cur_formspec,
934 InventoryManager *invmgr, IGameDef *gamedef,
935 IWritableTextureSource* tsrc, IrrlichtDevice * device,
936 IFormSource* fs_src, TextDest* txt_dest, Client* client
939 if (*cur_formspec == 0) {
940 *cur_formspec = new GUIFormSpecMenu(device, guiroot, -1, &g_menumgr,
941 invmgr, gamedef, tsrc, fs_src, txt_dest, cur_formspec, client);
942 (*cur_formspec)->doPause = false;
943 (*cur_formspec)->drop();
946 (*cur_formspec)->setFormSource(fs_src);
947 (*cur_formspec)->setTextDest(txt_dest);
952 #define SIZE_TAG "size[11,5.5]"
954 #define SIZE_TAG "size[11,5.5,true]"
957 static void show_chat_menu(GUIFormSpecMenu** cur_formspec,
958 InventoryManager *invmgr, IGameDef *gamedef,
959 IWritableTextureSource* tsrc, IrrlichtDevice * device,
960 Client* client, std::string text)
962 std::string formspec =
963 FORMSPEC_VERSION_STRING
965 "field[3,2.35;6,0.5;f_text;;" + text + "]"
966 "button_exit[4,3;3,0.5;btn_send;" + wide_to_narrow(wstrgettext("Proceed")) + "]"
970 /* Note: FormspecFormSource and LocalFormspecHandler
971 * are deleted by guiFormSpecMenu */
972 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
973 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_CHAT_MENU", client);
975 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
978 static void show_deathscreen(GUIFormSpecMenu** cur_formspec,
979 InventoryManager *invmgr, IGameDef *gamedef,
980 IWritableTextureSource* tsrc, IrrlichtDevice * device, Client* client)
982 std::string formspec =
983 std::string(FORMSPEC_VERSION_STRING) +
985 "bgcolor[#320000b4;true]"
986 "label[4.85,1.35;You died.]"
987 "button_exit[4,3;3,0.5;btn_respawn;" + gettext("Respawn") + "]"
991 /* Note: FormspecFormSource and LocalFormspecHandler
992 * are deleted by guiFormSpecMenu */
993 FormspecFormSource* fs_src = new FormspecFormSource(formspec);
994 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client);
996 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
999 /******************************************************************************/
1000 static void show_pause_menu(GUIFormSpecMenu** cur_formspec,
1001 InventoryManager *invmgr, IGameDef *gamedef,
1002 IWritableTextureSource* tsrc, IrrlichtDevice * device,
1003 bool singleplayermode)
1006 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1007 "No menu visible:\n"
1008 "- single tap: button activate\n"
1009 "- double tap: place/use\n"
1010 "- slide finger: look around\n"
1011 "Menu/Inventory visible:\n"
1012 "- double tap (outside):\n"
1014 "- touch stack, touch slot:\n"
1016 "- touch&drag, tap 2nd finger\n"
1017 " --> place single item to slot\n"
1020 std::string control_text = wide_to_narrow(wstrgettext("Default Controls:\n"
1022 "- Space: jump/climb\n"
1023 "- Shift: sneak/go down\n"
1026 "- Mouse: turn/look\n"
1027 "- Mouse left: dig/punch\n"
1028 "- Mouse right: place/use\n"
1029 "- Mouse wheel: select item\n"
1033 float ypos = singleplayermode ? 1.0 : 0.5;
1034 std::ostringstream os;
1036 os << FORMSPEC_VERSION_STRING << SIZE_TAG
1037 << "button_exit[4," << (ypos++) << ";3,0.5;btn_continue;"
1038 << wide_to_narrow(wstrgettext("Continue")) << "]";
1040 if (!singleplayermode) {
1041 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_change_password;"
1042 << wide_to_narrow(wstrgettext("Change Password")) << "]";
1045 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_sound;"
1046 << wide_to_narrow(wstrgettext("Sound Volume")) << "]";
1047 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_menu;"
1048 << wide_to_narrow(wstrgettext("Exit to Menu")) << "]";
1049 os << "button_exit[4," << (ypos++) << ";3,0.5;btn_exit_os;"
1050 << wide_to_narrow(wstrgettext("Exit to OS")) << "]"
1051 << "textarea[7.5,0.25;3.9,6.25;;" << control_text << ";]"
1052 << "textarea[0.4,0.25;3.5,6;;" << "Minetest\n"
1053 << minetest_build_info << "\n"
1054 << "path_user = " << wrap_rows(porting::path_user, 20)
1058 /* Note: FormspecFormSource and LocalFormspecHandler *
1059 * are deleted by guiFormSpecMenu */
1060 FormspecFormSource* fs_src = new FormspecFormSource(os.str());
1061 LocalFormspecHandler* txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU");
1063 create_formspec_menu(cur_formspec, invmgr, gamedef, tsrc, device, fs_src, txt_dst, NULL);
1065 (*cur_formspec)->doPause = true;
1068 /******************************************************************************/
1069 static void updateChat(Client& client, f32 dtime, bool show_debug,
1070 const v2u32& screensize, bool show_chat, u32 show_profiler,
1071 ChatBackend& chat_backend, gui::IGUIStaticText* guitext_chat,
1072 gui::IGUIFont* font)
1074 // Add chat log output for errors to be shown in chat
1075 static LogOutputBuffer chat_log_error_buf(LMT_ERROR);
1077 // Get new messages from error log buffer
1078 while(!chat_log_error_buf.empty()) {
1079 chat_backend.addMessage(L"", narrow_to_wide(chat_log_error_buf.get()));
1082 // Get new messages from client
1083 std::wstring message;
1084 while (client.getChatMessage(message)) {
1085 chat_backend.addUnparsedMessage(message);
1088 // Remove old messages
1089 chat_backend.step(dtime);
1091 // Display all messages in a static text element
1092 unsigned int recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
1093 std::wstring recent_chat = chat_backend.getRecentChat();
1095 // TODO replace by fontengine fcts
1096 unsigned int line_height = font->getDimension(L"Ay").Height + font->getKerningHeight();
1098 guitext_chat->setText(recent_chat.c_str());
1100 // Update gui element size and position
1101 s32 chat_y = 5 + line_height;
1103 chat_y += line_height;
1105 // first pass to calculate height of text to be set
1106 s32 width = std::min(font->getDimension(recent_chat.c_str()).Width + 10,
1107 porting::getWindowSize().X - 20);
1108 core::rect<s32> rect(10, chat_y, width, chat_y + porting::getWindowSize().Y);
1109 guitext_chat->setRelativePosition(rect);
1111 //now use real height of text and adjust rect according to this size
1112 rect = core::rect<s32>(10, chat_y, width,
1113 chat_y + guitext_chat->getTextHeight());
1116 guitext_chat->setRelativePosition(rect);
1117 // Don't show chat if disabled or empty or profiler is enabled
1118 guitext_chat->setVisible(
1119 show_chat && recent_chat_count != 0 && !show_profiler);
1122 /******************************************************************************/
1123 void the_game(bool &kill, bool random_input, InputHandler *input,
1124 IrrlichtDevice *device, gui::IGUIFont* font, std::string map_dir,
1125 std::string playername, std::string password,
1126 std::string address /* If "", local server is used */,
1127 u16 port, std::wstring &error_message, ChatBackend &chat_backend,
1128 const SubgameSpec &gamespec /* Used for local game */,
1129 bool simple_singleplayer_mode)
1131 GUIFormSpecMenu* current_formspec = 0;
1132 video::IVideoDriver* driver = device->getVideoDriver();
1133 scene::ISceneManager* smgr = device->getSceneManager();
1135 // Calculate text height using the font
1136 u32 text_height = font->getDimension(L"Random test string").Height;
1139 Draw "Loading" screen
1143 wchar_t* text = wgettext("Loading...");
1144 draw_load_screen(text, device, guienv, font, 0, 0);
1148 // Create texture source
1149 IWritableTextureSource *tsrc = createTextureSource(device);
1151 // Create shader source
1152 IWritableShaderSource *shsrc = createShaderSource(device);
1154 // These will be filled by data received from the server
1155 // Create item definition manager
1156 IWritableItemDefManager *itemdef = createItemDefManager();
1157 // Create node definition manager
1158 IWritableNodeDefManager *nodedef = createNodeDefManager();
1160 // Sound fetcher (useful when testing)
1161 GameOnDemandSoundFetcher soundfetcher;
1164 ISoundManager *sound = NULL;
1165 bool sound_is_dummy = false;
1167 if(g_settings->getBool("enable_sound")){
1168 infostream<<"Attempting to use OpenAL audio"<<std::endl;
1169 sound = createOpenALSoundManager(&soundfetcher);
1171 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
1173 infostream<<"Sound disabled."<<std::endl;
1177 infostream<<"Using dummy audio."<<std::endl;
1178 sound = &dummySoundManager;
1179 sound_is_dummy = true;
1182 Server *server = NULL;
1186 EventManager eventmgr;
1189 SoundMaker soundmaker(sound, nodedef);
1190 soundmaker.registerReceiver(&eventmgr);
1192 // Create UI for modifying quicktune values
1193 QuicktuneShortcutter quicktune;
1200 wchar_t* text = wgettext("Creating server....");
1201 draw_load_screen(text, device, guienv, font, 0, 25);
1203 infostream<<"Creating server"<<std::endl;
1205 std::string bind_str = g_settings->get("bind_address");
1206 Address bind_addr(0,0,0,0, port);
1208 if (g_settings->getBool("ipv6_server")) {
1209 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1212 bind_addr.Resolve(bind_str.c_str());
1214 } catch (ResolveError &e) {
1215 infostream << "Resolving bind address \"" << bind_str
1216 << "\" failed: " << e.what()
1217 << " -- Listening on all addresses." << std::endl;
1220 if(bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1221 error_message = L"Unable to listen on " +
1222 narrow_to_wide(bind_addr.serializeString()) +
1223 L" because IPv6 is disabled";
1224 errorstream<<wide_to_narrow(error_message)<<std::endl;
1225 // Break out of client scope
1229 server = new Server(map_dir, gamespec,
1230 simple_singleplayer_mode,
1231 bind_addr.isIPv6());
1233 server->start(bind_addr);
1236 do{ // Client scope (breakable do-while(0))
1243 wchar_t* text = wgettext("Creating client...");
1244 draw_load_screen(text, device, guienv, font, 0, 50);
1247 infostream<<"Creating client"<<std::endl;
1249 MapDrawControl draw_control;
1252 wchar_t* text = wgettext("Resolving address...");
1253 draw_load_screen(text, device, guienv, font, 0, 75);
1256 Address connect_address(0,0,0,0, port);
1258 connect_address.Resolve(address.c_str());
1259 if (connect_address.isZero()) { // i.e. INADDR_ANY, IN6ADDR_ANY
1260 //connect_address.Resolve("localhost");
1261 if (connect_address.isIPv6()) {
1262 IPv6AddressBytes addr_bytes;
1263 addr_bytes.bytes[15] = 1;
1264 connect_address.setAddress(&addr_bytes);
1266 connect_address.setAddress(127,0,0,1);
1270 catch(ResolveError &e) {
1271 error_message = L"Couldn't resolve address: " + narrow_to_wide(e.what());
1272 errorstream<<wide_to_narrow(error_message)<<std::endl;
1273 // Break out of client scope
1276 if(connect_address.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1277 error_message = L"Unable to connect to " +
1278 narrow_to_wide(connect_address.serializeString()) +
1279 L" because IPv6 is disabled";
1280 errorstream<<wide_to_narrow(error_message)<<std::endl;
1281 // Break out of client scope
1288 Client client(device, playername.c_str(), password, draw_control,
1289 tsrc, shsrc, itemdef, nodedef, sound, &eventmgr,
1290 connect_address.isIPv6());
1292 // Client acts as our GameDef
1293 IGameDef *gamedef = &client;
1296 Attempt to connect to the server
1299 infostream<<"Connecting to server at ";
1300 connect_address.print(&infostream);
1301 infostream<<std::endl;
1302 client.connect(connect_address);
1305 Wait for server to accept connection
1307 bool could_connect = false;
1308 bool connect_aborted = false;
1310 float time_counter = 0.0;
1312 float fps_max = g_settings->getFloat("fps_max");
1313 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1314 u32 lasttime = device->getTimer()->getTime();
1315 while(device->run())
1317 f32 dtime = 0.033; // in seconds
1318 if (cloud_menu_background) {
1319 u32 time = device->getTimer()->getTime();
1321 dtime = (time - lasttime) / 1000.0;
1326 // Update client and server
1329 server->step(dtime);
1332 if(client.getState() == LC_Init) {
1333 could_connect = true;
1337 if(client.accessDenied()) {
1338 error_message = L"Access denied. Reason: "
1339 +client.accessDeniedReason();
1340 errorstream<<wide_to_narrow(error_message)<<std::endl;
1343 if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1344 connect_aborted = true;
1345 infostream<<"Connect aborted [Escape]"<<std::endl;
1351 wchar_t* text = wgettext("Connecting to server...");
1352 draw_load_screen(text, device, guienv, font, dtime, 100);
1356 // On some computers framerate doesn't seem to be
1357 // automatically limited
1358 if (cloud_menu_background) {
1359 // Time of frame without fps limit
1362 // not using getRealTime is necessary for wine
1363 u32 time = device->getTimer()->getTime();
1365 busytime_u32 = time - lasttime;
1368 busytime = busytime_u32 / 1000.0;
1371 u32 frametime_min = 1000./fps_max;
1373 if(busytime_u32 < frametime_min) {
1374 u32 sleeptime = frametime_min - busytime_u32;
1375 device->sleep(sleeptime);
1380 time_counter += dtime;
1383 catch(con::PeerNotFoundException &e)
1387 Handle failure to connect
1389 if(!could_connect) {
1390 if(error_message == L"" && !connect_aborted) {
1391 error_message = L"Connection failed";
1392 errorstream<<wide_to_narrow(error_message)<<std::endl;
1394 // Break out of client scope
1399 Wait until content has been received
1401 bool got_content = false;
1402 bool content_aborted = false;
1404 float time_counter = 0.0;
1406 float fps_max = g_settings->getFloat("fps_max");
1407 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1408 u32 lasttime = device->getTimer()->getTime();
1409 while (device->run()) {
1410 f32 dtime = 0.033; // in seconds
1411 if (cloud_menu_background) {
1412 u32 time = device->getTimer()->getTime();
1414 dtime = (time - lasttime) / 1000.0;
1419 // Update client and server
1422 server->step(dtime);
1425 if (client.mediaReceived() &&
1426 client.itemdefReceived() &&
1427 client.nodedefReceived()) {
1432 if (client.accessDenied()) {
1433 error_message = L"Access denied. Reason: "
1434 +client.accessDeniedReason();
1435 errorstream<<wide_to_narrow(error_message)<<std::endl;
1438 if (client.getState() < LC_Init) {
1439 error_message = L"Client disconnected";
1440 errorstream<<wide_to_narrow(error_message)<<std::endl;
1443 if (input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey)) {
1444 content_aborted = true;
1445 infostream<<"Connect aborted [Escape]"<<std::endl;
1451 if (!client.itemdefReceived())
1453 wchar_t* text = wgettext("Item definitions...");
1455 draw_load_screen(text, device, guienv, font, dtime, progress);
1458 else if (!client.nodedefReceived())
1460 wchar_t* text = wgettext("Node definitions...");
1462 draw_load_screen(text, device, guienv, font, dtime, progress);
1468 std::stringstream message;
1469 message.precision(3);
1470 message << gettext("Media...");
1472 if ( ( USE_CURL == 0) ||
1473 (!g_settings->getBool("enable_remote_media_server"))) {
1474 float cur = client.getCurRate();
1475 std::string cur_unit = gettext(" KB/s");
1479 cur_unit = gettext(" MB/s");
1481 message << " ( " << cur << cur_unit << " )";
1483 progress = 50+client.mediaReceiveProgress()*50+0.5;
1484 draw_load_screen(narrow_to_wide(message.str().c_str()), device,
1485 guienv, font, dtime, progress);
1488 // On some computers framerate doesn't seem to be
1489 // automatically limited
1490 if (cloud_menu_background) {
1491 // Time of frame without fps limit
1494 // not using getRealTime is necessary for wine
1495 u32 time = device->getTimer()->getTime();
1497 busytime_u32 = time - lasttime;
1500 busytime = busytime_u32 / 1000.0;
1503 u32 frametime_min = 1000./fps_max;
1505 if(busytime_u32 < frametime_min) {
1506 u32 sleeptime = frametime_min - busytime_u32;
1507 device->sleep(sleeptime);
1512 time_counter += dtime;
1517 if(error_message == L"" && !content_aborted){
1518 error_message = L"Something failed";
1519 errorstream<<wide_to_narrow(error_message)<<std::endl;
1521 // Break out of client scope
1526 After all content has been received:
1527 Update cached textures, meshes and materials
1529 client.afterContentReceived(device,font);
1532 Create the camera node
1534 Camera camera(smgr, draw_control, gamedef);
1535 if (!camera.successfullyCreated(error_message))
1538 f32 camera_yaw = 0; // "right/left"
1539 f32 camera_pitch = 0; // "up/down"
1545 Clouds *clouds = NULL;
1546 if(g_settings->getBool("enable_clouds"))
1548 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1556 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1558 scene::ISceneNode* skybox = NULL;
1561 A copy of the local inventory
1563 Inventory local_inventory(itemdef);
1566 Find out size of crack animation
1568 int crack_animation_length = 5;
1570 video::ITexture *t = tsrc->getTexture("crack_anylength.png");
1571 v2u32 size = t->getOriginalSize();
1572 crack_animation_length = size.Y / size.X;
1579 // First line of debug text
1580 gui::IGUIStaticText *guitext = guienv->addStaticText(
1582 core::rect<s32>(0, 0, 0, 0),
1583 false, false, guiroot);
1584 // Second line of debug text
1585 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1587 core::rect<s32>(0, 0, 0, 0),
1588 false, false, guiroot);
1589 // At the middle of the screen
1590 // Object infos are shown in this
1591 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1593 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1594 false, true, guiroot);
1596 // Status text (displays info when showing and hiding GUI stuff, etc.)
1597 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1599 core::rect<s32>(0,0,0,0),
1600 false, false, guiroot);
1601 guitext_status->setVisible(false);
1603 std::wstring statustext;
1604 float statustext_time = 0;
1607 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1609 core::rect<s32>(0,0,0,0),
1610 //false, false); // Disable word wrap as of now
1611 false, true, guiroot);
1612 // Remove stale "recent" chat messages from previous connections
1613 chat_backend.clearRecentChat();
1614 // Chat backend and console
1615 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1617 // Profiler text (size is updated when text is updated)
1618 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1620 core::rect<s32>(0,0,0,0),
1621 false, false, guiroot);
1622 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1623 guitext_profiler->setVisible(false);
1624 guitext_profiler->setWordWrap(true);
1626 #ifdef HAVE_TOUCHSCREENGUI
1627 if (g_touchscreengui)
1628 g_touchscreengui->init(tsrc,porting::getDisplayDensity());
1632 Some statistics are collected in these
1635 u32 beginscenetime = 0;
1636 u32 endscenetime = 0;
1638 float recent_turn_speed = 0.0;
1640 ProfilerGraph graph;
1641 // Initially clear the profiler
1642 Profiler::GraphValues dummyvalues;
1643 g_profiler->graphGet(dummyvalues);
1645 float nodig_delay_timer = 0.0;
1646 float dig_time = 0.0;
1648 PointedThing pointed_old;
1649 bool digging = false;
1650 bool ldown_for_dig = false;
1652 float damage_flash = 0;
1654 float jump_timer = 0;
1655 bool reset_jump_timer = false;
1657 const float object_hit_delay = 0.2;
1658 float object_hit_delay_timer = 0.0;
1659 float time_from_last_punch = 10;
1661 float update_draw_list_timer = 0.0;
1662 v3f update_draw_list_last_cam_dir;
1664 bool invert_mouse = g_settings->getBool("invert_mouse");
1666 bool update_wielded_item_trigger = true;
1668 bool show_hud = true;
1669 bool show_chat = true;
1670 bool force_fog_off = false;
1671 f32 fog_range = 100*BS;
1672 bool disable_camera_update = false;
1673 bool show_debug = g_settings->getBool("show_debug");
1674 bool show_profiler_graph = false;
1675 u32 show_profiler = 0;
1676 u32 show_profiler_max = 3; // Number of pages
1678 float time_of_day = 0;
1679 float time_of_day_smooth = 0;
1681 float repeat_rightclick_timer = 0;
1686 shsrc->addGlobalConstantSetter(new GameGlobalShaderConstantSetter(
1687 sky, &force_fog_off, &fog_range, &client));
1693 bool first_loop_after_window_activation = true;
1695 // TODO: Convert the static interval timers to these
1696 // Interval limiter for profiler
1697 IntervalLimiter m_profiler_interval;
1699 // Time is in milliseconds
1700 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1701 // NOTE: So we have to use getTime() and call run()s between them
1702 u32 lasttime = device->getTimer()->getTime();
1704 LocalPlayer* player = client.getEnv().getLocalPlayer();
1705 player->hurt_tilt_timer = 0;
1706 player->hurt_tilt_strength = 0;
1711 Hud hud(driver, smgr, guienv, font, text_height,
1712 gamedef, player, &local_inventory);
1714 core::stringw str = L"Minetest [";
1715 str += driver->getName();
1717 device->setWindowCaption(str.c_str());
1720 std::wstring infotext;
1724 if(device->run() == false || kill == true ||
1725 g_gamecallback->shutdown_requested)
1728 v2u32 screensize = driver->getScreenSize();
1730 // Time of frame without fps limit
1734 // not using getRealTime is necessary for wine
1735 u32 time = device->getTimer()->getTime();
1737 busytime_u32 = time - lasttime;
1740 busytime = busytime_u32 / 1000.0;
1743 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1745 // Necessary for device->getTimer()->getTime()
1753 float fps_max = g_menumgr.pausesGame() ?
1754 g_settings->getFloat("pause_fps_max") :
1755 g_settings->getFloat("fps_max");
1756 u32 frametime_min = 1000./fps_max;
1758 if(busytime_u32 < frametime_min)
1760 u32 sleeptime = frametime_min - busytime_u32;
1761 device->sleep(sleeptime);
1762 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1766 // Necessary for device->getTimer()->getTime()
1770 Time difference calculation
1772 f32 dtime; // in seconds
1774 u32 time = device->getTimer()->getTime();
1776 dtime = (time - lasttime) / 1000.0;
1781 g_profiler->graphAdd("mainloop_dtime", dtime);
1785 if(nodig_delay_timer >= 0)
1786 nodig_delay_timer -= dtime;
1787 if(object_hit_delay_timer >= 0)
1788 object_hit_delay_timer -= dtime;
1789 time_from_last_punch += dtime;
1791 g_profiler->add("Elapsed time", dtime);
1792 g_profiler->avg("FPS", 1./dtime);
1795 Time average and jitter calculation
1798 static f32 dtime_avg1 = 0.0;
1799 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1800 f32 dtime_jitter1 = dtime - dtime_avg1;
1802 static f32 dtime_jitter1_max_sample = 0.0;
1803 static f32 dtime_jitter1_max_fraction = 0.0;
1805 static f32 jitter1_max = 0.0;
1806 static f32 counter = 0.0;
1807 if(dtime_jitter1 > jitter1_max)
1808 jitter1_max = dtime_jitter1;
1813 dtime_jitter1_max_sample = jitter1_max;
1814 dtime_jitter1_max_fraction
1815 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1821 Busytime average and jitter calculation
1824 static f32 busytime_avg1 = 0.0;
1825 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1826 f32 busytime_jitter1 = busytime - busytime_avg1;
1828 static f32 busytime_jitter1_max_sample = 0.0;
1829 static f32 busytime_jitter1_min_sample = 0.0;
1831 static f32 jitter1_max = 0.0;
1832 static f32 jitter1_min = 0.0;
1833 static f32 counter = 0.0;
1834 if(busytime_jitter1 > jitter1_max)
1835 jitter1_max = busytime_jitter1;
1836 if(busytime_jitter1 < jitter1_min)
1837 jitter1_min = busytime_jitter1;
1841 busytime_jitter1_max_sample = jitter1_max;
1842 busytime_jitter1_min_sample = jitter1_min;
1849 Handle miscellaneous stuff
1852 if(client.accessDenied())
1854 error_message = L"Access denied. Reason: "
1855 +client.accessDeniedReason();
1856 errorstream<<wide_to_narrow(error_message)<<std::endl;
1860 if(g_gamecallback->disconnect_requested)
1862 g_gamecallback->disconnect_requested = false;
1866 if(g_gamecallback->changepassword_requested)
1868 (new GUIPasswordChange(guienv, guiroot, -1,
1869 &g_menumgr, &client))->drop();
1870 g_gamecallback->changepassword_requested = false;
1873 if(g_gamecallback->changevolume_requested)
1875 (new GUIVolumeChange(guienv, guiroot, -1,
1876 &g_menumgr, &client))->drop();
1877 g_gamecallback->changevolume_requested = false;
1880 /* Process TextureSource's queue */
1881 tsrc->processQueue();
1883 /* Process ItemDefManager's queue */
1884 itemdef->processQueue(gamedef);
1887 Process ShaderSource's queue
1889 shsrc->processQueue();
1896 // Hilight boxes collected during the loop and displayed
1897 std::vector<aabb3f> hilightboxes;
1899 /* reset infotext */
1904 float profiler_print_interval =
1905 g_settings->getFloat("profiler_print_interval");
1906 bool print_to_log = true;
1907 if(profiler_print_interval == 0){
1908 print_to_log = false;
1909 profiler_print_interval = 5;
1911 if(m_profiler_interval.step(dtime, profiler_print_interval))
1914 infostream<<"Profiler:"<<std::endl;
1915 g_profiler->print(infostream);
1918 update_profiler_gui(guitext_profiler, font, text_height,
1919 show_profiler, show_profiler_max);
1921 g_profiler->clear();
1925 Direct handling of user input
1928 // Reset input if window not active or some menu is active
1929 if(device->isWindowActive() == false
1930 || noMenuActive() == false
1931 || guienv->hasFocus(gui_chat_console))
1935 if (!guienv->hasFocus(gui_chat_console) && gui_chat_console->isOpen())
1937 gui_chat_console->closeConsoleAtOnce();
1940 // Input handler step() (used by the random input generator)
1942 #ifdef HAVE_TOUCHSCREENGUI
1943 if (g_touchscreengui) {
1944 g_touchscreengui->step(dtime);
1948 if (current_formspec != 0)
1949 current_formspec->getAndroidUIInput();
1952 // Increase timer for doubleclick of "jump"
1953 if(g_settings->getBool("doubletap_jump") && jump_timer <= 0.2)
1954 jump_timer += dtime;
1957 Launch menus and trigger stuff according to keys
1959 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1961 // drop selected item
1962 IDropAction *a = new IDropAction();
1964 a->from_inv.setCurrentPlayer();
1965 a->from_list = "main";
1966 a->from_i = client.getPlayerItem();
1967 client.inventoryAction(a);
1969 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1971 infostream<<"the_game: "
1972 <<"Launching inventory"<<std::endl;
1974 PlayerInventoryFormSource* fs_src = new PlayerInventoryFormSource(&client);
1975 TextDest* txt_dst = new TextDestPlayerInventory(&client);
1977 create_formspec_menu(¤t_formspec, &client, gamedef, tsrc, device, fs_src, txt_dst, &client);
1979 InventoryLocation inventoryloc;
1980 inventoryloc.setCurrentPlayer();
1981 current_formspec->setFormSpec(fs_src->getForm(), inventoryloc);
1983 else if(input->wasKeyDown(EscapeKey) || input->wasKeyDown(CancelKey))
1985 show_pause_menu(¤t_formspec, &client, gamedef, tsrc, device,
1986 simple_singleplayer_mode);
1988 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1990 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
1993 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1995 show_chat_menu(¤t_formspec, &client, gamedef, tsrc, device,
1998 else if(input->wasKeyDown(getKeySetting("keymap_console")))
2000 if (!gui_chat_console->isOpenInhibited())
2002 // Open up to over half of the screen
2003 gui_chat_console->openConsole(0.6);
2004 guienv->setFocus(gui_chat_console);
2007 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
2009 if(g_settings->getBool("free_move"))
2011 g_settings->set("free_move","false");
2012 statustext = L"free_move disabled";
2013 statustext_time = 0;
2017 g_settings->set("free_move","true");
2018 statustext = L"free_move enabled";
2019 statustext_time = 0;
2020 if(!client.checkPrivilege("fly"))
2021 statustext += L" (note: no 'fly' privilege)";
2024 else if(input->wasKeyDown(getKeySetting("keymap_jump")))
2026 if(g_settings->getBool("doubletap_jump") && jump_timer < 0.2)
2028 if(g_settings->getBool("free_move"))
2030 g_settings->set("free_move","false");
2031 statustext = L"free_move disabled";
2032 statustext_time = 0;
2036 g_settings->set("free_move","true");
2037 statustext = L"free_move enabled";
2038 statustext_time = 0;
2039 if(!client.checkPrivilege("fly"))
2040 statustext += L" (note: no 'fly' privilege)";
2043 reset_jump_timer = true;
2045 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
2047 if(g_settings->getBool("fast_move"))
2049 g_settings->set("fast_move","false");
2050 statustext = L"fast_move disabled";
2051 statustext_time = 0;
2055 g_settings->set("fast_move","true");
2056 statustext = L"fast_move enabled";
2057 statustext_time = 0;
2058 if(!client.checkPrivilege("fast"))
2059 statustext += L" (note: no 'fast' privilege)";
2062 else if(input->wasKeyDown(getKeySetting("keymap_noclip")))
2064 if(g_settings->getBool("noclip"))
2066 g_settings->set("noclip","false");
2067 statustext = L"noclip disabled";
2068 statustext_time = 0;
2072 g_settings->set("noclip","true");
2073 statustext = L"noclip enabled";
2074 statustext_time = 0;
2075 if(!client.checkPrivilege("noclip"))
2076 statustext += L" (note: no 'noclip' privilege)";
2079 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
2081 client.makeScreenshot(device);
2083 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
2085 show_hud = !show_hud;
2087 statustext = L"HUD shown";
2088 client.setHighlighted(client.getHighlighted(), true);
2090 statustext = L"HUD hidden";
2091 client.setHighlighted(client.getHighlighted(), false);
2093 statustext_time = 0;
2095 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
2097 show_chat = !show_chat;
2099 statustext = L"Chat shown";
2101 statustext = L"Chat hidden";
2102 statustext_time = 0;
2104 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
2106 force_fog_off = !force_fog_off;
2108 statustext = L"Fog disabled";
2110 statustext = L"Fog enabled";
2111 statustext_time = 0;
2113 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
2115 disable_camera_update = !disable_camera_update;
2116 if(disable_camera_update)
2117 statustext = L"Camera update disabled";
2119 statustext = L"Camera update enabled";
2120 statustext_time = 0;
2122 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
2124 // Initial / 3x toggle: Chat only
2125 // 1x toggle: Debug text with chat
2126 // 2x toggle: Debug text with profiler graph
2130 show_profiler_graph = false;
2131 statustext = L"Debug info shown";
2132 statustext_time = 0;
2134 else if(show_profiler_graph)
2137 show_profiler_graph = false;
2138 statustext = L"Debug info and profiler graph hidden";
2139 statustext_time = 0;
2143 show_profiler_graph = true;
2144 statustext = L"Profiler graph shown";
2145 statustext_time = 0;
2148 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
2150 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
2152 // FIXME: This updates the profiler with incomplete values
2153 update_profiler_gui(guitext_profiler, font, text_height,
2154 show_profiler, show_profiler_max);
2156 if(show_profiler != 0)
2158 std::wstringstream sstr;
2159 sstr<<"Profiler shown (page "<<show_profiler
2160 <<" of "<<show_profiler_max<<")";
2161 statustext = sstr.str();
2162 statustext_time = 0;
2166 statustext = L"Profiler hidden";
2167 statustext_time = 0;
2170 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
2172 s16 range = g_settings->getS16("viewing_range_nodes_min");
2173 s16 range_new = range + 10;
2174 g_settings->set("viewing_range_nodes_min", itos(range_new));
2175 statustext = narrow_to_wide(
2176 "Minimum viewing range changed to "
2178 statustext_time = 0;
2180 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
2182 s16 range = g_settings->getS16("viewing_range_nodes_min");
2183 s16 range_new = range - 10;
2186 g_settings->set("viewing_range_nodes_min",
2188 statustext = narrow_to_wide(
2189 "Minimum viewing range changed to "
2191 statustext_time = 0;
2195 if(!input->isKeyDown(getKeySetting("keymap_jump")) && reset_jump_timer)
2197 reset_jump_timer = false;
2201 // Handle QuicktuneShortcutter
2202 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
2204 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
2206 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
2208 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
2211 std::string msg = quicktune.getMessage();
2213 statustext = narrow_to_wide(msg);
2214 statustext_time = 0;
2218 // Item selection with mouse wheel
2219 u16 new_playeritem = client.getPlayerItem();
2221 s32 wheel = input->getMouseWheel();
2222 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
2223 player->hud_hotbar_itemcount-1);
2227 if(new_playeritem < max_item)
2234 if(new_playeritem > 0)
2237 new_playeritem = max_item;
2242 for(u16 i=0; i<10; i++)
2244 const KeyPress *kp = NumberKey + (i + 1) % 10;
2245 if(input->wasKeyDown(*kp))
2247 if(i < PLAYER_INVENTORY_SIZE && i < player->hud_hotbar_itemcount)
2251 infostream<<"Selected item: "
2252 <<new_playeritem<<std::endl;
2257 // Viewing range selection
2258 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
2260 draw_control.range_all = !draw_control.range_all;
2261 if(draw_control.range_all)
2263 infostream<<"Enabled full viewing range"<<std::endl;
2264 statustext = L"Enabled full viewing range";
2265 statustext_time = 0;
2269 infostream<<"Disabled full viewing range"<<std::endl;
2270 statustext = L"Disabled full viewing range";
2271 statustext_time = 0;
2275 // Print debug stacks
2276 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
2278 dstream<<"-----------------------------------------"
2280 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
2281 dstream<<"-----------------------------------------"
2283 debug_stacks_print();
2287 Mouse and camera control
2288 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
2291 float turn_amount = 0;
2292 if((device->isWindowActive() && noMenuActive()) || random_input)
2297 // Mac OSX gets upset if this is set every frame
2298 if(device->getCursorControl()->isVisible())
2299 device->getCursorControl()->setVisible(false);
2303 if(first_loop_after_window_activation){
2304 //infostream<<"window active, first loop"<<std::endl;
2305 first_loop_after_window_activation = false;
2307 #ifdef HAVE_TOUCHSCREENGUI
2308 if (g_touchscreengui) {
2309 camera_yaw = g_touchscreengui->getYaw();
2310 camera_pitch = g_touchscreengui->getPitch();
2313 s32 dx = input->getMousePos().X - (driver->getScreenSize().Width/2);
2314 s32 dy = input->getMousePos().Y - (driver->getScreenSize().Height/2);
2316 || (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)) {
2319 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
2321 /*const float keyspeed = 500;
2322 if(input->isKeyDown(irr::KEY_UP))
2323 dy -= dtime * keyspeed;
2324 if(input->isKeyDown(irr::KEY_DOWN))
2325 dy += dtime * keyspeed;
2326 if(input->isKeyDown(irr::KEY_LEFT))
2327 dx -= dtime * keyspeed;
2328 if(input->isKeyDown(irr::KEY_RIGHT))
2329 dx += dtime * keyspeed;*/
2331 float d = g_settings->getFloat("mouse_sensitivity");
2332 d = rangelim(d, 0.01, 100.0);
2334 camera_pitch += dy*d;
2335 turn_amount = v2f(dx, dy).getLength() * d;
2337 #ifdef HAVE_TOUCHSCREENGUI
2340 if(camera_pitch < -89.5) camera_pitch = -89.5;
2341 if(camera_pitch > 89.5) camera_pitch = 89.5;
2343 input->setMousePos((driver->getScreenSize().Width/2),
2344 (driver->getScreenSize().Height/2));
2348 // Mac OSX gets upset if this is set every frame
2349 if(device->getCursorControl()->isVisible() == false)
2350 device->getCursorControl()->setVisible(true);
2353 //infostream<<"window inactive"<<std::endl;
2354 first_loop_after_window_activation = true;
2356 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
2357 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
2360 Player speed control
2374 PlayerControl control(
2375 input->isKeyDown(getKeySetting("keymap_forward")),
2376 input->isKeyDown(getKeySetting("keymap_backward")),
2377 input->isKeyDown(getKeySetting("keymap_left")),
2378 input->isKeyDown(getKeySetting("keymap_right")),
2379 input->isKeyDown(getKeySetting("keymap_jump")),
2380 input->isKeyDown(getKeySetting("keymap_special1")),
2381 input->isKeyDown(getKeySetting("keymap_sneak")),
2382 input->getLeftState(),
2383 input->getRightState(),
2387 client.setPlayerControl(control);
2388 LocalPlayer* player = client.getEnv().getLocalPlayer();
2390 (((int)input->isKeyDown(getKeySetting("keymap_forward")) & 0x1) << 0) |
2391 (((int)input->isKeyDown(getKeySetting("keymap_backward")) & 0x1) << 1) |
2392 (((int)input->isKeyDown(getKeySetting("keymap_left")) & 0x1) << 2) |
2393 (((int)input->isKeyDown(getKeySetting("keymap_right")) & 0x1) << 3) |
2394 (((int)input->isKeyDown(getKeySetting("keymap_jump")) & 0x1) << 4) |
2395 (((int)input->isKeyDown(getKeySetting("keymap_special1")) & 0x1) << 5) |
2396 (((int)input->isKeyDown(getKeySetting("keymap_sneak")) & 0x1) << 6) |
2397 (((int)input->getLeftState() & 0x1) << 7) |
2398 (((int)input->getRightState() & 0x1) << 8);
2402 Run server, client (and process environments)
2404 bool can_be_and_is_paused =
2405 (simple_singleplayer_mode && g_menumgr.pausesGame());
2406 if(can_be_and_is_paused)
2415 //TimeTaker timer("server->step(dtime)");
2416 server->step(dtime);
2419 //TimeTaker timer("client.step(dtime)");
2425 // Read client events
2427 ClientEvent event = client.getClientEvent();
2428 if(event.type == CE_NONE) {
2431 else if(event.type == CE_PLAYER_DAMAGE &&
2432 client.getHP() != 0) {
2433 //u16 damage = event.player_damage.amount;
2434 //infostream<<"Player damage: "<<damage<<std::endl;
2436 damage_flash += 100.0;
2437 damage_flash += 8.0 * event.player_damage.amount;
2439 player->hurt_tilt_timer = 1.5;
2440 player->hurt_tilt_strength = event.player_damage.amount/4;
2441 player->hurt_tilt_strength = rangelim(player->hurt_tilt_strength, 1.0, 4.0);
2443 MtEvent *e = new SimpleTriggerEvent("PlayerDamage");
2444 gamedef->event()->put(e);
2446 else if(event.type == CE_PLAYER_FORCE_MOVE) {
2447 camera_yaw = event.player_force_move.yaw;
2448 camera_pitch = event.player_force_move.pitch;
2450 else if(event.type == CE_DEATHSCREEN) {
2451 show_deathscreen(¤t_formspec, &client, gamedef, tsrc,
2454 chat_backend.addMessage(L"", L"You died.");
2456 /* Handle visualization */
2459 LocalPlayer* player = client.getEnv().getLocalPlayer();
2460 player->hurt_tilt_timer = 0;
2461 player->hurt_tilt_strength = 0;
2464 else if (event.type == CE_SHOW_FORMSPEC) {
2465 FormspecFormSource* fs_src =
2466 new FormspecFormSource(*(event.show_formspec.formspec));
2467 TextDestPlayerInventory* txt_dst =
2468 new TextDestPlayerInventory(&client,*(event.show_formspec.formname));
2470 create_formspec_menu(¤t_formspec, &client, gamedef,
2471 tsrc, device, fs_src, txt_dst, &client);
2473 delete(event.show_formspec.formspec);
2474 delete(event.show_formspec.formname);
2476 else if(event.type == CE_SPAWN_PARTICLE) {
2477 LocalPlayer* player = client.getEnv().getLocalPlayer();
2478 video::ITexture *texture =
2479 gamedef->tsrc()->getTexture(*(event.spawn_particle.texture));
2481 new Particle(gamedef, smgr, player, client.getEnv(),
2482 *event.spawn_particle.pos,
2483 *event.spawn_particle.vel,
2484 *event.spawn_particle.acc,
2485 event.spawn_particle.expirationtime,
2486 event.spawn_particle.size,
2487 event.spawn_particle.collisiondetection,
2488 event.spawn_particle.vertical,
2493 else if(event.type == CE_ADD_PARTICLESPAWNER) {
2494 LocalPlayer* player = client.getEnv().getLocalPlayer();
2495 video::ITexture *texture =
2496 gamedef->tsrc()->getTexture(*(event.add_particlespawner.texture));
2498 new ParticleSpawner(gamedef, smgr, player,
2499 event.add_particlespawner.amount,
2500 event.add_particlespawner.spawntime,
2501 *event.add_particlespawner.minpos,
2502 *event.add_particlespawner.maxpos,
2503 *event.add_particlespawner.minvel,
2504 *event.add_particlespawner.maxvel,
2505 *event.add_particlespawner.minacc,
2506 *event.add_particlespawner.maxacc,
2507 event.add_particlespawner.minexptime,
2508 event.add_particlespawner.maxexptime,
2509 event.add_particlespawner.minsize,
2510 event.add_particlespawner.maxsize,
2511 event.add_particlespawner.collisiondetection,
2512 event.add_particlespawner.vertical,
2514 event.add_particlespawner.id);
2516 else if(event.type == CE_DELETE_PARTICLESPAWNER) {
2517 delete_particlespawner (event.delete_particlespawner.id);
2519 else if (event.type == CE_HUDADD) {
2520 u32 id = event.hudadd.id;
2522 HudElement *e = player->getHud(id);
2525 delete event.hudadd.pos;
2526 delete event.hudadd.name;
2527 delete event.hudadd.scale;
2528 delete event.hudadd.text;
2529 delete event.hudadd.align;
2530 delete event.hudadd.offset;
2531 delete event.hudadd.world_pos;
2532 delete event.hudadd.size;
2537 e->type = (HudElementType)event.hudadd.type;
2538 e->pos = *event.hudadd.pos;
2539 e->name = *event.hudadd.name;
2540 e->scale = *event.hudadd.scale;
2541 e->text = *event.hudadd.text;
2542 e->number = event.hudadd.number;
2543 e->item = event.hudadd.item;
2544 e->dir = event.hudadd.dir;
2545 e->align = *event.hudadd.align;
2546 e->offset = *event.hudadd.offset;
2547 e->world_pos = *event.hudadd.world_pos;
2548 e->size = *event.hudadd.size;
2550 u32 new_id = player->addHud(e);
2551 //if this isn't true our huds aren't consistent
2552 assert(new_id == id);
2554 delete event.hudadd.pos;
2555 delete event.hudadd.name;
2556 delete event.hudadd.scale;
2557 delete event.hudadd.text;
2558 delete event.hudadd.align;
2559 delete event.hudadd.offset;
2560 delete event.hudadd.world_pos;
2561 delete event.hudadd.size;
2563 else if (event.type == CE_HUDRM) {
2564 HudElement* e = player->removeHud(event.hudrm.id);
2569 else if (event.type == CE_HUDCHANGE) {
2570 u32 id = event.hudchange.id;
2571 HudElement* e = player->getHud(id);
2574 delete event.hudchange.v3fdata;
2575 delete event.hudchange.v2fdata;
2576 delete event.hudchange.sdata;
2577 delete event.hudchange.v2s32data;
2581 switch (event.hudchange.stat) {
2583 e->pos = *event.hudchange.v2fdata;
2586 e->name = *event.hudchange.sdata;
2588 case HUD_STAT_SCALE:
2589 e->scale = *event.hudchange.v2fdata;
2592 e->text = *event.hudchange.sdata;
2594 case HUD_STAT_NUMBER:
2595 e->number = event.hudchange.data;
2598 e->item = event.hudchange.data;
2601 e->dir = event.hudchange.data;
2603 case HUD_STAT_ALIGN:
2604 e->align = *event.hudchange.v2fdata;
2606 case HUD_STAT_OFFSET:
2607 e->offset = *event.hudchange.v2fdata;
2609 case HUD_STAT_WORLD_POS:
2610 e->world_pos = *event.hudchange.v3fdata;
2613 e->size = *event.hudchange.v2s32data;
2617 delete event.hudchange.v3fdata;
2618 delete event.hudchange.v2fdata;
2619 delete event.hudchange.sdata;
2620 delete event.hudchange.v2s32data;
2622 else if (event.type == CE_SET_SKY) {
2623 sky->setVisible(false);
2628 // Handle according to type
2629 if(*event.set_sky.type == "regular") {
2630 sky->setVisible(true);
2632 else if(*event.set_sky.type == "skybox" &&
2633 event.set_sky.params->size() == 6) {
2634 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2635 skybox = smgr->addSkyBoxSceneNode(
2636 tsrc->getTexture((*event.set_sky.params)[0]),
2637 tsrc->getTexture((*event.set_sky.params)[1]),
2638 tsrc->getTexture((*event.set_sky.params)[2]),
2639 tsrc->getTexture((*event.set_sky.params)[3]),
2640 tsrc->getTexture((*event.set_sky.params)[4]),
2641 tsrc->getTexture((*event.set_sky.params)[5]));
2643 // Handle everything else as plain color
2645 if(*event.set_sky.type != "plain")
2646 infostream<<"Unknown sky type: "
2647 <<(*event.set_sky.type)<<std::endl;
2648 sky->setFallbackBgColor(*event.set_sky.bgcolor);
2651 delete event.set_sky.bgcolor;
2652 delete event.set_sky.type;
2653 delete event.set_sky.params;
2655 else if (event.type == CE_OVERRIDE_DAY_NIGHT_RATIO) {
2656 bool enable = event.override_day_night_ratio.do_override;
2657 u32 value = event.override_day_night_ratio.ratio_f * 1000;
2658 client.getEnv().setDayNightRatioOverride(enable, value);
2663 //TimeTaker //timer2("//timer2");
2666 For interaction purposes, get info about the held item
2668 - Is it a usable item?
2669 - Can it point to liquids?
2671 ItemStack playeritem;
2673 InventoryList *mlist = local_inventory.getList("main");
2674 if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
2675 playeritem = mlist->getItem(client.getPlayerItem());
2677 const ItemDefinition &playeritem_def =
2678 playeritem.getDefinition(itemdef);
2679 ToolCapabilities playeritem_toolcap =
2680 playeritem.getToolCapabilities(itemdef);
2686 v3s16 old_camera_offset = camera.getOffset();
2688 LocalPlayer* player = client.getEnv().getLocalPlayer();
2689 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2690 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2692 if(input->wasKeyDown(getKeySetting("keymap_camera_mode"))) {
2693 camera.toggleCameraMode();
2694 GenericCAO* playercao = player->getCAO();
2696 assert( playercao != NULL );
2697 if (camera.getCameraMode() > CAMERA_MODE_FIRST) {
2698 playercao->setVisible(true);
2701 playercao->setVisible(false);
2704 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2705 camera.update(player, dtime, busytime, tool_reload_ratio,
2709 v3f player_position = player->getPosition();
2710 v3f camera_position = camera.getPosition();
2711 v3f camera_direction = camera.getDirection();
2712 f32 camera_fov = camera.getFovMax();
2713 v3s16 camera_offset = camera.getOffset();
2715 bool camera_offset_changed = (camera_offset != old_camera_offset);
2717 if(!disable_camera_update){
2718 client.getEnv().getClientMap().updateCamera(camera_position,
2719 camera_direction, camera_fov, camera_offset);
2720 if (camera_offset_changed){
2721 client.updateCameraOffset(camera_offset);
2722 client.getEnv().updateCameraOffset(camera_offset);
2724 clouds->updateCameraOffset(camera_offset);
2728 // Update sound listener
2729 sound->updateListener(camera.getCameraNode()->getPosition()+intToFloat(camera_offset, BS),
2730 v3f(0,0,0), // velocity
2731 camera.getDirection(),
2732 camera.getCameraNode()->getUpVector());
2733 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2739 soundmaker.step(dtime);
2741 ClientMap &map = client.getEnv().getClientMap();
2742 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2743 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2747 Calculate what block is the crosshair pointing to
2750 //u32 t1 = device->getTimer()->getRealTime();
2752 f32 d = playeritem_def.range; // max. distance
2753 f32 d_hand = itemdef->get("").range;
2754 if(d < 0 && d_hand >= 0)
2758 core::line3d<f32> shootline(camera_position,
2759 camera_position + camera_direction * BS * (d+1));
2762 // prevent player pointing anything in front-view
2763 if (camera.getCameraMode() == CAMERA_MODE_THIRD_FRONT)
2764 shootline = core::line3d<f32>(0,0,0,0,0,0);
2766 #ifdef HAVE_TOUCHSCREENGUI
2767 if ((g_settings->getBool("touchtarget")) && (g_touchscreengui)) {
2768 shootline = g_touchscreengui->getShootline();
2769 shootline.start += intToFloat(camera_offset,BS);
2770 shootline.end += intToFloat(camera_offset,BS);
2774 ClientActiveObject *selected_object = NULL;
2776 PointedThing pointed = getPointedThing(
2778 &client, player_position, camera_direction,
2779 camera_position, shootline, d,
2780 playeritem_def.liquids_pointable, !ldown_for_dig,
2786 if(pointed != pointed_old)
2788 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2789 if (g_settings->getBool("enable_node_highlighting"))
2790 client.setHighlighted(pointed.node_undersurface, show_hud);
2795 - releasing left mouse button
2796 - pointing away from node
2800 if(input->getLeftReleased())
2802 infostream<<"Left button released"
2803 <<" (stopped digging)"<<std::endl;
2806 else if(pointed != pointed_old)
2808 if (pointed.type == POINTEDTHING_NODE
2809 && pointed_old.type == POINTEDTHING_NODE
2810 && pointed.node_undersurface == pointed_old.node_undersurface)
2812 // Still pointing to the same node,
2813 // but a different face. Don't reset.
2817 infostream<<"Pointing away from node"
2818 <<" (stopped digging)"<<std::endl;
2824 client.interact(1, pointed_old);
2825 client.setCrack(-1, v3s16(0,0,0));
2829 if(!digging && ldown_for_dig && !input->getLeftState())
2831 ldown_for_dig = false;
2834 bool left_punch = false;
2835 soundmaker.m_player_leftpunch_sound.name = "";
2837 if(input->getRightState())
2838 repeat_rightclick_timer += dtime;
2840 repeat_rightclick_timer = 0;
2842 if(playeritem_def.usable && input->getLeftState())
2844 if(input->getLeftClicked())
2845 client.interact(4, pointed);
2847 else if(pointed.type == POINTEDTHING_NODE)
2849 v3s16 nodepos = pointed.node_undersurface;
2850 v3s16 neighbourpos = pointed.node_abovesurface;
2853 Check information text of node
2856 ClientMap &map = client.getEnv().getClientMap();
2857 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2859 infotext = narrow_to_wide(meta->getString("infotext"));
2861 MapNode n = map.getNode(nodepos);
2862 if(nodedef->get(n).tiledef[0].name == "unknown_node.png"){
2863 infotext = L"Unknown node: ";
2864 infotext += narrow_to_wide(nodedef->get(n).name);
2872 if(nodig_delay_timer <= 0.0 && input->getLeftState()
2873 && client.checkPrivilege("interact"))
2877 infostream<<"Started digging"<<std::endl;
2878 client.interact(0, pointed);
2880 ldown_for_dig = true;
2882 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2884 // NOTE: Similar piece of code exists on the server side for
2886 // Get digging parameters
2887 DigParams params = getDigParams(nodedef->get(n).groups,
2888 &playeritem_toolcap);
2889 // If can't dig, try hand
2890 if(!params.diggable){
2891 const ItemDefinition &hand = itemdef->get("");
2892 const ToolCapabilities *tp = hand.tool_capabilities;
2894 params = getDigParams(nodedef->get(n).groups, tp);
2897 float dig_time_complete = 0.0;
2899 if(params.diggable == false)
2901 // I guess nobody will wait for this long
2902 dig_time_complete = 10000000.0;
2906 dig_time_complete = params.time;
2907 if (g_settings->getBool("enable_particles"))
2909 const ContentFeatures &features =
2910 client.getNodeDefManager()->get(n);
2911 addPunchingParticles
2912 (gamedef, smgr, player, client.getEnv(),
2913 nodepos, features.tiles);
2917 if(dig_time_complete >= 0.001)
2919 dig_index = (u16)((float)crack_animation_length
2920 * dig_time/dig_time_complete);
2922 // This is for torches
2925 dig_index = crack_animation_length;
2928 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2929 if(sound_dig.exists() && params.diggable){
2930 if(sound_dig.name == "__group"){
2931 if(params.main_group != ""){
2932 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2933 soundmaker.m_player_leftpunch_sound.name =
2934 std::string("default_dig_") +
2938 soundmaker.m_player_leftpunch_sound = sound_dig;
2942 // Don't show cracks if not diggable
2943 if(dig_time_complete >= 100000.0)
2946 else if(dig_index < crack_animation_length)
2948 //TimeTaker timer("client.setTempMod");
2949 //infostream<<"dig_index="<<dig_index<<std::endl;
2950 client.setCrack(dig_index, nodepos);
2954 infostream<<"Digging completed"<<std::endl;
2955 client.interact(2, pointed);
2956 client.setCrack(-1, v3s16(0,0,0));
2957 MapNode wasnode = map.getNode(nodepos);
2958 client.removeNode(nodepos);
2960 if (g_settings->getBool("enable_particles"))
2962 const ContentFeatures &features =
2963 client.getNodeDefManager()->get(wasnode);
2965 (gamedef, smgr, player, client.getEnv(),
2966 nodepos, features.tiles);
2972 nodig_delay_timer = dig_time_complete
2973 / (float)crack_animation_length;
2975 // We don't want a corresponding delay to
2976 // very time consuming nodes
2977 if(nodig_delay_timer > 0.3)
2978 nodig_delay_timer = 0.3;
2979 // We want a slight delay to very little
2980 // time consuming nodes
2981 float mindelay = 0.15;
2982 if(nodig_delay_timer < mindelay)
2983 nodig_delay_timer = mindelay;
2985 // Send event to trigger sound
2986 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2987 gamedef->event()->put(e);
2990 if(dig_time_complete < 100000.0)
2994 client.setCrack(-1, nodepos);
2997 camera.setDigging(0); // left click animation
3000 if((input->getRightClicked() ||
3001 repeat_rightclick_timer >=
3002 g_settings->getFloat("repeat_rightclick_time")) &&
3003 client.checkPrivilege("interact"))
3005 repeat_rightclick_timer = 0;
3006 infostream<<"Ground right-clicked"<<std::endl;
3008 if(meta && meta->getString("formspec") != "" && !random_input
3009 && !input->isKeyDown(getKeySetting("keymap_sneak")))
3011 infostream<<"Launching custom inventory view"<<std::endl;
3013 InventoryLocation inventoryloc;
3014 inventoryloc.setNodeMeta(nodepos);
3016 NodeMetadataFormSource* fs_src = new NodeMetadataFormSource(
3017 &client.getEnv().getClientMap(), nodepos);
3018 TextDest* txt_dst = new TextDestNodeMetadata(nodepos, &client);
3020 create_formspec_menu(¤t_formspec, &client, gamedef,
3021 tsrc, device, fs_src, txt_dst, &client);
3023 current_formspec->setFormSpec(meta->getString("formspec"), inventoryloc);
3025 // Otherwise report right click to server
3028 camera.setDigging(1); // right click animation (always shown for feedback)
3030 // If the wielded item has node placement prediction,
3032 bool placed = nodePlacementPrediction(client,
3034 nodepos, neighbourpos);
3038 client.interact(3, pointed);
3040 soundmaker.m_player_rightpunch_sound =
3041 playeritem_def.sound_place;
3043 soundmaker.m_player_rightpunch_sound =
3047 if (playeritem_def.node_placement_prediction == "" ||
3048 nodedef->get(map.getNode(nodepos)).rightclickable)
3049 client.interact(3, pointed); // Report to server
3053 else if(pointed.type == POINTEDTHING_OBJECT)
3055 infotext = narrow_to_wide(selected_object->infoText());
3057 if(infotext == L"" && show_debug){
3058 infotext = narrow_to_wide(selected_object->debugInfoText());
3061 //if(input->getLeftClicked())
3062 if(input->getLeftState())
3064 bool do_punch = false;
3065 bool do_punch_damage = false;
3066 if(object_hit_delay_timer <= 0.0){
3068 do_punch_damage = true;
3069 object_hit_delay_timer = object_hit_delay;
3071 if(input->getLeftClicked()){
3075 infostream<<"Left-clicked object"<<std::endl;
3078 if(do_punch_damage){
3079 // Report direct punch
3080 v3f objpos = selected_object->getPosition();
3081 v3f dir = (objpos - player_position).normalize();
3083 bool disable_send = selected_object->directReportPunch(
3084 dir, &playeritem, time_from_last_punch);
3085 time_from_last_punch = 0;
3087 client.interact(0, pointed);
3090 else if(input->getRightClicked())
3092 infostream<<"Right-clicked object"<<std::endl;
3093 client.interact(3, pointed); // place
3096 else if(input->getLeftState())
3098 // When button is held down in air, show continuous animation
3102 pointed_old = pointed;
3104 if(left_punch || input->getLeftClicked())
3106 camera.setDigging(0); // left click animation
3109 input->resetLeftClicked();
3110 input->resetRightClicked();
3112 input->resetLeftReleased();
3113 input->resetRightReleased();
3116 Calculate stuff for drawing
3123 if(draw_control.range_all)
3124 fog_range = 100000*BS;
3126 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
3127 fog_range = MYMIN(fog_range, (draw_control.farthest_drawn+20)*BS);
3132 Calculate general brightness
3134 u32 daynight_ratio = client.getEnv().getDayNightRatio();
3135 float time_brightness = decode_light_f((float)daynight_ratio/1000.0);
3136 float direct_brightness = 0;
3137 bool sunlight_seen = false;
3138 if(g_settings->getBool("free_move")){
3139 direct_brightness = time_brightness;
3140 sunlight_seen = true;
3142 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
3143 float old_brightness = sky->getBrightness();
3144 direct_brightness = (float)client.getEnv().getClientMap()
3145 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
3146 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
3150 time_of_day = client.getEnv().getTimeOfDayF();
3152 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
3153 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
3154 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
3155 time_of_day_smooth = time_of_day;
3157 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
3158 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3159 + (time_of_day+1.0) * todsm;
3161 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
3162 + time_of_day * todsm;
3164 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
3165 sunlight_seen,camera.getCameraMode(), player->getYaw(),
3166 player->getPitch());
3168 video::SColor bgcolor = sky->getBgColor();
3169 video::SColor skycolor = sky->getSkyColor();
3175 if(sky->getCloudsVisible()){
3176 clouds->setVisible(true);
3177 clouds->step(dtime);
3178 clouds->update(v2f(player_position.X, player_position.Z),
3179 sky->getCloudColor());
3181 clouds->setVisible(false);
3189 allparticles_step(dtime);
3190 allparticlespawners_step(dtime, client.getEnv());
3196 if(g_settings->getBool("enable_fog") && !force_fog_off)
3200 video::EFT_FOG_LINEAR,
3212 video::EFT_FOG_LINEAR,
3222 Update gui stuff (0ms)
3225 //TimeTaker guiupdatetimer("Gui updating");
3229 static float drawtime_avg = 0;
3230 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
3231 /*static float beginscenetime_avg = 0;
3232 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
3233 static float scenetime_avg = 0;
3234 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
3235 static float endscenetime_avg = 0;
3236 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
3238 u16 fps = (1.0/dtime_avg1);
3240 std::ostringstream os(std::ios_base::binary);
3242 <<"Minetest "<<minetest_version_hash
3244 <<" (R: range_all="<<draw_control.range_all<<")"
3245 <<std::setprecision(0)
3246 <<" drawtime = "<<drawtime_avg
3247 <<std::setprecision(1)
3248 <<", dtime_jitter = "
3249 <<(dtime_jitter1_max_fraction * 100.0)<<" %"
3250 <<std::setprecision(1)
3251 <<", v_range = "<<draw_control.wanted_range
3252 <<std::setprecision(3)
3253 <<", RTT = "<<client.getRTT();
3254 guitext->setText(narrow_to_wide(os.str()).c_str());
3255 guitext->setVisible(true);
3257 else if(show_hud || show_chat)
3259 std::ostringstream os(std::ios_base::binary);
3260 os<<"Minetest "<<minetest_version_hash;
3261 guitext->setText(narrow_to_wide(os.str()).c_str());
3262 guitext->setVisible(true);
3266 guitext->setVisible(false);
3269 if (guitext->isVisible())
3271 core::rect<s32> rect(
3277 guitext->setRelativePosition(rect);
3282 std::ostringstream os(std::ios_base::binary);
3283 os<<std::setprecision(1)<<std::fixed
3284 <<"(" <<(player_position.X/BS)
3285 <<", "<<(player_position.Y/BS)
3286 <<", "<<(player_position.Z/BS)
3287 <<") (yaw="<<(wrapDegrees_0_360(camera_yaw))
3288 <<") (seed = "<<((u64)client.getMapSeed())
3290 guitext2->setText(narrow_to_wide(os.str()).c_str());
3291 guitext2->setVisible(true);
3293 core::rect<s32> rect(
3297 5 + (text_height * 2)
3299 guitext2->setRelativePosition(rect);
3303 guitext2->setVisible(false);
3307 guitext_info->setText(infotext.c_str());
3308 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
3312 float statustext_time_max = 1.5;
3313 if(!statustext.empty())
3315 statustext_time += dtime;
3316 if(statustext_time >= statustext_time_max)
3319 statustext_time = 0;
3322 guitext_status->setText(statustext.c_str());
3323 guitext_status->setVisible(!statustext.empty());
3325 if(!statustext.empty())
3327 s32 status_y = screensize.Y - 130;
3328 core::rect<s32> rect(
3330 status_y - guitext_status->getTextHeight(),
3331 10 + guitext_status->getTextWidth(),
3334 guitext_status->setRelativePosition(rect);
3337 video::SColor initial_color(255,0,0,0);
3338 if(guienv->getSkin())
3339 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
3340 video::SColor final_color = initial_color;
3341 final_color.setAlpha(0);
3342 video::SColor fade_color =
3343 initial_color.getInterpolated_quadratic(
3346 pow(statustext_time / (float)statustext_time_max, 2.0f));
3347 guitext_status->setOverrideColor(fade_color);
3348 guitext_status->enableOverrideColor(true);
3353 Get chat messages from client
3355 updateChat(client, dtime, show_debug, screensize, show_chat,
3356 show_profiler, chat_backend, guitext_chat, font);
3362 if(client.getPlayerItem() != new_playeritem)
3364 client.selectPlayerItem(new_playeritem);
3366 if(client.getLocalInventoryUpdated())
3368 //infostream<<"Updating local inventory"<<std::endl;
3369 client.getLocalInventory(local_inventory);
3371 update_wielded_item_trigger = true;
3373 if(update_wielded_item_trigger)
3375 update_wielded_item_trigger = false;
3376 // Update wielded tool
3377 InventoryList *mlist = local_inventory.getList("main");
3379 if((mlist != NULL) && (client.getPlayerItem() < mlist->getSize()))
3380 item = mlist->getItem(client.getPlayerItem());
3381 camera.wield(item, client.getPlayerItem());
3385 Update block draw list every 200ms or when camera direction has
3388 update_draw_list_timer += dtime;
3389 if(update_draw_list_timer >= 0.2 ||
3390 update_draw_list_last_cam_dir.getDistanceFrom(camera_direction) > 0.2 ||
3391 camera_offset_changed){
3392 update_draw_list_timer = 0;
3393 client.getEnv().getClientMap().updateDrawList(driver);
3394 update_draw_list_last_cam_dir = camera_direction;
3398 make sure menu is on top
3400 if ((!noMenuActive()) && (current_formspec)) {
3401 guiroot->bringToFront(current_formspec);
3407 TimeTaker tt_draw("mainloop: draw");
3409 TimeTaker timer("beginScene");
3410 driver->beginScene(true, true, skycolor);
3411 beginscenetime = timer.stop(true);
3415 draw_scene(driver, smgr, camera, client, player, hud, guienv,
3416 hilightboxes, screensize, skycolor, show_hud);
3421 if(show_profiler_graph)
3423 graph.draw(10, screensize.Y - 10, driver, font);
3429 if(damage_flash > 0.0)
3431 video::SColor color(std::min(damage_flash, 180.0f),180,0,0);
3432 driver->draw2DRectangle(color,
3433 core::rect<s32>(0,0,screensize.X,screensize.Y),
3436 damage_flash -= 100.0*dtime;
3442 if(player->hurt_tilt_timer > 0.0)
3444 player->hurt_tilt_timer -= dtime*5;
3445 if(player->hurt_tilt_timer < 0)
3446 player->hurt_tilt_strength = 0;
3453 TimeTaker timer("endScene");
3455 endscenetime = timer.stop(true);
3458 drawtime = tt_draw.stop(true);
3459 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
3466 Log times and stuff for visualization
3468 Profiler::GraphValues values;
3469 g_profiler->graphGet(values);
3478 if (gui_chat_console)
3479 gui_chat_console->drop();
3485 while (g_menumgr.menuCount() > 0)
3487 g_menumgr.m_stack.front()->setVisible(false);
3488 g_menumgr.deletingMenu(g_menumgr.m_stack.front());
3491 Draw a "shutting down" screen, which will be shown while the map
3492 generator and other stuff quits
3495 wchar_t* text = wgettext("Shutting down stuff...");
3496 draw_load_screen(text, device, guienv, font, 0, -1, false);
3500 chat_backend.addMessage(L"", L"# Disconnected.");
3501 chat_backend.addMessage(L"", L"");
3505 //force answer all texture and shader jobs (TODO return empty values)
3507 while(!client.isShutdown()) {
3508 tsrc->processQueue();
3509 shsrc->processQueue();
3513 // Client scope (client is destructed before destructing *def and tsrc)
3516 catch(SerializationError &e)
3518 error_message = L"A serialization error occurred:\n"
3519 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
3520 L" running a different version of Minetest.";
3521 errorstream<<wide_to_narrow(error_message)<<std::endl;
3523 catch(ServerError &e) {
3524 error_message = narrow_to_wide(e.what());
3525 errorstream << "ServerError: " << e.what() << std::endl;
3527 catch(ModError &e) {
3528 errorstream << "ModError: " << e.what() << std::endl;
3529 error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
3537 //has to be deleted first to stop all server threads
3545 //extended resource accounting
3546 infostream << "Irrlicht resources after cleanup:" << std::endl;
3547 infostream << "\tRemaining meshes : "
3548 << device->getSceneManager()->getMeshCache()->getMeshCount() << std::endl;
3549 infostream << "\tRemaining textures : "
3550 << driver->getTextureCount() << std::endl;
3551 for (unsigned int i = 0; i < driver->getTextureCount(); i++ ) {
3552 irr::video::ITexture* texture = driver->getTextureByIndex(i);
3553 infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str()
3556 clearTextureNameCache();
3557 infostream << "\tRemaining materials: "
3558 << driver-> getMaterialRendererCount ()
3559 << " (note: irrlicht doesn't support removing renderers)"<< std::endl;