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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
15 You should have received a copy of the GNU 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"
66 Setting this to 1 enables a special camera mode that forces
67 the renderers to think that the camera statically points from
68 the starting place to a static direction.
70 This allows one to move around with the player and see what
71 is actually drawn behind solid things and behind the player.
73 #define FIELD_OF_VIEW_TEST 0
80 struct TextDestChat : public TextDest
82 TextDestChat(Client *client)
86 void gotText(std::wstring text)
88 m_client->typeChatMessage(text);
94 struct TextDestNodeMetadata : public TextDest
96 TextDestNodeMetadata(v3s16 p, Client *client)
101 void gotText(std::wstring text)
103 std::string ntext = wide_to_narrow(text);
104 infostream<<"Changing text of a sign node: "
106 m_client->sendSignNodeText(m_p, ntext);
113 /* Respawn menu callback */
115 class MainRespawnInitiator: public IRespawnInitiator
118 MainRespawnInitiator(bool *active, Client *client):
119 m_active(active), m_client(client)
126 m_client->sendRespawn();
136 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
138 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
139 Inventory *inventory, s32 halfheartcount, u16 playeritem)
141 InventoryList *mainlist = inventory->getList("main");
144 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
148 s32 padding = imgsize/12;
149 //s32 height = imgsize + padding*2;
150 s32 width = itemcount*(imgsize+padding*2);
152 // Position of upper left corner of bar
153 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
155 // Draw background color
156 /*core::rect<s32> barrect(0,0,width,height);
158 video::SColor bgcolor(255,128,128,128);
159 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
161 core::rect<s32> imgrect(0,0,imgsize,imgsize);
163 for(s32 i=0; i<itemcount; i++)
165 const ItemStack &item = mainlist->getItem(i);
167 core::rect<s32> rect = imgrect + pos
168 + v2s32(padding+i*(imgsize+padding*2), padding);
172 video::SColor c_outside(255,255,0,0);
173 //video::SColor c_outside(255,0,0,0);
174 //video::SColor c_inside(255,192,192,192);
175 s32 x1 = rect.UpperLeftCorner.X;
176 s32 y1 = rect.UpperLeftCorner.Y;
177 s32 x2 = rect.LowerRightCorner.X;
178 s32 y2 = rect.LowerRightCorner.Y;
179 // Black base borders
180 driver->draw2DRectangle(c_outside,
182 v2s32(x1 - padding, y1 - padding),
183 v2s32(x2 + padding, y1)
185 driver->draw2DRectangle(c_outside,
187 v2s32(x1 - padding, y2),
188 v2s32(x2 + padding, y2 + padding)
190 driver->draw2DRectangle(c_outside,
192 v2s32(x1 - padding, y1),
195 driver->draw2DRectangle(c_outside,
198 v2s32(x2 + padding, y2)
200 /*// Light inside borders
201 driver->draw2DRectangle(c_inside,
203 v2s32(x1 - padding/2, y1 - padding/2),
204 v2s32(x2 + padding/2, y1)
206 driver->draw2DRectangle(c_inside,
208 v2s32(x1 - padding/2, y2),
209 v2s32(x2 + padding/2, y2 + padding/2)
211 driver->draw2DRectangle(c_inside,
213 v2s32(x1 - padding/2, y1),
216 driver->draw2DRectangle(c_inside,
219 v2s32(x2 + padding/2, y2)
224 video::SColor bgcolor2(128,0,0,0);
225 driver->draw2DRectangle(bgcolor2, rect, NULL);
226 drawItemStack(driver, font, item, rect, NULL, gamedef);
232 video::ITexture *heart_texture =
233 gamedef->getTextureSource()->getTextureRaw("heart.png");
236 v2s32 p = pos + v2s32(0, -20);
237 for(s32 i=0; i<halfheartcount/2; i++)
239 const video::SColor color(255,255,255,255);
240 const video::SColor colors[] = {color,color,color,color};
241 core::rect<s32> rect(0,0,16,16);
243 driver->draw2DImage(heart_texture, rect,
244 core::rect<s32>(core::position2d<s32>(0,0),
245 core::dimension2di(heart_texture->getOriginalSize())),
249 if(halfheartcount % 2 == 1)
251 const video::SColor color(255,255,255,255);
252 const video::SColor colors[] = {color,color,color,color};
253 core::rect<s32> rect(0,0,16/2,16);
255 core::dimension2di srcd(heart_texture->getOriginalSize());
257 driver->draw2DImage(heart_texture, rect,
258 core::rect<s32>(core::position2d<s32>(0,0), srcd),
266 Check if a node is pointable
268 inline bool isPointableNode(const MapNode& n,
269 Client *client, bool liquids_pointable)
271 const ContentFeatures &features = client->getNodeDefManager()->get(n);
272 return features.pointable ||
273 (liquids_pointable && features.isLiquid());
277 Find what the player is pointing at
279 PointedThing getPointedThing(Client *client, v3f player_position,
280 v3f camera_direction, v3f camera_position,
281 core::line3d<f32> shootline, f32 d,
282 bool liquids_pointable,
283 bool look_for_object,
284 core::aabbox3d<f32> &hilightbox,
285 bool &should_show_hilightbox,
286 ClientActiveObject *&selected_object)
290 hilightbox = core::aabbox3d<f32>(0,0,0,0,0,0);
291 should_show_hilightbox = false;
292 selected_object = NULL;
294 INodeDefManager *nodedef = client->getNodeDefManager();
295 ClientMap &map = client->getEnv().getClientMap();
297 // First try to find a pointed at active object
300 selected_object = client->getSelectedActiveObject(d*BS,
301 camera_position, shootline);
303 if(selected_object != NULL)
305 core::aabbox3d<f32> *selection_box
306 = selected_object->getSelectionBox();
307 // Box should exist because object was returned in the
309 assert(selection_box);
311 v3f pos = selected_object->getPosition();
313 hilightbox = core::aabbox3d<f32>(
314 selection_box->MinEdge + pos,
315 selection_box->MaxEdge + pos
318 should_show_hilightbox = selected_object->doShowSelectionBox();
320 result.type = POINTEDTHING_OBJECT;
321 result.object_id = selected_object->getId();
325 // That didn't work, try to find a pointed at node
327 f32 mindistance = BS * 1001;
329 v3s16 pos_i = floatToInt(player_position, BS);
331 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
335 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
336 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
337 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
338 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
339 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
340 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
342 for(s16 y = ystart; y <= yend; y++)
343 for(s16 z = zstart; z <= zend; z++)
344 for(s16 x = xstart; x <= xend; x++)
349 n = map.getNode(v3s16(x,y,z));
351 catch(InvalidPositionException &e)
355 if(!isPointableNode(n, client, liquids_pointable))
359 v3f npf = intToFloat(np, BS);
364 v3s16(0,0,1), // back
366 v3s16(1,0,0), // right
367 v3s16(0,0,-1), // front
368 v3s16(0,-1,0), // bottom
369 v3s16(-1,0,0), // left
372 const ContentFeatures &f = nodedef->get(n);
374 if(f.selection_box.type == NODEBOX_FIXED)
376 core::aabbox3d<f32> box = f.selection_box.fixed;
380 v3s16 facedirs[6] = {
389 core::aabbox3d<f32> faceboxes[6] = {
392 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
393 box.MinEdge.X+d, box.MaxEdge.Y, box.MaxEdge.Z
397 box.MaxEdge.X-d, box.MinEdge.Y, box.MinEdge.Z,
398 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
402 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
403 box.MaxEdge.X, box.MinEdge.Y+d, box.MaxEdge.Z
407 box.MinEdge.X, box.MaxEdge.Y-d, box.MinEdge.Z,
408 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
412 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
413 box.MaxEdge.X, box.MaxEdge.Y, box.MinEdge.Z+d
417 box.MinEdge.X, box.MinEdge.Y, box.MaxEdge.Z-d,
418 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
422 for(u16 i=0; i<6; i++)
424 v3f facedir_f(facedirs[i].X, facedirs[i].Y, facedirs[i].Z);
425 v3f centerpoint = npf + facedir_f * BS/2;
426 f32 distance = (centerpoint - camera_position).getLength();
427 if(distance >= mindistance)
429 if(!faceboxes[i].intersectsWithLine(shootline))
431 result.type = POINTEDTHING_NODE;
432 result.node_undersurface = np;
433 result.node_abovesurface = np+facedirs[i];
434 mindistance = distance;
436 should_show_hilightbox = true;
439 else if(f.selection_box.type == NODEBOX_WALLMOUNTED)
441 v3s16 dir = n.getWallMountedDir(nodedef);
442 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
443 dir_f *= BS/2 - BS/6 - BS/20;
444 v3f cpf = npf + dir_f;
445 f32 distance = (cpf - camera_position).getLength();
447 core::aabbox3d<f32> box;
450 if(dir == v3s16(0,1,0)){
451 box = f.selection_box.wall_top;
454 else if(dir == v3s16(0,-1,0)){
455 box = f.selection_box.wall_bottom;
461 f.selection_box.wall_side.MinEdge,
462 f.selection_box.wall_side.MaxEdge
465 for(s32 i=0; i<2; i++)
467 if(dir == v3s16(-1,0,0))
468 vertices[i].rotateXZBy(0);
469 if(dir == v3s16(1,0,0))
470 vertices[i].rotateXZBy(180);
471 if(dir == v3s16(0,0,-1))
472 vertices[i].rotateXZBy(90);
473 if(dir == v3s16(0,0,1))
474 vertices[i].rotateXZBy(-90);
477 box = core::aabbox3d<f32>(vertices[0]);
478 box.addInternalPoint(vertices[1]);
484 if(distance < mindistance)
486 if(box.intersectsWithLine(shootline))
488 result.type = POINTEDTHING_NODE;
489 result.node_undersurface = np;
490 result.node_abovesurface = np;
491 mindistance = distance;
493 should_show_hilightbox = true;
497 else // NODEBOX_REGULAR
499 for(u16 i=0; i<6; i++)
501 v3f dir_f = v3f(dirs[i].X,
502 dirs[i].Y, dirs[i].Z);
503 v3f centerpoint = npf + dir_f * BS/2;
505 (centerpoint - camera_position).getLength();
507 if(distance < mindistance)
509 core::CMatrix4<f32> m;
510 m.buildRotateFromTo(v3f(0,0,1), dir_f);
512 // This is the back face
514 v3f(BS/2, BS/2, BS/2),
515 v3f(-BS/2, -BS/2, BS/2+d)
518 for(u16 j=0; j<2; j++)
520 m.rotateVect(corners[j]);
524 core::aabbox3d<f32> facebox(corners[0]);
525 facebox.addInternalPoint(corners[1]);
527 if(facebox.intersectsWithLine(shootline))
529 result.type = POINTEDTHING_NODE;
530 result.node_undersurface = np;
531 result.node_abovesurface = np + dirs[i];
532 mindistance = distance;
534 //hilightbox = facebox;
536 const float d = 0.502;
537 core::aabbox3d<f32> nodebox
538 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
539 v3f nodepos_f = intToFloat(np, BS);
540 nodebox.MinEdge += nodepos_f;
541 nodebox.MaxEdge += nodepos_f;
542 hilightbox = nodebox;
543 should_show_hilightbox = true;
545 } // if distance < mindistance
554 Draws a screen with a single text on it.
555 Text will be removed when the screen is drawn the next time.
557 /*gui::IGUIStaticText **/
558 void draw_load_screen(const std::wstring &text,
559 video::IVideoDriver* driver, gui::IGUIFont* font)
561 v2u32 screensize = driver->getScreenSize();
562 const wchar_t *loadingtext = text.c_str();
563 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
564 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
565 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
566 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
568 gui::IGUIStaticText *guitext = guienv->addStaticText(
569 loadingtext, textrect, false, false);
570 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
572 driver->beginScene(true, true, video::SColor(255,0,0,0));
581 /* Profiler display */
583 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
584 gui::IGUIFont *font, u32 text_height,
585 u32 show_profiler, u32 show_profiler_max)
587 if(show_profiler == 0)
589 guitext_profiler->setVisible(false);
594 std::ostringstream os(std::ios_base::binary);
595 g_profiler->printPage(os, show_profiler, show_profiler_max);
596 std::wstring text = narrow_to_wide(os.str());
597 guitext_profiler->setText(text.c_str());
598 guitext_profiler->setVisible(true);
600 s32 w = font->getDimension(text.c_str()).Width;
603 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
604 8+(text_height+5)*2 +
605 font->getDimension(text.c_str()).Height);
606 guitext_profiler->setRelativePosition(rect);
607 guitext_profiler->setVisible(true);
615 Profiler::GraphValues values;
621 Meta(float initial=0, video::SColor color=
622 video::SColor(255,255,255,255)):
628 std::list<Piece> m_log;
636 void put(const Profiler::GraphValues &values)
639 piece.values = values;
640 m_log.push_back(piece);
641 while(m_log.size() > m_log_max_size)
642 m_log.erase(m_log.begin());
645 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
646 gui::IGUIFont* font) const
648 std::map<std::string, Meta> m_meta;
649 for(std::list<Piece>::const_iterator k = m_log.begin();
650 k != m_log.end(); k++)
652 const Piece &piece = *k;
653 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
654 i != piece.values.end(); i++){
655 const std::string &id = i->first;
656 const float &value = i->second;
657 std::map<std::string, Meta>::iterator j =
659 if(j == m_meta.end()){
660 m_meta[id] = Meta(value);
663 if(value < j->second.min)
664 j->second.min = value;
665 if(value > j->second.max)
666 j->second.max = value;
671 static const video::SColor usable_colors[] = {
672 video::SColor(255,255,100,100),
673 video::SColor(255,90,225,90),
674 video::SColor(255,100,100,255),
675 video::SColor(255,255,150,50),
676 video::SColor(255,220,220,100)
678 static const u32 usable_colors_count =
679 sizeof(usable_colors) / sizeof(*usable_colors);
680 u32 next_color_i = 0;
681 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
682 i != m_meta.end(); i++){
683 Meta &meta = i->second;
684 video::SColor color(255,200,200,200);
685 if(next_color_i < usable_colors_count)
686 color = usable_colors[next_color_i++];
691 s32 textx = x_left + m_log_max_size + 15;
692 s32 textx2 = textx + 200 - 15;
696 u32 num_graphs = m_meta.size();
697 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
699 video::SColor bgcolor(120,0,0,0);
700 driver->draw2DRectangle(bgcolor, rect, NULL);
704 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
705 i != m_meta.end(); i++){
706 const std::string &id = i->first;
707 const Meta &meta = i->second;
709 s32 y = y_bottom - meta_i * 50;
710 float show_min = meta.min;
711 float show_max = meta.max;
712 if(show_min >= -0.0001 && show_max >= -0.0001){
713 if(show_min <= show_max * 0.5)
718 snprintf(buf, 10, "%.3g", show_max);
719 font->draw(narrow_to_wide(buf).c_str(),
720 core::rect<s32>(textx, y - graphh,
721 textx2, y - graphh + texth),
723 snprintf(buf, 10, "%.3g", show_min);
724 font->draw(narrow_to_wide(buf).c_str(),
725 core::rect<s32>(textx, y - texth,
728 font->draw(narrow_to_wide(id).c_str(),
729 core::rect<s32>(textx, y - graphh/2 - texth/2,
730 textx2, y - graphh/2 + texth/2),
733 s32 graph1h = graphh;
734 bool relativegraph = (show_min != 0 && show_min != show_max);
735 float lastscaledvalue = 0.0;
736 bool lastscaledvalue_exists = false;
737 for(std::list<Piece>::const_iterator j = m_log.begin();
738 j != m_log.end(); j++)
740 const Piece &piece = *j;
742 bool value_exists = false;
743 Profiler::GraphValues::const_iterator k =
744 piece.values.find(id);
745 if(k != piece.values.end()){
751 lastscaledvalue_exists = false;
754 float scaledvalue = 1.0;
755 if(show_max != show_min)
756 scaledvalue = (value - show_min) / (show_max - show_min);
757 if(scaledvalue == 1.0 && value == 0){
759 lastscaledvalue_exists = false;
763 if(lastscaledvalue_exists){
764 s32 ivalue1 = lastscaledvalue * graph1h;
765 s32 ivalue2 = scaledvalue * graph1h;
766 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
767 v2s32(x, graph1y - ivalue2), meta.color);
769 lastscaledvalue = scaledvalue;
770 lastscaledvalue_exists = true;
772 s32 ivalue = scaledvalue * graph1h;
773 driver->draw2DLine(v2s32(x, graph1y),
774 v2s32(x, graph1y - ivalue), meta.color);
786 ISoundManager *m_sound;
788 SimpleSoundSpec m_player_step_sound;
789 float m_player_step_timer;
791 SoundMaker(ISoundManager *sound):
793 m_player_step_sound("default_grass_walk"),
794 m_player_step_timer(0)
798 void playPlayerStep()
800 if(m_player_step_timer <= 0 && m_player_step_sound.exists()){
801 m_player_step_timer = 0.03;
802 m_sound->playSound(m_player_step_sound, false);
806 static void viewBobbingStep(MtEvent *e, void *data)
808 SoundMaker *sm = (SoundMaker*)data;
809 sm->playPlayerStep();
812 static void playerRegainGround(MtEvent *e, void *data)
814 SoundMaker *sm = (SoundMaker*)data;
815 sm->playPlayerStep();
818 static void playerJump(MtEvent *e, void *data)
822 void registerReceiver(MtEventManager *mgr)
824 mgr->reg("ViewBobbingStep", SoundMaker::viewBobbingStep, this);
825 mgr->reg("PlayerRegainGround", SoundMaker::playerRegainGround, this);
826 mgr->reg("PlayerJump", SoundMaker::playerJump, this);
829 void step(float dtime)
831 m_player_step_timer -= dtime;
839 IrrlichtDevice *device,
842 std::string playername,
843 std::string password,
844 std::string address, // If "", local server is used
846 std::wstring &error_message,
847 std::string configpath,
848 ChatBackend &chat_backend,
849 const SubgameSpec &gamespec, // Used for local game,
850 bool simple_singleplayer_mode
853 video::IVideoDriver* driver = device->getVideoDriver();
854 scene::ISceneManager* smgr = device->getSceneManager();
856 // Calculate text height using the font
857 u32 text_height = font->getDimension(L"Random test string").Height;
859 v2u32 screensize(0,0);
860 v2u32 last_screensize(0,0);
861 screensize = driver->getScreenSize();
863 const s32 hotbar_itemcount = 8;
864 //const s32 hotbar_imagesize = 36;
865 //const s32 hotbar_imagesize = 64;
866 s32 hotbar_imagesize = 48;
869 Draw "Loading" screen
872 draw_load_screen(L"Loading...", driver, font);
874 // Create texture source
875 IWritableTextureSource *tsrc = createTextureSource(device);
877 // These will be filled by data received from the server
878 // Create item definition manager
879 IWritableItemDefManager *itemdef = createItemDefManager();
880 // Create node definition manager
881 IWritableNodeDefManager *nodedef = createNodeDefManager();
884 ISoundManager *sound = NULL;
885 bool sound_is_dummy = false;
887 infostream<<"Attempting to use OpenAL audio"<<std::endl;
888 sound = createOpenALSoundManager(NULL);
890 infostream<<"Failed to initialize OpenAL audio"<<std::endl;
893 infostream<<"Using dummy audio."<<std::endl;
894 sound = &dummySoundManager;
895 sound_is_dummy = true;
899 EventManager eventmgr;
902 SoundMaker soundmaker(sound);
903 soundmaker.registerReceiver(&eventmgr);
906 sound->loadSound("default_grass_footstep", porting::path_share + DIR_DELIM
907 + "sounds" + DIR_DELIM + "default_grass_walk3_mono.ogg");
908 sound->loadSound("default_grass_footstep", porting::path_share + DIR_DELIM
909 + "sounds" + DIR_DELIM + "default_grass_walk4_mono.ogg");
910 //sound->playSound("default_grass_walk", false, 1.0);
911 //sound->playSoundAt("default_grass_walk", true, 1.0, v3f(0,10,0)*BS);
913 // Add chat log output for errors to be shown in chat
914 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
916 // Create UI for modifying quicktune values
917 QuicktuneShortcutter quicktune;
921 SharedPtr will delete it when it goes out of scope.
923 SharedPtr<Server> server;
925 draw_load_screen(L"Creating server...", driver, font);
926 infostream<<"Creating server"<<std::endl;
927 server = new Server(map_dir, configpath, gamespec,
928 simple_singleplayer_mode);
932 do{ // Client scope (breakable do-while(0))
938 draw_load_screen(L"Creating client...", driver, font);
939 infostream<<"Creating client"<<std::endl;
941 MapDrawControl draw_control;
943 Client client(device, playername.c_str(), password, draw_control,
944 tsrc, itemdef, nodedef, sound, &eventmgr);
946 // Client acts as our GameDef
947 IGameDef *gamedef = &client;
949 draw_load_screen(L"Resolving address...", driver, font);
950 Address connect_address(0,0,0,0, port);
953 //connect_address.Resolve("localhost");
954 connect_address.setAddress(127,0,0,1);
956 connect_address.Resolve(address.c_str());
958 catch(ResolveError &e)
960 error_message = L"Couldn't resolve address";
961 errorstream<<wide_to_narrow(error_message)<<std::endl;
962 // Break out of client scope
967 Attempt to connect to the server
970 infostream<<"Connecting to server at ";
971 connect_address.print(&infostream);
972 infostream<<std::endl;
973 client.connect(connect_address);
976 Wait for server to accept connection
978 bool could_connect = false;
979 bool connect_aborted = false;
981 float frametime = 0.033;
982 float time_counter = 0.0;
986 // Update client and server
987 client.step(frametime);
989 server->step(frametime);
992 if(client.connectedAndInitialized()){
993 could_connect = true;
997 if(client.accessDenied()){
998 error_message = L"Access denied. Reason: "
999 +client.accessDeniedReason();
1000 errorstream<<wide_to_narrow(error_message)<<std::endl;
1003 if(input->wasKeyDown(EscapeKey)){
1004 connect_aborted = true;
1005 infostream<<"Connect aborted [Escape]"<<std::endl;
1010 std::wostringstream ss;
1011 ss<<L"Connecting to server... (press Escape to cancel)\n";
1012 std::wstring animation = L"/-\\|";
1013 ss<<animation[(int)(time_counter/0.2)%4];
1014 draw_load_screen(ss.str(), driver, font);
1017 sleep_ms(1000*frametime);
1018 time_counter += frametime;
1021 catch(con::PeerNotFoundException &e)
1025 Handle failure to connect
1028 if(error_message == L"" && !connect_aborted){
1029 error_message = L"Connection failed";
1030 errorstream<<wide_to_narrow(error_message)<<std::endl;
1032 // Break out of client scope
1037 Wait until content has been received
1039 bool got_content = false;
1040 bool content_aborted = false;
1042 float frametime = 0.033;
1043 float time_counter = 0.0;
1045 while(device->run())
1047 // Update client and server
1048 client.step(frametime);
1050 server->step(frametime);
1053 if(client.texturesReceived() &&
1054 client.itemdefReceived() &&
1055 client.nodedefReceived()){
1060 if(!client.connectedAndInitialized()){
1061 error_message = L"Client disconnected";
1062 errorstream<<wide_to_narrow(error_message)<<std::endl;
1065 if(input->wasKeyDown(EscapeKey)){
1066 content_aborted = true;
1067 infostream<<"Connect aborted [Escape]"<<std::endl;
1072 std::wostringstream ss;
1073 ss<<L"Waiting content... (press Escape to cancel)\n";
1075 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
1076 ss<<L" Item definitions\n";
1077 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
1078 ss<<L" Node definitions\n";
1079 //ss<<(client.texturesReceived()?L"[X]":L"[ ]");
1080 ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
1083 draw_load_screen(ss.str(), driver, font);
1086 sleep_ms(1000*frametime);
1087 time_counter += frametime;
1092 if(error_message == L"" && !content_aborted){
1093 error_message = L"Something failed";
1094 errorstream<<wide_to_narrow(error_message)<<std::endl;
1096 // Break out of client scope
1101 After all content has been received:
1102 Update cached textures, meshes and materials
1104 client.afterContentReceived();
1107 Create the camera node
1109 Camera camera(smgr, draw_control, gamedef);
1110 if (!camera.successfullyCreated(error_message))
1113 f32 camera_yaw = 0; // "right/left"
1114 f32 camera_pitch = 0; // "up/down"
1120 Clouds *clouds = NULL;
1121 if(g_settings->getBool("enable_clouds"))
1123 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1131 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1137 FarMesh *farmesh = NULL;
1138 if(g_settings->getBool("enable_farmesh"))
1140 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1144 A copy of the local inventory
1146 Inventory local_inventory(itemdef);
1152 // First line of debug text
1153 gui::IGUIStaticText *guitext = guienv->addStaticText(
1155 core::rect<s32>(5, 5, 795, 5+text_height),
1157 // Second line of debug text
1158 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1160 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1162 // At the middle of the screen
1163 // Object infos are shown in this
1164 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1166 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1169 // Status text (displays info when showing and hiding GUI stuff, etc.)
1170 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1172 core::rect<s32>(0,0,0,0),
1174 guitext_status->setVisible(false);
1176 std::wstring statustext;
1177 float statustext_time = 0;
1180 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1182 core::rect<s32>(0,0,0,0),
1183 //false, false); // Disable word wrap as of now
1185 // Remove stale "recent" chat messages from previous connections
1186 chat_backend.clearRecentChat();
1187 // Chat backend and console
1188 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1190 // Profiler text (size is updated when text is updated)
1191 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1193 core::rect<s32>(0,0,0,0),
1195 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1196 guitext_profiler->setVisible(false);
1199 Some statistics are collected in these
1202 u32 beginscenetime = 0;
1204 u32 endscenetime = 0;
1206 float recent_turn_speed = 0.0;
1208 ProfilerGraph graph;
1209 // Initially clear the profiler
1210 Profiler::GraphValues dummyvalues;
1211 g_profiler->graphGet(dummyvalues);
1213 float nodig_delay_timer = 0.0;
1214 float dig_time = 0.0;
1216 PointedThing pointed_old;
1217 bool digging = false;
1218 bool ldown_for_dig = false;
1220 float damage_flash_timer = 0;
1221 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1223 const float object_hit_delay = 0.2;
1224 float object_hit_delay_timer = 0.0;
1225 float time_from_last_punch = 10;
1227 bool invert_mouse = g_settings->getBool("invert_mouse");
1229 bool respawn_menu_active = false;
1230 bool update_wielded_item_trigger = false;
1232 bool show_hud = true;
1233 bool show_chat = true;
1234 bool force_fog_off = false;
1235 bool disable_camera_update = false;
1236 bool show_debug = g_settings->getBool("show_debug");
1237 bool show_profiler_graph = false;
1238 u32 show_profiler = 0;
1239 u32 show_profiler_max = 3; // Number of pages
1241 float time_of_day = 0;
1242 float time_of_day_smooth = 0;
1248 bool first_loop_after_window_activation = true;
1250 // TODO: Convert the static interval timers to these
1251 // Interval limiter for profiler
1252 IntervalLimiter m_profiler_interval;
1254 // Time is in milliseconds
1255 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1256 // NOTE: So we have to use getTime() and call run()s between them
1257 u32 lasttime = device->getTimer()->getTime();
1261 if(device->run() == false || kill == true)
1264 // Time of frame without fps limit
1268 // not using getRealTime is necessary for wine
1269 u32 time = device->getTimer()->getTime();
1271 busytime_u32 = time - lasttime;
1274 busytime = busytime_u32 / 1000.0;
1277 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1279 // Necessary for device->getTimer()->getTime()
1287 float fps_max = g_settings->getFloat("fps_max");
1288 u32 frametime_min = 1000./fps_max;
1290 if(busytime_u32 < frametime_min)
1292 u32 sleeptime = frametime_min - busytime_u32;
1293 device->sleep(sleeptime);
1294 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1298 // Necessary for device->getTimer()->getTime()
1302 Time difference calculation
1304 f32 dtime; // in seconds
1306 u32 time = device->getTimer()->getTime();
1308 dtime = (time - lasttime) / 1000.0;
1313 g_profiler->graphAdd("mainloop_dtime", dtime);
1317 if(nodig_delay_timer >= 0)
1318 nodig_delay_timer -= dtime;
1319 if(object_hit_delay_timer >= 0)
1320 object_hit_delay_timer -= dtime;
1321 time_from_last_punch += dtime;
1323 g_profiler->add("Elapsed time", dtime);
1324 g_profiler->avg("FPS", 1./dtime);
1327 Time average and jitter calculation
1330 static f32 dtime_avg1 = 0.0;
1331 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1332 f32 dtime_jitter1 = dtime - dtime_avg1;
1334 static f32 dtime_jitter1_max_sample = 0.0;
1335 static f32 dtime_jitter1_max_fraction = 0.0;
1337 static f32 jitter1_max = 0.0;
1338 static f32 counter = 0.0;
1339 if(dtime_jitter1 > jitter1_max)
1340 jitter1_max = dtime_jitter1;
1345 dtime_jitter1_max_sample = jitter1_max;
1346 dtime_jitter1_max_fraction
1347 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1353 Busytime average and jitter calculation
1356 static f32 busytime_avg1 = 0.0;
1357 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1358 f32 busytime_jitter1 = busytime - busytime_avg1;
1360 static f32 busytime_jitter1_max_sample = 0.0;
1361 static f32 busytime_jitter1_min_sample = 0.0;
1363 static f32 jitter1_max = 0.0;
1364 static f32 jitter1_min = 0.0;
1365 static f32 counter = 0.0;
1366 if(busytime_jitter1 > jitter1_max)
1367 jitter1_max = busytime_jitter1;
1368 if(busytime_jitter1 < jitter1_min)
1369 jitter1_min = busytime_jitter1;
1373 busytime_jitter1_max_sample = jitter1_max;
1374 busytime_jitter1_min_sample = jitter1_min;
1381 Handle miscellaneous stuff
1384 if(client.accessDenied())
1386 error_message = L"Access denied. Reason: "
1387 +client.accessDeniedReason();
1388 errorstream<<wide_to_narrow(error_message)<<std::endl;
1392 if(g_gamecallback->disconnect_requested)
1394 g_gamecallback->disconnect_requested = false;
1398 if(g_gamecallback->changepassword_requested)
1400 (new GUIPasswordChange(guienv, guiroot, -1,
1401 &g_menumgr, &client))->drop();
1402 g_gamecallback->changepassword_requested = false;
1406 Process TextureSource's queue
1408 tsrc->processQueue();
1413 last_screensize = screensize;
1414 screensize = driver->getScreenSize();
1415 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1416 //bool screensize_changed = screensize != last_screensize;
1419 if(screensize.Y <= 800)
1420 hotbar_imagesize = 32;
1421 else if(screensize.Y <= 1280)
1422 hotbar_imagesize = 48;
1424 hotbar_imagesize = 64;
1426 // Hilight boxes collected during the loop and displayed
1427 core::list< core::aabbox3d<f32> > hilightboxes;
1430 std::wstring infotext;
1433 Debug info for client
1436 static float counter = 0.0;
1441 client.printDebugInfo(infostream);
1448 float profiler_print_interval =
1449 g_settings->getFloat("profiler_print_interval");
1450 bool print_to_log = true;
1451 if(profiler_print_interval == 0){
1452 print_to_log = false;
1453 profiler_print_interval = 5;
1455 if(m_profiler_interval.step(dtime, profiler_print_interval))
1458 infostream<<"Profiler:"<<std::endl;
1459 g_profiler->print(infostream);
1462 update_profiler_gui(guitext_profiler, font, text_height,
1463 show_profiler, show_profiler_max);
1465 g_profiler->clear();
1469 Direct handling of user input
1472 // Reset input if window not active or some menu is active
1473 if(device->isWindowActive() == false
1474 || noMenuActive() == false
1475 || guienv->hasFocus(gui_chat_console))
1480 // Input handler step() (used by the random input generator)
1484 Launch menus and trigger stuff according to keys
1486 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1488 // drop selected item
1489 IDropAction *a = new IDropAction();
1491 a->from_inv.setCurrentPlayer();
1492 a->from_list = "main";
1493 a->from_i = client.getPlayerItem();
1494 client.inventoryAction(a);
1496 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1498 infostream<<"the_game: "
1499 <<"Launching inventory"<<std::endl;
1501 GUIInventoryMenu *menu =
1502 new GUIInventoryMenu(guienv, guiroot, -1,
1503 &g_menumgr, v2s16(8,7),
1506 InventoryLocation inventoryloc;
1507 inventoryloc.setCurrentPlayer();
1509 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1510 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1511 "list", inventoryloc, "main",
1512 v2s32(0, 3), v2s32(8, 4)));
1513 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1514 "list", inventoryloc, "craft",
1515 v2s32(3, 0), v2s32(3, 3)));
1516 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1517 "list", inventoryloc, "craftpreview",
1518 v2s32(7, 1), v2s32(1, 1)));
1520 menu->setDrawSpec(draw_spec);
1524 else if(input->wasKeyDown(EscapeKey))
1526 infostream<<"the_game: "
1527 <<"Launching pause menu"<<std::endl;
1528 // It will delete itself by itself
1529 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1530 &g_menumgr, simple_singleplayer_mode))->drop();
1532 // Move mouse cursor on top of the disconnect button
1533 if(simple_singleplayer_mode)
1534 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1536 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1538 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1540 TextDest *dest = new TextDestChat(&client);
1542 (new GUITextInputMenu(guienv, guiroot, -1,
1546 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1548 TextDest *dest = new TextDestChat(&client);
1550 (new GUITextInputMenu(guienv, guiroot, -1,
1554 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1556 if (!gui_chat_console->isOpenInhibited())
1558 // Open up to over half of the screen
1559 gui_chat_console->openConsole(0.6);
1560 guienv->setFocus(gui_chat_console);
1563 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1565 if(g_settings->getBool("free_move"))
1567 g_settings->set("free_move","false");
1568 statustext = L"free_move disabled";
1569 statustext_time = 0;
1573 g_settings->set("free_move","true");
1574 statustext = L"free_move enabled";
1575 statustext_time = 0;
1578 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1580 if(g_settings->getBool("fast_move"))
1582 g_settings->set("fast_move","false");
1583 statustext = L"fast_move disabled";
1584 statustext_time = 0;
1588 g_settings->set("fast_move","true");
1589 statustext = L"fast_move enabled";
1590 statustext_time = 0;
1593 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1595 irr::video::IImage* const image = driver->createScreenShot();
1597 irr::c8 filename[256];
1598 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1599 g_settings->get("screenshot_path").c_str(),
1600 device->getTimer()->getRealTime());
1601 if (driver->writeImageToFile(image, filename)) {
1602 std::wstringstream sstr;
1603 sstr<<"Saved screenshot to '"<<filename<<"'";
1604 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1605 statustext = sstr.str();
1606 statustext_time = 0;
1608 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1613 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1615 show_hud = !show_hud;
1617 statustext = L"HUD shown";
1619 statustext = L"HUD hidden";
1620 statustext_time = 0;
1622 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1624 show_chat = !show_chat;
1626 statustext = L"Chat shown";
1628 statustext = L"Chat hidden";
1629 statustext_time = 0;
1631 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1633 force_fog_off = !force_fog_off;
1635 statustext = L"Fog disabled";
1637 statustext = L"Fog enabled";
1638 statustext_time = 0;
1640 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1642 disable_camera_update = !disable_camera_update;
1643 if(disable_camera_update)
1644 statustext = L"Camera update disabled";
1646 statustext = L"Camera update enabled";
1647 statustext_time = 0;
1649 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1651 // Initial / 3x toggle: Chat only
1652 // 1x toggle: Debug text with chat
1653 // 2x toggle: Debug text with profiler graph
1657 show_profiler_graph = false;
1658 statustext = L"Debug info shown";
1659 statustext_time = 0;
1661 else if(show_profiler_graph)
1664 show_profiler_graph = false;
1665 statustext = L"Debug info and profiler graph hidden";
1666 statustext_time = 0;
1670 show_profiler_graph = true;
1671 statustext = L"Profiler graph shown";
1672 statustext_time = 0;
1675 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1677 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1679 // FIXME: This updates the profiler with incomplete values
1680 update_profiler_gui(guitext_profiler, font, text_height,
1681 show_profiler, show_profiler_max);
1683 if(show_profiler != 0)
1685 std::wstringstream sstr;
1686 sstr<<"Profiler shown (page "<<show_profiler
1687 <<" of "<<show_profiler_max<<")";
1688 statustext = sstr.str();
1689 statustext_time = 0;
1693 statustext = L"Profiler hidden";
1694 statustext_time = 0;
1697 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1699 s16 range = g_settings->getS16("viewing_range_nodes_min");
1700 s16 range_new = range + 10;
1701 g_settings->set("viewing_range_nodes_min", itos(range_new));
1702 statustext = narrow_to_wide(
1703 "Minimum viewing range changed to "
1705 statustext_time = 0;
1707 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1709 s16 range = g_settings->getS16("viewing_range_nodes_min");
1710 s16 range_new = range - 10;
1713 g_settings->set("viewing_range_nodes_min",
1715 statustext = narrow_to_wide(
1716 "Minimum viewing range changed to "
1718 statustext_time = 0;
1721 // Handle QuicktuneShortcutter
1722 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1724 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1726 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1728 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1731 std::string msg = quicktune.getMessage();
1733 statustext = narrow_to_wide(msg);
1734 statustext_time = 0;
1738 // Item selection with mouse wheel
1739 u16 new_playeritem = client.getPlayerItem();
1741 s32 wheel = input->getMouseWheel();
1742 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1743 hotbar_itemcount-1);
1747 if(new_playeritem < max_item)
1754 if(new_playeritem > 0)
1757 new_playeritem = max_item;
1762 for(u16 i=0; i<10; i++)
1764 const KeyPress *kp = NumberKey + (i + 1) % 10;
1765 if(input->wasKeyDown(*kp))
1767 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1771 infostream<<"Selected item: "
1772 <<new_playeritem<<std::endl;
1777 // Viewing range selection
1778 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1780 draw_control.range_all = !draw_control.range_all;
1781 if(draw_control.range_all)
1783 infostream<<"Enabled full viewing range"<<std::endl;
1784 statustext = L"Enabled full viewing range";
1785 statustext_time = 0;
1789 infostream<<"Disabled full viewing range"<<std::endl;
1790 statustext = L"Disabled full viewing range";
1791 statustext_time = 0;
1795 // Print debug stacks
1796 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1798 dstream<<"-----------------------------------------"
1800 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1801 dstream<<"-----------------------------------------"
1803 debug_stacks_print();
1807 Mouse and camera control
1808 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1811 float turn_amount = 0;
1812 if((device->isWindowActive() && noMenuActive()) || random_input)
1816 // Mac OSX gets upset if this is set every frame
1817 if(device->getCursorControl()->isVisible())
1818 device->getCursorControl()->setVisible(false);
1821 if(first_loop_after_window_activation){
1822 //infostream<<"window active, first loop"<<std::endl;
1823 first_loop_after_window_activation = false;
1826 s32 dx = input->getMousePos().X - displaycenter.X;
1827 s32 dy = input->getMousePos().Y - displaycenter.Y;
1830 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1832 /*const float keyspeed = 500;
1833 if(input->isKeyDown(irr::KEY_UP))
1834 dy -= dtime * keyspeed;
1835 if(input->isKeyDown(irr::KEY_DOWN))
1836 dy += dtime * keyspeed;
1837 if(input->isKeyDown(irr::KEY_LEFT))
1838 dx -= dtime * keyspeed;
1839 if(input->isKeyDown(irr::KEY_RIGHT))
1840 dx += dtime * keyspeed;*/
1844 camera_pitch += dy*d;
1845 if(camera_pitch < -89.5) camera_pitch = -89.5;
1846 if(camera_pitch > 89.5) camera_pitch = 89.5;
1848 turn_amount = v2f(dx, dy).getLength() * d;
1850 input->setMousePos(displaycenter.X, displaycenter.Y);
1853 // Mac OSX gets upset if this is set every frame
1854 if(device->getCursorControl()->isVisible() == false)
1855 device->getCursorControl()->setVisible(true);
1857 //infostream<<"window inactive"<<std::endl;
1858 first_loop_after_window_activation = true;
1860 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1861 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1864 Player speed control
1876 PlayerControl control(
1877 input->isKeyDown(getKeySetting("keymap_forward")),
1878 input->isKeyDown(getKeySetting("keymap_backward")),
1879 input->isKeyDown(getKeySetting("keymap_left")),
1880 input->isKeyDown(getKeySetting("keymap_right")),
1881 input->isKeyDown(getKeySetting("keymap_jump")),
1882 input->isKeyDown(getKeySetting("keymap_special1")),
1883 input->isKeyDown(getKeySetting("keymap_sneak")),
1887 client.setPlayerControl(control);
1896 //TimeTaker timer("server->step(dtime)");
1897 server->step(dtime);
1905 //TimeTaker timer("client.step(dtime)");
1907 //client.step(dtime_avg1);
1911 // Read client events
1914 ClientEvent event = client.getClientEvent();
1915 if(event.type == CE_NONE)
1919 else if(event.type == CE_PLAYER_DAMAGE)
1921 //u16 damage = event.player_damage.amount;
1922 //infostream<<"Player damage: "<<damage<<std::endl;
1923 damage_flash_timer = 0.05;
1924 if(event.player_damage.amount >= 2){
1925 damage_flash_timer += 0.05 * event.player_damage.amount;
1928 else if(event.type == CE_PLAYER_FORCE_MOVE)
1930 camera_yaw = event.player_force_move.yaw;
1931 camera_pitch = event.player_force_move.pitch;
1933 else if(event.type == CE_DEATHSCREEN)
1935 if(respawn_menu_active)
1938 /*bool set_camera_point_target =
1939 event.deathscreen.set_camera_point_target;
1940 v3f camera_point_target;
1941 camera_point_target.X = event.deathscreen.camera_point_target_x;
1942 camera_point_target.Y = event.deathscreen.camera_point_target_y;
1943 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1944 MainRespawnInitiator *respawner =
1945 new MainRespawnInitiator(
1946 &respawn_menu_active, &client);
1947 GUIDeathScreen *menu =
1948 new GUIDeathScreen(guienv, guiroot, -1,
1949 &g_menumgr, respawner);
1952 chat_backend.addMessage(L"", L"You died.");
1954 /* Handle visualization */
1956 damage_flash_timer = 0;
1958 /*LocalPlayer* player = client.getLocalPlayer();
1959 player->setPosition(player->getPosition() + v3f(0,-BS,0));
1960 camera.update(player, busytime, screensize);*/
1962 else if(event.type == CE_TEXTURES_UPDATED)
1964 update_wielded_item_trigger = true;
1969 //TimeTaker //timer2("//timer2");
1972 For interaction purposes, get info about the held item
1974 - Is it a usable item?
1975 - Can it point to liquids?
1977 ItemStack playeritem;
1978 bool playeritem_usable = false;
1979 bool playeritem_liquids_pointable = false;
1981 InventoryList *mlist = local_inventory.getList("main");
1984 playeritem = mlist->getItem(client.getPlayerItem());
1985 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1986 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1989 ToolCapabilities playeritem_toolcap =
1990 playeritem.getToolCapabilities(itemdef);
1996 LocalPlayer* player = client.getEnv().getLocalPlayer();
1997 float full_punch_interval = playeritem_toolcap.full_punch_interval;
1998 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
1999 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
2000 camera.update(player, busytime, screensize, tool_reload_ratio);
2003 v3f player_position = player->getPosition();
2004 v3f camera_position = camera.getPosition();
2005 v3f camera_direction = camera.getDirection();
2006 f32 camera_fov = camera.getFovMax();
2008 if(!disable_camera_update){
2009 client.getEnv().getClientMap().updateCamera(camera_position,
2010 camera_direction, camera_fov);
2013 // Update sound listener
2014 sound->updateListener(camera.getCameraNode()->getPosition(),
2015 v3f(0,0,0), // velocity
2016 camera.getCameraNode()->getTarget(),
2017 camera.getCameraNode()->getUpVector());
2023 soundmaker.step(dtime);
2025 ClientMap &map = client.getEnv().getClientMap();
2026 MapNode n = map.getNodeNoEx(player->getStandingNodePos());
2027 soundmaker.m_player_step_sound = nodedef->get(n).sound_footstep;
2031 Calculate what block is the crosshair pointing to
2034 //u32 t1 = device->getTimer()->getRealTime();
2036 f32 d = 4; // max. distance
2037 core::line3d<f32> shootline(camera_position,
2038 camera_position + camera_direction * BS * (d+1));
2040 core::aabbox3d<f32> hilightbox;
2041 bool should_show_hilightbox = false;
2042 ClientActiveObject *selected_object = NULL;
2044 PointedThing pointed = getPointedThing(
2046 &client, player_position, camera_direction,
2047 camera_position, shootline, d,
2048 playeritem_liquids_pointable, !ldown_for_dig,
2050 hilightbox, should_show_hilightbox,
2053 if(pointed != pointed_old)
2055 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
2056 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
2062 if(should_show_hilightbox)
2063 hilightboxes.push_back(hilightbox);
2067 - releasing left mouse button
2068 - pointing away from node
2072 if(input->getLeftReleased())
2074 infostream<<"Left button released"
2075 <<" (stopped digging)"<<std::endl;
2078 else if(pointed != pointed_old)
2080 if (pointed.type == POINTEDTHING_NODE
2081 && pointed_old.type == POINTEDTHING_NODE
2082 && pointed.node_undersurface == pointed_old.node_undersurface)
2084 // Still pointing to the same node,
2085 // but a different face. Don't reset.
2089 infostream<<"Pointing away from node"
2090 <<" (stopped digging)"<<std::endl;
2096 client.interact(1, pointed_old);
2097 client.setCrack(-1, v3s16(0,0,0));
2101 if(!digging && ldown_for_dig && !input->getLeftState())
2103 ldown_for_dig = false;
2106 bool left_punch = false;
2108 if(playeritem_usable && input->getLeftState())
2110 if(input->getLeftClicked())
2111 client.interact(4, pointed);
2113 else if(pointed.type == POINTEDTHING_NODE)
2115 v3s16 nodepos = pointed.node_undersurface;
2116 v3s16 neighbourpos = pointed.node_abovesurface;
2119 Check information text of node
2122 ClientMap &map = client.getEnv().getClientMap();
2123 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2125 infotext = narrow_to_wide(meta->infoText());
2127 MapNode n = map.getNode(nodepos);
2128 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
2129 infotext = L"Unknown node: ";
2130 infotext += narrow_to_wide(nodedef->get(n).name);
2138 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2142 infostream<<"Started digging"<<std::endl;
2143 client.interact(0, pointed);
2145 ldown_for_dig = true;
2147 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2149 // Get digging parameters
2150 DigParams params = getDigParams(nodedef->get(n).groups,
2151 &playeritem_toolcap);
2152 // If can't dig, try hand
2153 if(!params.diggable){
2154 const ItemDefinition &hand = itemdef->get("");
2155 const ToolCapabilities *tp = hand.tool_capabilities;
2157 params = getDigParams(nodedef->get(n).groups, tp);
2160 float dig_time_complete = 0.0;
2162 if(params.diggable == false)
2164 // I guess nobody will wait for this long
2165 dig_time_complete = 10000000.0;
2169 dig_time_complete = params.time;
2172 if(dig_time_complete >= 0.001)
2174 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
2175 * dig_time/dig_time_complete);
2177 // This is for torches
2180 dig_index = CRACK_ANIMATION_LENGTH;
2183 // Don't show cracks if not diggable
2184 if(dig_time_complete >= 100000.0)
2187 else if(dig_index < CRACK_ANIMATION_LENGTH)
2189 //TimeTaker timer("client.setTempMod");
2190 //infostream<<"dig_index="<<dig_index<<std::endl;
2191 client.setCrack(dig_index, nodepos);
2195 infostream<<"Digging completed"<<std::endl;
2196 client.interact(2, pointed);
2197 client.setCrack(-1, v3s16(0,0,0));
2198 client.removeNode(nodepos);
2203 nodig_delay_timer = dig_time_complete
2204 / (float)CRACK_ANIMATION_LENGTH;
2206 // We don't want a corresponding delay to
2207 // very time consuming nodes
2208 if(nodig_delay_timer > 0.5)
2210 nodig_delay_timer = 0.5;
2212 // We want a slight delay to very little
2213 // time consuming nodes
2214 float mindelay = 0.15;
2215 if(nodig_delay_timer < mindelay)
2217 nodig_delay_timer = mindelay;
2223 camera.setDigging(0); // left click animation
2226 if(input->getRightClicked())
2228 infostream<<"Ground right-clicked"<<std::endl;
2230 // If metadata provides an inventory view, activate it
2231 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2233 infostream<<"Launching custom inventory view"<<std::endl;
2235 InventoryLocation inventoryloc;
2236 inventoryloc.setNodeMeta(nodepos);
2243 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2245 GUIInventoryMenu::makeDrawSpecArrayFromString(
2247 meta->getInventoryDrawSpecString(),
2250 GUIInventoryMenu *menu =
2251 new GUIInventoryMenu(guienv, guiroot, -1,
2252 &g_menumgr, invsize,
2254 menu->setDrawSpec(draw_spec);
2257 // If metadata provides text input, activate text input
2258 else if(meta && meta->allowsTextInput() && !random_input)
2260 infostream<<"Launching metadata text input"<<std::endl;
2262 // Get a new text for it
2264 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2266 std::wstring wtext = narrow_to_wide(meta->getText());
2268 (new GUITextInputMenu(guienv, guiroot, -1,
2272 // Otherwise report right click to server
2275 client.interact(3, pointed);
2276 camera.setDigging(1); // right click animation
2280 else if(pointed.type == POINTEDTHING_OBJECT)
2282 infotext = narrow_to_wide(selected_object->infoText());
2284 if(infotext == L"" && show_debug){
2285 infotext = narrow_to_wide(selected_object->debugInfoText());
2288 //if(input->getLeftClicked())
2289 if(input->getLeftState())
2291 bool do_punch = false;
2292 bool do_punch_damage = false;
2293 if(object_hit_delay_timer <= 0.0){
2295 do_punch_damage = true;
2296 object_hit_delay_timer = object_hit_delay;
2298 if(input->getLeftClicked()){
2302 infostream<<"Left-clicked object"<<std::endl;
2305 if(do_punch_damage){
2306 // Report direct punch
2307 v3f objpos = selected_object->getPosition();
2308 v3f dir = (objpos - player_position).normalize();
2310 bool disable_send = selected_object->directReportPunch(
2311 dir, &playeritem, time_from_last_punch);
2312 time_from_last_punch = 0;
2314 client.interact(0, pointed);
2317 else if(input->getRightClicked())
2319 infostream<<"Right-clicked object"<<std::endl;
2320 client.interact(3, pointed); // place
2323 else if(input->getLeftState())
2325 // When button is held down in air, show continuous animation
2329 pointed_old = pointed;
2331 if(left_punch || input->getLeftClicked())
2333 camera.setDigging(0); // left click animation
2336 input->resetLeftClicked();
2337 input->resetRightClicked();
2339 input->resetLeftReleased();
2340 input->resetRightReleased();
2343 Calculate stuff for drawing
2353 fog_range = BS*farmesh_range;
2357 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2359 if(draw_control.range_all)
2360 fog_range = 100000*BS;
2364 Calculate general brightness
2366 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2367 float time_brightness = (float)decode_light(
2368 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2369 float direct_brightness = 0;
2370 bool sunlight_seen = false;
2371 if(g_settings->getBool("free_move")){
2372 direct_brightness = time_brightness;
2373 sunlight_seen = true;
2375 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2376 float old_brightness = sky->getBrightness();
2377 direct_brightness = (float)client.getEnv().getClientMap()
2378 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2379 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2383 time_of_day = client.getEnv().getTimeOfDayF();
2385 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2386 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2387 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2388 time_of_day_smooth = time_of_day;
2390 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2391 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2392 + (time_of_day+1.0) * todsm;
2394 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2395 + time_of_day * todsm;
2397 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2400 float brightness = sky->getBrightness();
2401 video::SColor bgcolor = sky->getBgColor();
2402 video::SColor skycolor = sky->getSkyColor();
2408 if(sky->getCloudsVisible()){
2409 clouds->setVisible(true);
2410 clouds->step(dtime);
2411 clouds->update(v2f(player_position.X, player_position.Z),
2412 sky->getCloudColor());
2414 clouds->setVisible(false);
2423 farmesh_range = draw_control.wanted_range * 10;
2424 if(draw_control.range_all && farmesh_range < 500)
2425 farmesh_range = 500;
2426 if(farmesh_range > 1000)
2427 farmesh_range = 1000;
2429 farmesh->step(dtime);
2430 farmesh->update(v2f(player_position.X, player_position.Z),
2431 brightness, farmesh_range);
2438 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2442 video::EFT_FOG_LINEAR,
2454 video::EFT_FOG_LINEAR,
2464 Update gui stuff (0ms)
2467 //TimeTaker guiupdatetimer("Gui updating");
2469 const char program_name_and_version[] =
2470 "Minetest-c55 " VERSION_STRING;
2474 static float drawtime_avg = 0;
2475 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2476 /*static float beginscenetime_avg = 0;
2477 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2478 static float scenetime_avg = 0;
2479 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2480 static float endscenetime_avg = 0;
2481 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2484 snprintf(temptext, 300, "%s ("
2487 " drawtime=%.0f, dtime_jitter = % .1f %%"
2488 ", v_range = %.1f, RTT = %.3f",
2489 program_name_and_version,
2490 draw_control.range_all,
2492 dtime_jitter1_max_fraction * 100.0,
2493 draw_control.wanted_range,
2497 guitext->setText(narrow_to_wide(temptext).c_str());
2498 guitext->setVisible(true);
2500 else if(show_hud || show_chat)
2502 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2503 guitext->setVisible(true);
2507 guitext->setVisible(false);
2513 snprintf(temptext, 300,
2514 "(% .1f, % .1f, % .1f)"
2516 player_position.X/BS,
2517 player_position.Y/BS,
2518 player_position.Z/BS,
2519 wrapDegrees_0_360(camera_yaw));
2521 guitext2->setText(narrow_to_wide(temptext).c_str());
2522 guitext2->setVisible(true);
2526 guitext2->setVisible(false);
2530 guitext_info->setText(infotext.c_str());
2531 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2535 float statustext_time_max = 1.5;
2536 if(!statustext.empty())
2538 statustext_time += dtime;
2539 if(statustext_time >= statustext_time_max)
2542 statustext_time = 0;
2545 guitext_status->setText(statustext.c_str());
2546 guitext_status->setVisible(!statustext.empty());
2548 if(!statustext.empty())
2550 s32 status_y = screensize.Y - 130;
2551 core::rect<s32> rect(
2553 status_y - guitext_status->getTextHeight(),
2557 guitext_status->setRelativePosition(rect);
2560 video::SColor initial_color(255,0,0,0);
2561 if(guienv->getSkin())
2562 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2563 video::SColor final_color = initial_color;
2564 final_color.setAlpha(0);
2565 video::SColor fade_color =
2566 initial_color.getInterpolated_quadratic(
2569 pow(statustext_time / (float)statustext_time_max, 2.0f));
2570 guitext_status->setOverrideColor(fade_color);
2571 guitext_status->enableOverrideColor(true);
2576 Get chat messages from client
2579 // Get new messages from error log buffer
2580 while(!chat_log_error_buf.empty())
2582 chat_backend.addMessage(L"", narrow_to_wide(
2583 chat_log_error_buf.get()));
2585 // Get new messages from client
2586 std::wstring message;
2587 while(client.getChatMessage(message))
2589 chat_backend.addUnparsedMessage(message);
2591 // Remove old messages
2592 chat_backend.step(dtime);
2594 // Display all messages in a static text element
2595 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2596 std::wstring recent_chat = chat_backend.getRecentChat();
2597 guitext_chat->setText(recent_chat.c_str());
2599 // Update gui element size and position
2600 s32 chat_y = 5+(text_height+5);
2602 chat_y += (text_height+5);
2603 core::rect<s32> rect(
2607 chat_y + guitext_chat->getTextHeight()
2609 guitext_chat->setRelativePosition(rect);
2611 // Don't show chat if disabled or empty or profiler is enabled
2612 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2620 if(client.getPlayerItem() != new_playeritem)
2622 client.selectPlayerItem(new_playeritem);
2624 if(client.getLocalInventoryUpdated())
2626 //infostream<<"Updating local inventory"<<std::endl;
2627 client.getLocalInventory(local_inventory);
2629 update_wielded_item_trigger = true;
2631 if(update_wielded_item_trigger)
2633 update_wielded_item_trigger = false;
2634 // Update wielded tool
2635 InventoryList *mlist = local_inventory.getList("main");
2638 item = mlist->getItem(client.getPlayerItem());
2646 TimeTaker tt_draw("mainloop: draw");
2650 TimeTaker timer("beginScene");
2651 //driver->beginScene(false, true, bgcolor);
2652 //driver->beginScene(true, true, bgcolor);
2653 driver->beginScene(true, true, skycolor);
2654 beginscenetime = timer.stop(true);
2659 //infostream<<"smgr->drawAll()"<<std::endl;
2661 TimeTaker timer("smgr");
2663 scenetime = timer.stop(true);
2667 //TimeTaker timer9("auxiliary drawings");
2671 //TimeTaker //timer10("//timer10");
2677 driver->setMaterial(m);
2679 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2683 for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2684 i != hilightboxes.end(); i++)
2686 /*infostream<<"hilightbox min="
2687 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2689 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2691 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2700 // Warning: This clears the Z buffer.
2701 camera.drawWieldedTool();
2708 client.getEnv().getClientMap().renderPostFx();
2714 if(show_profiler_graph)
2716 graph.draw(10, screensize.Y - 10, driver, font);
2724 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2725 displaycenter + core::vector2d<s32>(10,0),
2726 video::SColor(255,255,255,255));
2727 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2728 displaycenter + core::vector2d<s32>(0,10),
2729 video::SColor(255,255,255,255));
2735 //TimeTaker //timer11("//timer11");
2748 draw_hotbar(driver, font, gamedef,
2749 v2s32(displaycenter.X, screensize.Y),
2750 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2751 client.getHP(), client.getPlayerItem());
2757 if(damage_flash_timer > 0.0)
2759 damage_flash_timer -= dtime;
2761 video::SColor color(128,255,0,0);
2762 driver->draw2DRectangle(color,
2763 core::rect<s32>(0,0,screensize.X,screensize.Y),
2771 TimeTaker timer("endScene");
2773 endscenetime = timer.stop(true);
2776 drawtime = tt_draw.stop(true);
2777 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2783 static s16 lastFPS = 0;
2784 //u16 fps = driver->getFPS();
2785 u16 fps = (1.0/dtime_avg1);
2789 core::stringw str = L"Minetest [";
2790 str += driver->getName();
2794 device->setWindowCaption(str.c_str());
2799 Log times and stuff for visualization
2801 Profiler::GraphValues values;
2802 g_profiler->graphGet(values);
2811 if(gui_chat_console)
2812 gui_chat_console->drop();
2815 Draw a "shutting down" screen, which will be shown while the map
2816 generator and other stuff quits
2819 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2820 draw_load_screen(L"Shutting down stuff...", driver, font);
2821 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2824 gui_shuttingdowntext->remove();*/
2827 chat_backend.addMessage(L"", L"# Disconnected.");
2828 chat_backend.addMessage(L"", L"");
2830 // Client scope (client is destructed before destructing *def and tsrc)