3 Copyright (C) 2010-2011 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 "common_irrlicht.h"
22 #include <IGUICheckBox.h>
23 #include <IGUIEditBox.h>
24 #include <IGUIButton.h>
25 #include <IGUIStaticText.h>
29 #include "guiPauseMenu.h"
30 #include "guiPasswordChange.h"
31 #include "guiInventoryMenu.h"
32 #include "guiTextInputMenu.h"
33 #include "guiDeathScreen.h"
35 #include "guiChatConsole.h"
43 #include "mainmenumanager.h"
47 // Needed for determining pointing to nodes
49 #include "nodemetadata.h"
50 #include "main.h" // For g_settings
52 #include "tile.h" // For TextureSource
53 #include "logoutputbuffer.h"
55 #include "quicktune_shortcutter.h"
56 #include "clientmap.h"
60 #include "sound_openal.h"
62 #include "event_manager.h"
69 struct TextDestChat : public TextDest
71 TextDestChat(Client *client)
75 void gotText(std::wstring text)
77 m_client->typeChatMessage(text);
83 struct TextDestNodeMetadata : public TextDest
85 TextDestNodeMetadata(v3s16 p, Client *client)
90 void gotText(std::wstring text)
92 std::string ntext = wide_to_narrow(text);
93 infostream<<"Changing text of a sign node: "
95 std::map<std::string, std::string> fields;
96 fields["text"] = ntext;
97 m_client->sendNodemetaFields(m_p, "", fields);
104 /* Respawn menu callback */
106 class MainRespawnInitiator: public IRespawnInitiator
109 MainRespawnInitiator(bool *active, Client *client):
110 m_active(active), m_client(client)
117 m_client->sendRespawn();
124 /* Form update callback */
126 class NodeMetadataFormSource: public IFormSource
129 NodeMetadataFormSource(ClientMap *map, v3s16 p):
134 std::string getForm()
136 NodeMetadata *meta = m_map->getNodeMetadata(m_p);
139 return meta->getString("formspec");
149 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
151 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
152 Inventory *inventory, s32 halfheartcount, u16 playeritem)
154 InventoryList *mainlist = inventory->getList("main");
157 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
161 s32 padding = imgsize/12;
162 //s32 height = imgsize + padding*2;
163 s32 width = itemcount*(imgsize+padding*2);
165 // Position of upper left corner of bar
166 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
168 // Draw background color
169 /*core::rect<s32> barrect(0,0,width,height);
171 video::SColor bgcolor(255,128,128,128);
172 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
174 core::rect<s32> imgrect(0,0,imgsize,imgsize);
176 for(s32 i=0; i<itemcount; i++)
178 const ItemStack &item = mainlist->getItem(i);
180 core::rect<s32> rect = imgrect + pos
181 + v2s32(padding+i*(imgsize+padding*2), padding);
185 video::SColor c_outside(255,255,0,0);
186 //video::SColor c_outside(255,0,0,0);
187 //video::SColor c_inside(255,192,192,192);
188 s32 x1 = rect.UpperLeftCorner.X;
189 s32 y1 = rect.UpperLeftCorner.Y;
190 s32 x2 = rect.LowerRightCorner.X;
191 s32 y2 = rect.LowerRightCorner.Y;
192 // Black base borders
193 driver->draw2DRectangle(c_outside,
195 v2s32(x1 - padding, y1 - padding),
196 v2s32(x2 + padding, y1)
198 driver->draw2DRectangle(c_outside,
200 v2s32(x1 - padding, y2),
201 v2s32(x2 + padding, y2 + padding)
203 driver->draw2DRectangle(c_outside,
205 v2s32(x1 - padding, y1),
208 driver->draw2DRectangle(c_outside,
211 v2s32(x2 + padding, y2)
213 /*// Light inside borders
214 driver->draw2DRectangle(c_inside,
216 v2s32(x1 - padding/2, y1 - padding/2),
217 v2s32(x2 + padding/2, y1)
219 driver->draw2DRectangle(c_inside,
221 v2s32(x1 - padding/2, y2),
222 v2s32(x2 + padding/2, y2 + padding/2)
224 driver->draw2DRectangle(c_inside,
226 v2s32(x1 - padding/2, y1),
229 driver->draw2DRectangle(c_inside,
232 v2s32(x2 + padding/2, y2)
237 video::SColor bgcolor2(128,0,0,0);
238 driver->draw2DRectangle(bgcolor2, rect, NULL);
239 drawItemStack(driver, font, item, rect, NULL, gamedef);
245 video::ITexture *heart_texture =
246 gamedef->getTextureSource()->getTextureRaw("heart.png");
249 v2s32 p = pos + v2s32(0, -20);
250 for(s32 i=0; i<halfheartcount/2; i++)
252 const video::SColor color(255,255,255,255);
253 const video::SColor colors[] = {color,color,color,color};
254 core::rect<s32> rect(0,0,16,16);
256 driver->draw2DImage(heart_texture, rect,
257 core::rect<s32>(core::position2d<s32>(0,0),
258 core::dimension2di(heart_texture->getOriginalSize())),
262 if(halfheartcount % 2 == 1)
264 const video::SColor color(255,255,255,255);
265 const video::SColor colors[] = {color,color,color,color};
266 core::rect<s32> rect(0,0,16/2,16);
268 core::dimension2di srcd(heart_texture->getOriginalSize());
270 driver->draw2DImage(heart_texture, rect,
271 core::rect<s32>(core::position2d<s32>(0,0), srcd),
279 Check if a node is pointable
281 inline bool isPointableNode(const MapNode& n,
282 Client *client, bool liquids_pointable)
284 const ContentFeatures &features = client->getNodeDefManager()->get(n);
285 return features.pointable ||
286 (liquids_pointable && features.isLiquid());
290 Find what the player is pointing at
292 PointedThing getPointedThing(Client *client, v3f player_position,
293 v3f camera_direction, v3f camera_position,
294 core::line3d<f32> shootline, f32 d,
295 bool liquids_pointable,
296 bool look_for_object,
297 core::aabbox3d<f32> &hilightbox,
298 bool &should_show_hilightbox,
299 ClientActiveObject *&selected_object)
303 hilightbox = core::aabbox3d<f32>(0,0,0,0,0,0);
304 should_show_hilightbox = false;
305 selected_object = NULL;
307 INodeDefManager *nodedef = client->getNodeDefManager();
308 ClientMap &map = client->getEnv().getClientMap();
310 // First try to find a pointed at active object
313 selected_object = client->getSelectedActiveObject(d*BS,
314 camera_position, shootline);
316 if(selected_object != NULL)
318 core::aabbox3d<f32> *selection_box
319 = selected_object->getSelectionBox();
320 // Box should exist because object was returned in the
322 assert(selection_box);
324 v3f pos = selected_object->getPosition();
326 hilightbox = core::aabbox3d<f32>(
327 selection_box->MinEdge + pos,
328 selection_box->MaxEdge + pos
331 should_show_hilightbox = selected_object->doShowSelectionBox();
333 result.type = POINTEDTHING_OBJECT;
334 result.object_id = selected_object->getId();
338 // That didn't work, try to find a pointed at node
340 f32 mindistance = BS * 1001;
342 v3s16 pos_i = floatToInt(player_position, BS);
344 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
348 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
349 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
350 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
351 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
352 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
353 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
355 for(s16 y = ystart; y <= yend; y++)
356 for(s16 z = zstart; z <= zend; z++)
357 for(s16 x = xstart; x <= xend; x++)
362 n = map.getNode(v3s16(x,y,z));
364 catch(InvalidPositionException &e)
368 if(!isPointableNode(n, client, liquids_pointable))
372 v3f npf = intToFloat(np, BS);
377 v3s16(0,0,1), // back
379 v3s16(1,0,0), // right
380 v3s16(0,0,-1), // front
381 v3s16(0,-1,0), // bottom
382 v3s16(-1,0,0), // left
385 const ContentFeatures &f = nodedef->get(n);
387 if(f.selection_box.type == NODEBOX_FIXED)
389 core::aabbox3d<f32> box = f.selection_box.fixed;
393 v3s16 facedirs[6] = {
402 core::aabbox3d<f32> faceboxes[6] = {
405 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
406 box.MinEdge.X+d, box.MaxEdge.Y, box.MaxEdge.Z
410 box.MaxEdge.X-d, box.MinEdge.Y, box.MinEdge.Z,
411 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
415 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
416 box.MaxEdge.X, box.MinEdge.Y+d, box.MaxEdge.Z
420 box.MinEdge.X, box.MaxEdge.Y-d, box.MinEdge.Z,
421 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
425 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
426 box.MaxEdge.X, box.MaxEdge.Y, box.MinEdge.Z+d
430 box.MinEdge.X, box.MinEdge.Y, box.MaxEdge.Z-d,
431 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
435 for(u16 i=0; i<6; i++)
437 v3f facedir_f(facedirs[i].X, facedirs[i].Y, facedirs[i].Z);
438 v3f centerpoint = npf + facedir_f * BS/2;
439 f32 distance = (centerpoint - camera_position).getLength();
440 if(distance >= mindistance)
442 if(!faceboxes[i].intersectsWithLine(shootline))
444 result.type = POINTEDTHING_NODE;
445 result.node_undersurface = np;
446 result.node_abovesurface = np+facedirs[i];
447 mindistance = distance;
449 should_show_hilightbox = true;
452 else if(f.selection_box.type == NODEBOX_WALLMOUNTED)
454 v3s16 dir = n.getWallMountedDir(nodedef);
455 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
456 dir_f *= BS/2 - BS/6 - BS/20;
457 v3f cpf = npf + dir_f;
458 f32 distance = (cpf - camera_position).getLength();
460 core::aabbox3d<f32> box;
463 if(dir == v3s16(0,1,0)){
464 box = f.selection_box.wall_top;
467 else if(dir == v3s16(0,-1,0)){
468 box = f.selection_box.wall_bottom;
474 f.selection_box.wall_side.MinEdge,
475 f.selection_box.wall_side.MaxEdge
478 for(s32 i=0; i<2; i++)
480 if(dir == v3s16(-1,0,0))
481 vertices[i].rotateXZBy(0);
482 if(dir == v3s16(1,0,0))
483 vertices[i].rotateXZBy(180);
484 if(dir == v3s16(0,0,-1))
485 vertices[i].rotateXZBy(90);
486 if(dir == v3s16(0,0,1))
487 vertices[i].rotateXZBy(-90);
490 box = core::aabbox3d<f32>(vertices[0]);
491 box.addInternalPoint(vertices[1]);
497 if(distance < mindistance)
499 if(box.intersectsWithLine(shootline))
501 result.type = POINTEDTHING_NODE;
502 result.node_undersurface = np;
503 result.node_abovesurface = np;
504 mindistance = distance;
506 should_show_hilightbox = true;
510 else // NODEBOX_REGULAR
512 for(u16 i=0; i<6; i++)
514 v3f dir_f = v3f(dirs[i].X,
515 dirs[i].Y, dirs[i].Z);
516 v3f centerpoint = npf + dir_f * BS/2;
518 (centerpoint - camera_position).getLength();
520 if(distance < mindistance)
522 core::CMatrix4<f32> m;
523 m.buildRotateFromTo(v3f(0,0,1), dir_f);
525 // This is the back face
527 v3f(BS/2, BS/2, BS/2),
528 v3f(-BS/2, -BS/2, BS/2+d)
531 for(u16 j=0; j<2; j++)
533 m.rotateVect(corners[j]);
537 core::aabbox3d<f32> facebox(corners[0]);
538 facebox.addInternalPoint(corners[1]);
540 if(facebox.intersectsWithLine(shootline))
542 result.type = POINTEDTHING_NODE;
543 result.node_undersurface = np;
544 result.node_abovesurface = np + dirs[i];
545 mindistance = distance;
547 //hilightbox = facebox;
549 const float d = 0.502;
550 core::aabbox3d<f32> nodebox
551 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
552 v3f nodepos_f = intToFloat(np, BS);
553 nodebox.MinEdge += nodepos_f;
554 nodebox.MaxEdge += nodepos_f;
555 hilightbox = nodebox;
556 should_show_hilightbox = true;
558 } // if distance < mindistance
567 Draws a screen with a single text on it.
568 Text will be removed when the screen is drawn the next time.
570 /*gui::IGUIStaticText **/
571 void draw_load_screen(const std::wstring &text,
572 video::IVideoDriver* driver, gui::IGUIFont* font)
574 v2u32 screensize = driver->getScreenSize();
575 const wchar_t *loadingtext = text.c_str();
576 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
577 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
578 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
579 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
581 gui::IGUIStaticText *guitext = guienv->addStaticText(
582 loadingtext, textrect, false, false);
583 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
585 driver->beginScene(true, true, video::SColor(255,0,0,0));
594 /* Profiler display */
596 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
597 gui::IGUIFont *font, u32 text_height,
598 u32 show_profiler, u32 show_profiler_max)
600 if(show_profiler == 0)
602 guitext_profiler->setVisible(false);
607 std::ostringstream os(std::ios_base::binary);
608 g_profiler->printPage(os, show_profiler, show_profiler_max);
609 std::wstring text = narrow_to_wide(os.str());
610 guitext_profiler->setText(text.c_str());
611 guitext_profiler->setVisible(true);
613 s32 w = font->getDimension(text.c_str()).Width;
616 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
617 8+(text_height+5)*2 +
618 font->getDimension(text.c_str()).Height);
619 guitext_profiler->setRelativePosition(rect);
620 guitext_profiler->setVisible(true);
628 Profiler::GraphValues values;
634 Meta(float initial=0, video::SColor color=
635 video::SColor(255,255,255,255)):
641 std::list<Piece> m_log;
649 void put(const Profiler::GraphValues &values)
652 piece.values = values;
653 m_log.push_back(piece);
654 while(m_log.size() > m_log_max_size)
655 m_log.erase(m_log.begin());
658 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
659 gui::IGUIFont* font) const
661 std::map<std::string, Meta> m_meta;
662 for(std::list<Piece>::const_iterator k = m_log.begin();
663 k != m_log.end(); k++)
665 const Piece &piece = *k;
666 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
667 i != piece.values.end(); i++){
668 const std::string &id = i->first;
669 const float &value = i->second;
670 std::map<std::string, Meta>::iterator j =
672 if(j == m_meta.end()){
673 m_meta[id] = Meta(value);
676 if(value < j->second.min)
677 j->second.min = value;
678 if(value > j->second.max)
679 j->second.max = value;
684 static const video::SColor usable_colors[] = {
685 video::SColor(255,255,100,100),
686 video::SColor(255,90,225,90),
687 video::SColor(255,100,100,255),
688 video::SColor(255,255,150,50),
689 video::SColor(255,220,220,100)
691 static const u32 usable_colors_count =
692 sizeof(usable_colors) / sizeof(*usable_colors);
693 u32 next_color_i = 0;
694 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
695 i != m_meta.end(); i++){
696 Meta &meta = i->second;
697 video::SColor color(255,200,200,200);
698 if(next_color_i < usable_colors_count)
699 color = usable_colors[next_color_i++];
704 s32 textx = x_left + m_log_max_size + 15;
705 s32 textx2 = textx + 200 - 15;
709 u32 num_graphs = m_meta.size();
710 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
712 video::SColor bgcolor(120,0,0,0);
713 driver->draw2DRectangle(bgcolor, rect, NULL);
717 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
718 i != m_meta.end(); i++){
719 const std::string &id = i->first;
720 const Meta &meta = i->second;
722 s32 y = y_bottom - meta_i * 50;
723 float show_min = meta.min;
724 float show_max = meta.max;
725 if(show_min >= -0.0001 && show_max >= -0.0001){
726 if(show_min <= show_max * 0.5)
731 snprintf(buf, 10, "%.3g", show_max);
732 font->draw(narrow_to_wide(buf).c_str(),
733 core::rect<s32>(textx, y - graphh,
734 textx2, y - graphh + texth),
736 snprintf(buf, 10, "%.3g", show_min);
737 font->draw(narrow_to_wide(buf).c_str(),
738 core::rect<s32>(textx, y - texth,
741 font->draw(narrow_to_wide(id).c_str(),
742 core::rect<s32>(textx, y - graphh/2 - texth/2,
743 textx2, y - graphh/2 + texth/2),
746 s32 graph1h = graphh;
747 bool relativegraph = (show_min != 0 && show_min != show_max);
748 float lastscaledvalue = 0.0;
749 bool lastscaledvalue_exists = false;
750 for(std::list<Piece>::const_iterator j = m_log.begin();
751 j != m_log.end(); j++)
753 const Piece &piece = *j;
755 bool value_exists = false;
756 Profiler::GraphValues::const_iterator k =
757 piece.values.find(id);
758 if(k != piece.values.end()){
764 lastscaledvalue_exists = false;
767 float scaledvalue = 1.0;
768 if(show_max != show_min)
769 scaledvalue = (value - show_min) / (show_max - show_min);
770 if(scaledvalue == 1.0 && value == 0){
772 lastscaledvalue_exists = false;
776 if(lastscaledvalue_exists){
777 s32 ivalue1 = lastscaledvalue * graph1h;
778 s32 ivalue2 = scaledvalue * graph1h;
779 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
780 v2s32(x, graph1y - ivalue2), meta.color);
782 lastscaledvalue = scaledvalue;
783 lastscaledvalue_exists = true;
785 s32 ivalue = scaledvalue * graph1h;
786 driver->draw2DLine(v2s32(x, graph1y),
787 v2s32(x, graph1y - ivalue), meta.color);
796 class NodeDugEvent: public MtEvent
802 NodeDugEvent(v3s16 p, MapNode n):
806 const char* getType() const
812 ISoundManager *m_sound;
813 INodeDefManager *m_ndef;
815 float m_player_step_timer;
817 SimpleSoundSpec m_player_step_sound;
818 SimpleSoundSpec m_player_leftpunch_sound;
819 SimpleSoundSpec m_player_rightpunch_sound;
821 SoundMaker(ISoundManager *sound, INodeDefManager *ndef):
824 m_player_step_timer(0)
828 void playPlayerStep()
830 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
831 m_player_step_timer = 0.03;
832 m_sound->playSound(m_player_step_sound, false);
836 static void viewBobbingStep(MtEvent *e, void *data)
838 SoundMaker *sm = (SoundMaker*)data;
839 sm->playPlayerStep();
842 static void playerRegainGround(MtEvent *e, void *data)
844 SoundMaker *sm = (SoundMaker*)data;
845 sm->playPlayerStep();
848 static void playerJump(MtEvent *e, void *data)
850 //SoundMaker *sm = (SoundMaker*)data;
853 static void cameraPunchLeft(MtEvent *e, void *data)
855 SoundMaker *sm = (SoundMaker*)data;
856 sm->m_sound->playSound(sm->m_player_leftpunch_sound, false);
859 static void cameraPunchRight(MtEvent *e, void *data)
861 SoundMaker *sm = (SoundMaker*)data;
862 sm->m_sound->playSound(sm->m_player_rightpunch_sound, false);
865 static void nodeDug(MtEvent *e, void *data)
867 SoundMaker *sm = (SoundMaker*)data;
868 NodeDugEvent *nde = (NodeDugEvent*)e;
869 sm->m_sound->playSound(sm->m_ndef->get(nde->n).sound_dug, false);
872 void registerReceiver(MtEventManager *mgr)
874 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
875 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
876 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
877 mgr->reg("CameraPunchLeft", SoundMaker::cameraPunchLeft, this);
878 mgr->reg("CameraPunchRight", SoundMaker::cameraPunchRight, this);
879 mgr->reg("NodeDug", SoundMaker::nodeDug, this);
882 void step(float dtime)
884 m_player_step_timer -= dtime;
888 // Locally stored sounds don't need to be preloaded because of this
889 class GameOnDemandSoundFetcher: public OnDemandSoundFetcher
891 std::set<std::string> m_fetched;
894 void fetchSounds(const std::string &name,
895 std::set<std::string> &dst_paths,
896 std::set<std::string> &dst_datas)
898 if(m_fetched.count(name))
900 m_fetched.insert(name);
901 std::string base = porting::path_share + DIR_DELIM + "testsounds";
902 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
903 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
904 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
905 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
906 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
907 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
908 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
909 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
910 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
911 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
912 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
920 IrrlichtDevice *device,
923 std::string playername,
924 std::string password,
925 std::string address, // If "", local server is used
927 std::wstring &error_message,
928 std::string configpath,
929 ChatBackend &chat_backend,
930 const SubgameSpec &gamespec, // Used for local game,
931 bool simple_singleplayer_mode
934 video::IVideoDriver* driver = device->getVideoDriver();
935 scene::ISceneManager* smgr = device->getSceneManager();
937 // Calculate text height using the font
938 u32 text_height = font->getDimension(L"Random test string").Height;
940 v2u32 screensize(0,0);
941 v2u32 last_screensize(0,0);
942 screensize = driver->getScreenSize();
944 const s32 hotbar_itemcount = 8;
945 //const s32 hotbar_imagesize = 36;
946 //const s32 hotbar_imagesize = 64;
947 s32 hotbar_imagesize = 48;
950 Draw "Loading" screen
953 draw_load_screen(L"Loading...", driver, font);
955 // Create texture source
956 IWritableTextureSource *tsrc = createTextureSource(device);
958 // These will be filled by data received from the server
959 // Create item definition manager
960 IWritableItemDefManager *itemdef = createItemDefManager();
961 // Create node definition manager
962 IWritableNodeDefManager *nodedef = createNodeDefManager();
964 // Sound fetcher (useful when testing)
965 GameOnDemandSoundFetcher soundfetcher;
968 ISoundManager *sound = NULL;
969 bool sound_is_dummy = false;
971 if(g_settings->getBool("enable_sound")){
972 infostream<<"Attempting to use OpenAL audio"<<std::endl;
973 sound = createOpenALSoundManager(&soundfetcher);
975 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
977 infostream<<"Sound disabled."<<std::endl;
981 infostream<<"Using dummy audio."<<std::endl;
982 sound = &dummySoundManager;
983 sound_is_dummy = true;
987 EventManager eventmgr;
990 SoundMaker soundmaker(sound, nodedef);
991 soundmaker.registerReceiver(&eventmgr);
993 // Add chat log output for errors to be shown in chat
994 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
996 // Create UI for modifying quicktune values
997 QuicktuneShortcutter quicktune;
1001 SharedPtr will delete it when it goes out of scope.
1003 SharedPtr<Server> server;
1005 draw_load_screen(L"Creating server...", driver, font);
1006 infostream<<"Creating server"<<std::endl;
1007 server = new Server(map_dir, configpath, gamespec,
1008 simple_singleplayer_mode);
1009 server->start(port);
1013 do{ // Client scope (breakable do-while(0))
1019 draw_load_screen(L"Creating client...", driver, font);
1020 infostream<<"Creating client"<<std::endl;
1022 MapDrawControl draw_control;
1024 Client client(device, playername.c_str(), password, draw_control,
1025 tsrc, itemdef, nodedef, sound, &eventmgr);
1027 // Client acts as our GameDef
1028 IGameDef *gamedef = &client;
1030 draw_load_screen(L"Resolving address...", driver, font);
1031 Address connect_address(0,0,0,0, port);
1034 //connect_address.Resolve("localhost");
1035 connect_address.setAddress(127,0,0,1);
1037 connect_address.Resolve(address.c_str());
1039 catch(ResolveError &e)
1041 error_message = L"Couldn't resolve address";
1042 errorstream<<wide_to_narrow(error_message)<<std::endl;
1043 // Break out of client scope
1048 Attempt to connect to the server
1051 infostream<<"Connecting to server at ";
1052 connect_address.print(&infostream);
1053 infostream<<std::endl;
1054 client.connect(connect_address);
1057 Wait for server to accept connection
1059 bool could_connect = false;
1060 bool connect_aborted = false;
1062 float frametime = 0.033;
1063 float time_counter = 0.0;
1065 while(device->run())
1067 // Update client and server
1068 client.step(frametime);
1070 server->step(frametime);
1073 if(client.connectedAndInitialized()){
1074 could_connect = true;
1078 if(client.accessDenied()){
1079 error_message = L"Access denied. Reason: "
1080 +client.accessDeniedReason();
1081 errorstream<<wide_to_narrow(error_message)<<std::endl;
1084 if(input->wasKeyDown(EscapeKey)){
1085 connect_aborted = true;
1086 infostream<<"Connect aborted [Escape]"<<std::endl;
1091 std::wostringstream ss;
1092 ss<<L"Connecting to server... (press Escape to cancel)\n";
1093 std::wstring animation = L"/-\\|";
1094 ss<<animation[(int)(time_counter/0.2)%4];
1095 draw_load_screen(ss.str(), driver, font);
1098 sleep_ms(1000*frametime);
1099 time_counter += frametime;
1102 catch(con::PeerNotFoundException &e)
1106 Handle failure to connect
1109 if(error_message == L"" && !connect_aborted){
1110 error_message = L"Connection failed";
1111 errorstream<<wide_to_narrow(error_message)<<std::endl;
1113 // Break out of client scope
1118 Wait until content has been received
1120 bool got_content = false;
1121 bool content_aborted = false;
1123 float frametime = 0.033;
1124 float time_counter = 0.0;
1126 while(device->run())
1128 // Update client and server
1129 client.step(frametime);
1131 server->step(frametime);
1134 if(client.texturesReceived() &&
1135 client.itemdefReceived() &&
1136 client.nodedefReceived()){
1141 if(!client.connectedAndInitialized()){
1142 error_message = L"Client disconnected";
1143 errorstream<<wide_to_narrow(error_message)<<std::endl;
1146 if(input->wasKeyDown(EscapeKey)){
1147 content_aborted = true;
1148 infostream<<"Connect aborted [Escape]"<<std::endl;
1153 std::wostringstream ss;
1154 ss<<L"Waiting content... (press Escape to cancel)\n";
1156 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1157 ss<<L" Item definitions\n";
1158 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1159 ss<<L" Node definitions\n";
1160 ss<<L"["<<(int)(client.mediaReceiveProgress()*100+0.5)<<L"%] ";
1163 draw_load_screen(ss.str(), driver, font);
1166 sleep_ms(1000*frametime);
1167 time_counter += frametime;
1172 if(error_message == L"" && !content_aborted){
1173 error_message = L"Something failed";
1174 errorstream<<wide_to_narrow(error_message)<<std::endl;
1176 // Break out of client scope
1181 After all content has been received:
1182 Update cached textures, meshes and materials
1184 client.afterContentReceived();
1187 Create the camera node
1189 Camera camera(smgr, draw_control, gamedef);
1190 if (!camera.successfullyCreated(error_message))
1193 f32 camera_yaw = 0; // "right/left"
1194 f32 camera_pitch = 0; // "up/down"
1200 Clouds *clouds = NULL;
1201 if(g_settings->getBool("enable_clouds"))
1203 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1211 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1217 FarMesh *farmesh = NULL;
1218 if(g_settings->getBool("enable_farmesh"))
1220 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1224 A copy of the local inventory
1226 Inventory local_inventory(itemdef);
1232 // First line of debug text
1233 gui::IGUIStaticText *guitext = guienv->addStaticText(
1235 core::rect<s32>(5, 5, 795, 5+text_height),
1237 // Second line of debug text
1238 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1240 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1242 // At the middle of the screen
1243 // Object infos are shown in this
1244 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1246 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1249 // Status text (displays info when showing and hiding GUI stuff, etc.)
1250 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1252 core::rect<s32>(0,0,0,0),
1254 guitext_status->setVisible(false);
1256 std::wstring statustext;
1257 float statustext_time = 0;
1260 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1262 core::rect<s32>(0,0,0,0),
1263 //false, false); // Disable word wrap as of now
1265 // Remove stale "recent" chat messages from previous connections
1266 chat_backend.clearRecentChat();
1267 // Chat backend and console
1268 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1270 // Profiler text (size is updated when text is updated)
1271 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1273 core::rect<s32>(0,0,0,0),
1275 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1276 guitext_profiler->setVisible(false);
1279 Some statistics are collected in these
1282 u32 beginscenetime = 0;
1284 u32 endscenetime = 0;
1286 float recent_turn_speed = 0.0;
1288 ProfilerGraph graph;
1289 // Initially clear the profiler
1290 Profiler::GraphValues dummyvalues;
1291 g_profiler->graphGet(dummyvalues);
1293 float nodig_delay_timer = 0.0;
1294 float dig_time = 0.0;
1296 PointedThing pointed_old;
1297 bool digging = false;
1298 bool ldown_for_dig = false;
1300 float damage_flash_timer = 0;
1301 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1303 const float object_hit_delay = 0.2;
1304 float object_hit_delay_timer = 0.0;
1305 float time_from_last_punch = 10;
1307 bool invert_mouse = g_settings->getBool("invert_mouse");
1309 bool respawn_menu_active = false;
1310 bool update_wielded_item_trigger = false;
1312 bool show_hud = true;
1313 bool show_chat = true;
1314 bool force_fog_off = false;
1315 bool disable_camera_update = false;
1316 bool show_debug = g_settings->getBool("show_debug");
1317 bool show_profiler_graph = false;
1318 u32 show_profiler = 0;
1319 u32 show_profiler_max = 3; // Number of pages
1321 float time_of_day = 0;
1322 float time_of_day_smooth = 0;
1328 bool first_loop_after_window_activation = true;
1330 // TODO: Convert the static interval timers to these
1331 // Interval limiter for profiler
1332 IntervalLimiter m_profiler_interval;
1334 // Time is in milliseconds
1335 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1336 // NOTE: So we have to use getTime() and call run()s between them
1337 u32 lasttime = device->getTimer()->getTime();
1341 if(device->run() == false || kill == true)
1344 // Time of frame without fps limit
1348 // not using getRealTime is necessary for wine
1349 u32 time = device->getTimer()->getTime();
1351 busytime_u32 = time - lasttime;
1354 busytime = busytime_u32 / 1000.0;
1357 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1359 // Necessary for device->getTimer()->getTime()
1367 float fps_max = g_settings->getFloat("fps_max");
1368 u32 frametime_min = 1000./fps_max;
1370 if(busytime_u32 < frametime_min)
1372 u32 sleeptime = frametime_min - busytime_u32;
1373 device->sleep(sleeptime);
1374 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1378 // Necessary for device->getTimer()->getTime()
1382 Time difference calculation
1384 f32 dtime; // in seconds
1386 u32 time = device->getTimer()->getTime();
1388 dtime = (time - lasttime) / 1000.0;
1393 g_profiler->graphAdd("mainloop_dtime", dtime);
1397 if(nodig_delay_timer >= 0)
1398 nodig_delay_timer -= dtime;
1399 if(object_hit_delay_timer >= 0)
1400 object_hit_delay_timer -= dtime;
1401 time_from_last_punch += dtime;
1403 g_profiler->add("Elapsed time", dtime);
1404 g_profiler->avg("FPS", 1./dtime);
1407 Time average and jitter calculation
1410 static f32 dtime_avg1 = 0.0;
1411 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1412 f32 dtime_jitter1 = dtime - dtime_avg1;
1414 static f32 dtime_jitter1_max_sample = 0.0;
1415 static f32 dtime_jitter1_max_fraction = 0.0;
1417 static f32 jitter1_max = 0.0;
1418 static f32 counter = 0.0;
1419 if(dtime_jitter1 > jitter1_max)
1420 jitter1_max = dtime_jitter1;
1425 dtime_jitter1_max_sample = jitter1_max;
1426 dtime_jitter1_max_fraction
1427 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1433 Busytime average and jitter calculation
1436 static f32 busytime_avg1 = 0.0;
1437 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1438 f32 busytime_jitter1 = busytime - busytime_avg1;
1440 static f32 busytime_jitter1_max_sample = 0.0;
1441 static f32 busytime_jitter1_min_sample = 0.0;
1443 static f32 jitter1_max = 0.0;
1444 static f32 jitter1_min = 0.0;
1445 static f32 counter = 0.0;
1446 if(busytime_jitter1 > jitter1_max)
1447 jitter1_max = busytime_jitter1;
1448 if(busytime_jitter1 < jitter1_min)
1449 jitter1_min = busytime_jitter1;
1453 busytime_jitter1_max_sample = jitter1_max;
1454 busytime_jitter1_min_sample = jitter1_min;
1461 Handle miscellaneous stuff
1464 if(client.accessDenied())
1466 error_message = L"Access denied. Reason: "
1467 +client.accessDeniedReason();
1468 errorstream<<wide_to_narrow(error_message)<<std::endl;
1472 if(g_gamecallback->disconnect_requested)
1474 g_gamecallback->disconnect_requested = false;
1478 if(g_gamecallback->changepassword_requested)
1480 (new GUIPasswordChange(guienv, guiroot, -1,
1481 &g_menumgr, &client))->drop();
1482 g_gamecallback->changepassword_requested = false;
1486 Process TextureSource's queue
1488 tsrc->processQueue();
1493 last_screensize = screensize;
1494 screensize = driver->getScreenSize();
1495 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1496 //bool screensize_changed = screensize != last_screensize;
1499 if(screensize.Y <= 800)
1500 hotbar_imagesize = 32;
1501 else if(screensize.Y <= 1280)
1502 hotbar_imagesize = 48;
1504 hotbar_imagesize = 64;
1506 // Hilight boxes collected during the loop and displayed
1507 core::list< core::aabbox3d<f32> > hilightboxes;
1510 std::wstring infotext;
1513 Debug info for client
1516 static float counter = 0.0;
1521 client.printDebugInfo(infostream);
1528 float profiler_print_interval =
1529 g_settings->getFloat("profiler_print_interval");
1530 bool print_to_log = true;
1531 if(profiler_print_interval == 0){
1532 print_to_log = false;
1533 profiler_print_interval = 5;
1535 if(m_profiler_interval.step(dtime, profiler_print_interval))
1538 infostream<<"Profiler:"<<std::endl;
1539 g_profiler->print(infostream);
1542 update_profiler_gui(guitext_profiler, font, text_height,
1543 show_profiler, show_profiler_max);
1545 g_profiler->clear();
1549 Direct handling of user input
1552 // Reset input if window not active or some menu is active
1553 if(device->isWindowActive() == false
1554 || noMenuActive() == false
1555 || guienv->hasFocus(gui_chat_console))
1560 // Input handler step() (used by the random input generator)
1564 Launch menus and trigger stuff according to keys
1566 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1568 // drop selected item
1569 IDropAction *a = new IDropAction();
1571 a->from_inv.setCurrentPlayer();
1572 a->from_list = "main";
1573 a->from_i = client.getPlayerItem();
1574 client.inventoryAction(a);
1576 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1578 infostream<<"the_game: "
1579 <<"Launching inventory"<<std::endl;
1581 GUIInventoryMenu *menu =
1582 new GUIInventoryMenu(guienv, guiroot, -1,
1586 InventoryLocation inventoryloc;
1587 inventoryloc.setCurrentPlayer();
1591 //"image[1,0.6;1,2;player.png]"
1592 "list[current_player;main;0,3.5;8,4;]"
1593 "list[current_player;craft;3,0;3,3;]"
1594 "list[current_player;craftpreview;7,1;1,1;]"
1599 else if(input->wasKeyDown(EscapeKey))
1601 infostream<<"the_game: "
1602 <<"Launching pause menu"<<std::endl;
1603 // It will delete itself by itself
1604 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1605 &g_menumgr, simple_singleplayer_mode))->drop();
1607 // Move mouse cursor on top of the disconnect button
1608 if(simple_singleplayer_mode)
1609 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1611 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1613 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1615 TextDest *dest = new TextDestChat(&client);
1617 (new GUITextInputMenu(guienv, guiroot, -1,
1621 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1623 TextDest *dest = new TextDestChat(&client);
1625 (new GUITextInputMenu(guienv, guiroot, -1,
1629 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1631 if (!gui_chat_console->isOpenInhibited())
1633 // Open up to over half of the screen
1634 gui_chat_console->openConsole(0.6);
1635 guienv->setFocus(gui_chat_console);
1638 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1640 if(g_settings->getBool("free_move"))
1642 g_settings->set("free_move","false");
1643 statustext = L"free_move disabled";
1644 statustext_time = 0;
1648 g_settings->set("free_move","true");
1649 statustext = L"free_move enabled";
1650 statustext_time = 0;
1651 if(!client.checkPrivilege("fly"))
1652 statustext += L" (note: no 'fly' privilege)";
1655 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1657 if(g_settings->getBool("fast_move"))
1659 g_settings->set("fast_move","false");
1660 statustext = L"fast_move disabled";
1661 statustext_time = 0;
1665 g_settings->set("fast_move","true");
1666 statustext = L"fast_move enabled";
1667 statustext_time = 0;
1668 if(!client.checkPrivilege("fast"))
1669 statustext += L" (note: no 'fast' privilege)";
1672 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1674 irr::video::IImage* const image = driver->createScreenShot();
1676 irr::c8 filename[256];
1677 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1678 g_settings->get("screenshot_path").c_str(),
1679 device->getTimer()->getRealTime());
1680 if (driver->writeImageToFile(image, filename)) {
1681 std::wstringstream sstr;
1682 sstr<<"Saved screenshot to '"<<filename<<"'";
1683 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1684 statustext = sstr.str();
1685 statustext_time = 0;
1687 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1692 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1694 show_hud = !show_hud;
1696 statustext = L"HUD shown";
1698 statustext = L"HUD hidden";
1699 statustext_time = 0;
1701 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1703 show_chat = !show_chat;
1705 statustext = L"Chat shown";
1707 statustext = L"Chat hidden";
1708 statustext_time = 0;
1710 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1712 force_fog_off = !force_fog_off;
1714 statustext = L"Fog disabled";
1716 statustext = L"Fog enabled";
1717 statustext_time = 0;
1719 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1721 disable_camera_update = !disable_camera_update;
1722 if(disable_camera_update)
1723 statustext = L"Camera update disabled";
1725 statustext = L"Camera update enabled";
1726 statustext_time = 0;
1728 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1730 // Initial / 3x toggle: Chat only
1731 // 1x toggle: Debug text with chat
1732 // 2x toggle: Debug text with profiler graph
1736 show_profiler_graph = false;
1737 statustext = L"Debug info shown";
1738 statustext_time = 0;
1740 else if(show_profiler_graph)
1743 show_profiler_graph = false;
1744 statustext = L"Debug info and profiler graph hidden";
1745 statustext_time = 0;
1749 show_profiler_graph = true;
1750 statustext = L"Profiler graph shown";
1751 statustext_time = 0;
1754 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1756 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1758 // FIXME: This updates the profiler with incomplete values
1759 update_profiler_gui(guitext_profiler, font, text_height,
1760 show_profiler, show_profiler_max);
1762 if(show_profiler != 0)
1764 std::wstringstream sstr;
1765 sstr<<"Profiler shown (page "<<show_profiler
1766 <<" of "<<show_profiler_max<<")";
1767 statustext = sstr.str();
1768 statustext_time = 0;
1772 statustext = L"Profiler hidden";
1773 statustext_time = 0;
1776 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1778 s16 range = g_settings->getS16("viewing_range_nodes_min");
1779 s16 range_new = range + 10;
1780 g_settings->set("viewing_range_nodes_min", itos(range_new));
1781 statustext = narrow_to_wide(
1782 "Minimum viewing range changed to "
1784 statustext_time = 0;
1786 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1788 s16 range = g_settings->getS16("viewing_range_nodes_min");
1789 s16 range_new = range - 10;
1792 g_settings->set("viewing_range_nodes_min",
1794 statustext = narrow_to_wide(
1795 "Minimum viewing range changed to "
1797 statustext_time = 0;
1800 // Handle QuicktuneShortcutter
1801 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1803 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1805 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1807 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1810 std::string msg = quicktune.getMessage();
1812 statustext = narrow_to_wide(msg);
1813 statustext_time = 0;
1817 // Item selection with mouse wheel
1818 u16 new_playeritem = client.getPlayerItem();
1820 s32 wheel = input->getMouseWheel();
1821 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1822 hotbar_itemcount-1);
1826 if(new_playeritem < max_item)
1833 if(new_playeritem > 0)
1836 new_playeritem = max_item;
1841 for(u16 i=0; i<10; i++)
1843 const KeyPress *kp = NumberKey + (i + 1) % 10;
1844 if(input->wasKeyDown(*kp))
1846 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1850 infostream<<"Selected item: "
1851 <<new_playeritem<<std::endl;
1856 // Viewing range selection
1857 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1859 draw_control.range_all = !draw_control.range_all;
1860 if(draw_control.range_all)
1862 infostream<<"Enabled full viewing range"<<std::endl;
1863 statustext = L"Enabled full viewing range";
1864 statustext_time = 0;
1868 infostream<<"Disabled full viewing range"<<std::endl;
1869 statustext = L"Disabled full viewing range";
1870 statustext_time = 0;
1874 // Print debug stacks
1875 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1877 dstream<<"-----------------------------------------"
1879 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1880 dstream<<"-----------------------------------------"
1882 debug_stacks_print();
1886 Mouse and camera control
1887 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1890 float turn_amount = 0;
1891 if((device->isWindowActive() && noMenuActive()) || random_input)
1895 // Mac OSX gets upset if this is set every frame
1896 if(device->getCursorControl()->isVisible())
1897 device->getCursorControl()->setVisible(false);
1900 if(first_loop_after_window_activation){
1901 //infostream<<"window active, first loop"<<std::endl;
1902 first_loop_after_window_activation = false;
1905 s32 dx = input->getMousePos().X - displaycenter.X;
1906 s32 dy = input->getMousePos().Y - displaycenter.Y;
1909 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1911 /*const float keyspeed = 500;
1912 if(input->isKeyDown(irr::KEY_UP))
1913 dy -= dtime * keyspeed;
1914 if(input->isKeyDown(irr::KEY_DOWN))
1915 dy += dtime * keyspeed;
1916 if(input->isKeyDown(irr::KEY_LEFT))
1917 dx -= dtime * keyspeed;
1918 if(input->isKeyDown(irr::KEY_RIGHT))
1919 dx += dtime * keyspeed;*/
1923 camera_pitch += dy*d;
1924 if(camera_pitch < -89.5) camera_pitch = -89.5;
1925 if(camera_pitch > 89.5) camera_pitch = 89.5;
1927 turn_amount = v2f(dx, dy).getLength() * d;
1929 input->setMousePos(displaycenter.X, displaycenter.Y);
1932 // Mac OSX gets upset if this is set every frame
1933 if(device->getCursorControl()->isVisible() == false)
1934 device->getCursorControl()->setVisible(true);
1936 //infostream<<"window inactive"<<std::endl;
1937 first_loop_after_window_activation = true;
1939 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1940 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1943 Player speed control
1955 PlayerControl control(
1956 input->isKeyDown(getKeySetting("keymap_forward")),
1957 input->isKeyDown(getKeySetting("keymap_backward")),
1958 input->isKeyDown(getKeySetting("keymap_left")),
1959 input->isKeyDown(getKeySetting("keymap_right")),
1960 input->isKeyDown(getKeySetting("keymap_jump")),
1961 input->isKeyDown(getKeySetting("keymap_special1")),
1962 input->isKeyDown(getKeySetting("keymap_sneak")),
1966 client.setPlayerControl(control);
1975 //TimeTaker timer("server->step(dtime)");
1976 server->step(dtime);
1984 //TimeTaker timer("client.step(dtime)");
1986 //client.step(dtime_avg1);
1990 // Read client events
1993 ClientEvent event = client.getClientEvent();
1994 if(event.type == CE_NONE)
1998 else if(event.type == CE_PLAYER_DAMAGE)
2000 //u16 damage = event.player_damage.amount;
2001 //infostream<<"Player damage: "<<damage<<std::endl;
2002 damage_flash_timer = 0.05;
2003 if(event.player_damage.amount >= 2){
2004 damage_flash_timer += 0.05 * event.player_damage.amount;
2007 else if(event.type == CE_PLAYER_FORCE_MOVE)
2009 camera_yaw = event.player_force_move.yaw;
2010 camera_pitch = event.player_force_move.pitch;
2012 else if(event.type == CE_DEATHSCREEN)
2014 if(respawn_menu_active)
2017 /*bool set_camera_point_target =
2018 event.deathscreen.set_camera_point_target;
2019 v3f camera_point_target;
2020 camera_point_target.X = event.deathscreen.camera_point_target_x;
2021 camera_point_target.Y = event.deathscreen.camera_point_target_y;
2022 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
2023 MainRespawnInitiator *respawner =
2024 new MainRespawnInitiator(
2025 &respawn_menu_active, &client);
2026 GUIDeathScreen *menu =
2027 new GUIDeathScreen(guienv, guiroot, -1,
2028 &g_menumgr, respawner);
2031 chat_backend.addMessage(L"", L"You died.");
2033 /* Handle visualization */
2035 damage_flash_timer = 0;
2037 /*LocalPlayer* player = client.getLocalPlayer();
2038 player->setPosition(player->getPosition() + v3f(0,-BS,0));
2039 camera.update(player, busytime, screensize);*/
2041 else if(event.type == CE_TEXTURES_UPDATED)
2043 update_wielded_item_trigger = true;
2048 //TimeTaker //timer2("//timer2");
2051 For interaction purposes, get info about the held item
2053 - Is it a usable item?
2054 - Can it point to liquids?
2056 ItemStack playeritem;
2057 bool playeritem_usable = false;
2058 bool playeritem_liquids_pointable = false;
2060 InventoryList *mlist = local_inventory.getList("main");
2063 playeritem = mlist->getItem(client.getPlayerItem());
2064 playeritem_usable = playeritem.getDefinition(itemdef).usable;
2065 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
2068 ToolCapabilities playeritem_toolcap =
2069 playeritem.getToolCapabilities(itemdef);
2075 LocalPlayer* player = client.getEnv().getLocalPlayer();
2076 float full_punch_interval = playeritem_toolcap.full_punch_interval;
2077 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
2078 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2079 camera.update(player, busytime, screensize, tool_reload_ratio);
2082 v3f player_position = player->getPosition();
2083 v3f camera_position = camera.getPosition();
2084 v3f camera_direction = camera.getDirection();
2085 f32 camera_fov = camera.getFovMax();
2087 if(!disable_camera_update){
2088 client.getEnv().getClientMap().updateCamera(camera_position,
2089 camera_direction, camera_fov);
2092 // Update sound listener
2093 sound->updateListener(camera.getCameraNode()->getPosition(),
2094 v3f(0,0,0), // velocity
2095 camera.getDirection(),
2096 camera.getCameraNode()->getUpVector());
2097 sound->setListenerGain(g_settings->getFloat("sound_volume"));
2103 soundmaker.step(dtime);
2105 ClientMap &map = client.getEnv().getClientMap();
2106 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2107 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2111 Calculate what block is the crosshair pointing to
2114 //u32 t1 = device->getTimer()->getRealTime();
2116 f32 d = 4; // max. distance
2117 core::line3d<f32> shootline(camera_position,
2118 camera_position + camera_direction * BS * (d+1));
2120 core::aabbox3d<f32> hilightbox;
2121 bool should_show_hilightbox = false;
2122 ClientActiveObject *selected_object = NULL;
2124 PointedThing pointed = getPointedThing(
2126 &client, player_position, camera_direction,
2127 camera_position, shootline, d,
2128 playeritem_liquids_pointable, !ldown_for_dig,
2130 hilightbox, should_show_hilightbox,
2133 if(pointed != pointed_old)
2135 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2136 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2142 if(should_show_hilightbox)
2143 hilightboxes.push_back(hilightbox);
2147 - releasing left mouse button
2148 - pointing away from node
2152 if(input->getLeftReleased())
2154 infostream<<"Left button released"
2155 <<" (stopped digging)"<<std::endl;
2158 else if(pointed != pointed_old)
2160 if (pointed.type == POINTEDTHING_NODE
2161 && pointed_old.type == POINTEDTHING_NODE
2162 && pointed.node_undersurface == pointed_old.node_undersurface)
2164 // Still pointing to the same node,
2165 // but a different face. Don't reset.
2169 infostream<<"Pointing away from node"
2170 <<" (stopped digging)"<<std::endl;
2176 client.interact(1, pointed_old);
2177 client.setCrack(-1, v3s16(0,0,0));
2181 if(!digging && ldown_for_dig && !input->getLeftState())
2183 ldown_for_dig = false;
2186 bool left_punch = false;
2187 soundmaker.m_player_leftpunch_sound.name = "";
2189 if(playeritem_usable && input->getLeftState())
2191 if(input->getLeftClicked())
2192 client.interact(4, pointed);
2194 else if(pointed.type == POINTEDTHING_NODE)
2196 v3s16 nodepos = pointed.node_undersurface;
2197 v3s16 neighbourpos = pointed.node_abovesurface;
2200 Check information text of node
2203 ClientMap &map = client.getEnv().getClientMap();
2204 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2206 infotext = narrow_to_wide(meta->getString("infotext"));
2208 MapNode n = map.getNode(nodepos);
2209 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
2210 infotext = L"Unknown node: ";
2211 infotext += narrow_to_wide(nodedef->get(n).name);
2215 // We can't actually know, but assume the sound of right-clicking
2216 // to be the sound of placing a node
2217 soundmaker.m_player_rightpunch_sound.gain = 0.5;
2218 soundmaker.m_player_rightpunch_sound.name = "default_place_node";
2224 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2228 infostream<<"Started digging"<<std::endl;
2229 client.interact(0, pointed);
2231 ldown_for_dig = true;
2233 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2235 // Get digging parameters
2236 DigParams params = getDigParams(nodedef->get(n).groups,
2237 &playeritem_toolcap);
2238 // If can't dig, try hand
2239 if(!params.diggable){
2240 const ItemDefinition &hand = itemdef->get("");
2241 const ToolCapabilities *tp = hand.tool_capabilities;
2243 params = getDigParams(nodedef->get(n).groups, tp);
2246 SimpleSoundSpec sound_dig = nodedef->get(n).sound_dig;
2247 if(sound_dig.exists()){
2248 if(sound_dig.name == "__group"){
2249 if(params.main_group != ""){
2250 soundmaker.m_player_leftpunch_sound.gain = 0.5;
2251 soundmaker.m_player_leftpunch_sound.name =
2252 std::string("default_dig_") +
2256 soundmaker.m_player_leftpunch_sound = sound_dig;
2260 float dig_time_complete = 0.0;
2262 if(params.diggable == false)
2264 // I guess nobody will wait for this long
2265 dig_time_complete = 10000000.0;
2269 dig_time_complete = params.time;
2272 if(dig_time_complete >= 0.001)
2274 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
2275 * dig_time/dig_time_complete);
2277 // This is for torches
2280 dig_index = CRACK_ANIMATION_LENGTH;
2283 // Don't show cracks if not diggable
2284 if(dig_time_complete >= 100000.0)
2287 else if(dig_index < CRACK_ANIMATION_LENGTH)
2289 //TimeTaker timer("client.setTempMod");
2290 //infostream<<"dig_index="<<dig_index<<std::endl;
2291 client.setCrack(dig_index, nodepos);
2295 infostream<<"Digging completed"<<std::endl;
2296 client.interact(2, pointed);
2297 client.setCrack(-1, v3s16(0,0,0));
2298 MapNode wasnode = map.getNode(nodepos);
2299 client.removeNode(nodepos);
2304 nodig_delay_timer = dig_time_complete
2305 / (float)CRACK_ANIMATION_LENGTH;
2307 // We don't want a corresponding delay to
2308 // very time consuming nodes
2309 if(nodig_delay_timer > 0.3)
2310 nodig_delay_timer = 0.3;
2311 // We want a slight delay to very little
2312 // time consuming nodes
2313 float mindelay = 0.15;
2314 if(nodig_delay_timer < mindelay)
2315 nodig_delay_timer = mindelay;
2317 // Send event to trigger sound
2318 MtEvent *e = new NodeDugEvent(nodepos, wasnode);
2319 gamedef->event()->put(e);
2324 camera.setDigging(0); // left click animation
2327 if(input->getRightClicked())
2329 infostream<<"Ground right-clicked"<<std::endl;
2331 // sign special case, at least until formspec is properly implemented
2332 if(meta && meta->getString("formspec") == "hack:sign_text_input" && !random_input)
2334 infostream<<"Launching metadata text input"<<std::endl;
2336 // Get a new text for it
2338 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2340 std::wstring wtext = narrow_to_wide(meta->getString("text"));
2342 (new GUITextInputMenu(guienv, guiroot, -1,
2346 // If metadata provides an inventory view, activate it
2347 else if(meta && meta->getString("formspec") != "" && !random_input)
2349 infostream<<"Launching custom inventory view"<<std::endl;
2351 InventoryLocation inventoryloc;
2352 inventoryloc.setNodeMeta(nodepos);
2356 GUIInventoryMenu *menu =
2357 new GUIInventoryMenu(guienv, guiroot, -1,
2360 menu->setFormSpec(meta->getString("formspec"),
2362 menu->setFormSource(new NodeMetadataFormSource(
2363 &client.getEnv().getClientMap(), nodepos));
2366 // Otherwise report right click to server
2369 client.interact(3, pointed);
2370 camera.setDigging(1); // right click animation
2374 else if(pointed.type == POINTEDTHING_OBJECT)
2376 infotext = narrow_to_wide(selected_object->infoText());
2378 if(infotext == L"" && show_debug){
2379 infotext = narrow_to_wide(selected_object->debugInfoText());
2382 //if(input->getLeftClicked())
2383 if(input->getLeftState())
2385 bool do_punch = false;
2386 bool do_punch_damage = false;
2387 if(object_hit_delay_timer <= 0.0){
2389 do_punch_damage = true;
2390 object_hit_delay_timer = object_hit_delay;
2392 if(input->getLeftClicked()){
2396 infostream<<"Left-clicked object"<<std::endl;
2399 if(do_punch_damage){
2400 // Report direct punch
2401 v3f objpos = selected_object->getPosition();
2402 v3f dir = (objpos - player_position).normalize();
2404 bool disable_send = selected_object->directReportPunch(
2405 dir, &playeritem, time_from_last_punch);
2406 time_from_last_punch = 0;
2408 client.interact(0, pointed);
2411 else if(input->getRightClicked())
2413 infostream<<"Right-clicked object"<<std::endl;
2414 client.interact(3, pointed); // place
2417 else if(input->getLeftState())
2419 // When button is held down in air, show continuous animation
2423 pointed_old = pointed;
2425 if(left_punch || input->getLeftClicked())
2427 camera.setDigging(0); // left click animation
2430 input->resetLeftClicked();
2431 input->resetRightClicked();
2433 input->resetLeftReleased();
2434 input->resetRightReleased();
2437 Calculate stuff for drawing
2447 fog_range = BS*farmesh_range;
2451 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2453 if(draw_control.range_all)
2454 fog_range = 100000*BS;
2458 Calculate general brightness
2460 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2461 float time_brightness = (float)decode_light(
2462 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2463 float direct_brightness = 0;
2464 bool sunlight_seen = false;
2465 if(g_settings->getBool("free_move")){
2466 direct_brightness = time_brightness;
2467 sunlight_seen = true;
2469 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2470 float old_brightness = sky->getBrightness();
2471 direct_brightness = (float)client.getEnv().getClientMap()
2472 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2473 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2477 time_of_day = client.getEnv().getTimeOfDayF();
2479 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2480 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2481 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2482 time_of_day_smooth = time_of_day;
2484 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2485 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2486 + (time_of_day+1.0) * todsm;
2488 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2489 + time_of_day * todsm;
2491 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2494 float brightness = sky->getBrightness();
2495 video::SColor bgcolor = sky->getBgColor();
2496 video::SColor skycolor = sky->getSkyColor();
2502 if(sky->getCloudsVisible()){
2503 clouds->setVisible(true);
2504 clouds->step(dtime);
2505 clouds->update(v2f(player_position.X, player_position.Z),
2506 sky->getCloudColor());
2508 clouds->setVisible(false);
2517 farmesh_range = draw_control.wanted_range * 10;
2518 if(draw_control.range_all && farmesh_range < 500)
2519 farmesh_range = 500;
2520 if(farmesh_range > 1000)
2521 farmesh_range = 1000;
2523 farmesh->step(dtime);
2524 farmesh->update(v2f(player_position.X, player_position.Z),
2525 brightness, farmesh_range);
2532 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2536 video::EFT_FOG_LINEAR,
2548 video::EFT_FOG_LINEAR,
2558 Update gui stuff (0ms)
2561 //TimeTaker guiupdatetimer("Gui updating");
2563 const char program_name_and_version[] =
2564 "Minetest-c55 " VERSION_STRING;
2568 static float drawtime_avg = 0;
2569 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2570 /*static float beginscenetime_avg = 0;
2571 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2572 static float scenetime_avg = 0;
2573 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2574 static float endscenetime_avg = 0;
2575 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2578 snprintf(temptext, 300, "%s ("
2581 " drawtime=%.0f, dtime_jitter = % .1f %%"
2582 ", v_range = %.1f, RTT = %.3f",
2583 program_name_and_version,
2584 draw_control.range_all,
2586 dtime_jitter1_max_fraction * 100.0,
2587 draw_control.wanted_range,
2591 guitext->setText(narrow_to_wide(temptext).c_str());
2592 guitext->setVisible(true);
2594 else if(show_hud || show_chat)
2596 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2597 guitext->setVisible(true);
2601 guitext->setVisible(false);
2607 snprintf(temptext, 300,
2608 "(% .1f, % .1f, % .1f)"
2609 " (yaw = %.1f) (seed = %lli)",
2610 player_position.X/BS,
2611 player_position.Y/BS,
2612 player_position.Z/BS,
2613 wrapDegrees_0_360(camera_yaw),
2614 client.getMapSeed());
2616 guitext2->setText(narrow_to_wide(temptext).c_str());
2617 guitext2->setVisible(true);
2621 guitext2->setVisible(false);
2625 guitext_info->setText(infotext.c_str());
2626 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2630 float statustext_time_max = 1.5;
2631 if(!statustext.empty())
2633 statustext_time += dtime;
2634 if(statustext_time >= statustext_time_max)
2637 statustext_time = 0;
2640 guitext_status->setText(statustext.c_str());
2641 guitext_status->setVisible(!statustext.empty());
2643 if(!statustext.empty())
2645 s32 status_y = screensize.Y - 130;
2646 core::rect<s32> rect(
2648 status_y - guitext_status->getTextHeight(),
2652 guitext_status->setRelativePosition(rect);
2655 video::SColor initial_color(255,0,0,0);
2656 if(guienv->getSkin())
2657 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2658 video::SColor final_color = initial_color;
2659 final_color.setAlpha(0);
2660 video::SColor fade_color =
2661 initial_color.getInterpolated_quadratic(
2664 pow(statustext_time / (float)statustext_time_max, 2.0f));
2665 guitext_status->setOverrideColor(fade_color);
2666 guitext_status->enableOverrideColor(true);
2671 Get chat messages from client
2674 // Get new messages from error log buffer
2675 while(!chat_log_error_buf.empty())
2677 chat_backend.addMessage(L"", narrow_to_wide(
2678 chat_log_error_buf.get()));
2680 // Get new messages from client
2681 std::wstring message;
2682 while(client.getChatMessage(message))
2684 chat_backend.addUnparsedMessage(message);
2686 // Remove old messages
2687 chat_backend.step(dtime);
2689 // Display all messages in a static text element
2690 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2691 std::wstring recent_chat = chat_backend.getRecentChat();
2692 guitext_chat->setText(recent_chat.c_str());
2694 // Update gui element size and position
2695 s32 chat_y = 5+(text_height+5);
2697 chat_y += (text_height+5);
2698 core::rect<s32> rect(
2702 chat_y + guitext_chat->getTextHeight()
2704 guitext_chat->setRelativePosition(rect);
2706 // Don't show chat if disabled or empty or profiler is enabled
2707 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2715 if(client.getPlayerItem() != new_playeritem)
2717 client.selectPlayerItem(new_playeritem);
2719 if(client.getLocalInventoryUpdated())
2721 //infostream<<"Updating local inventory"<<std::endl;
2722 client.getLocalInventory(local_inventory);
2724 update_wielded_item_trigger = true;
2726 if(update_wielded_item_trigger)
2728 update_wielded_item_trigger = false;
2729 // Update wielded tool
2730 InventoryList *mlist = local_inventory.getList("main");
2733 item = mlist->getItem(client.getPlayerItem());
2741 TimeTaker tt_draw("mainloop: draw");
2745 TimeTaker timer("beginScene");
2746 //driver->beginScene(false, true, bgcolor);
2747 //driver->beginScene(true, true, bgcolor);
2748 driver->beginScene(true, true, skycolor);
2749 beginscenetime = timer.stop(true);
2754 //infostream<<"smgr->drawAll()"<<std::endl;
2756 TimeTaker timer("smgr");
2758 scenetime = timer.stop(true);
2762 //TimeTaker timer9("auxiliary drawings");
2766 //TimeTaker //timer10("//timer10");
2772 driver->setMaterial(m);
2774 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2778 for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2779 i != hilightboxes.end(); i++)
2781 /*infostream<<"hilightbox min="
2782 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2784 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2786 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2795 // Warning: This clears the Z buffer.
2796 camera.drawWieldedTool();
2803 client.getEnv().getClientMap().renderPostFx();
2809 if(show_profiler_graph)
2811 graph.draw(10, screensize.Y - 10, driver, font);
2819 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2820 displaycenter + core::vector2d<s32>(10,0),
2821 video::SColor(255,255,255,255));
2822 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2823 displaycenter + core::vector2d<s32>(0,10),
2824 video::SColor(255,255,255,255));
2830 //TimeTaker //timer11("//timer11");
2843 draw_hotbar(driver, font, gamedef,
2844 v2s32(displaycenter.X, screensize.Y),
2845 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2846 client.getHP(), client.getPlayerItem());
2852 if(damage_flash_timer > 0.0)
2854 damage_flash_timer -= dtime;
2856 video::SColor color(128,255,0,0);
2857 driver->draw2DRectangle(color,
2858 core::rect<s32>(0,0,screensize.X,screensize.Y),
2866 TimeTaker timer("endScene");
2868 endscenetime = timer.stop(true);
2871 drawtime = tt_draw.stop(true);
2872 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2878 static s16 lastFPS = 0;
2879 //u16 fps = driver->getFPS();
2880 u16 fps = (1.0/dtime_avg1);
2884 core::stringw str = L"Minetest [";
2885 str += driver->getName();
2889 device->setWindowCaption(str.c_str());
2894 Log times and stuff for visualization
2896 Profiler::GraphValues values;
2897 g_profiler->graphGet(values);
2906 if(gui_chat_console)
2907 gui_chat_console->drop();
2910 Draw a "shutting down" screen, which will be shown while the map
2911 generator and other stuff quits
2914 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2915 draw_load_screen(L"Shutting down stuff...", driver, font);
2916 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2919 gui_shuttingdowntext->remove();*/
2922 chat_backend.addMessage(L"", L"# Disconnected.");
2923 chat_backend.addMessage(L"", L"");
2925 // Client scope (client is destructed before destructing *def and tsrc)
2928 catch(SerializationError &e)
2930 error_message = L"A serialization error occurred:\n"
2931 + narrow_to_wide(e.what()) + L"\n\nThe server is probably "
2932 L" running a different version of Minetest.";
2933 errorstream<<wide_to_narrow(error_message)<<std::endl;