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"
62 Setting this to 1 enables a special camera mode that forces
63 the renderers to think that the camera statically points from
64 the starting place to a static direction.
66 This allows one to move around with the player and see what
67 is actually drawn behind solid things and behind the player.
69 #define FIELD_OF_VIEW_TEST 0
76 struct TextDestChat : public TextDest
78 TextDestChat(Client *client)
82 void gotText(std::wstring text)
84 m_client->typeChatMessage(text);
90 struct TextDestNodeMetadata : public TextDest
92 TextDestNodeMetadata(v3s16 p, Client *client)
97 void gotText(std::wstring text)
99 std::string ntext = wide_to_narrow(text);
100 infostream<<"Changing text of a sign node: "
102 m_client->sendSignNodeText(m_p, ntext);
109 /* Respawn menu callback */
111 class MainRespawnInitiator: public IRespawnInitiator
114 MainRespawnInitiator(bool *active, Client *client):
115 m_active(active), m_client(client)
122 m_client->sendRespawn();
132 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
134 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
135 Inventory *inventory, s32 halfheartcount, u16 playeritem)
137 InventoryList *mainlist = inventory->getList("main");
140 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
144 s32 padding = imgsize/12;
145 //s32 height = imgsize + padding*2;
146 s32 width = itemcount*(imgsize+padding*2);
148 // Position of upper left corner of bar
149 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
151 // Draw background color
152 /*core::rect<s32> barrect(0,0,width,height);
154 video::SColor bgcolor(255,128,128,128);
155 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
157 core::rect<s32> imgrect(0,0,imgsize,imgsize);
159 for(s32 i=0; i<itemcount; i++)
161 const ItemStack &item = mainlist->getItem(i);
163 core::rect<s32> rect = imgrect + pos
164 + v2s32(padding+i*(imgsize+padding*2), padding);
168 video::SColor c_outside(255,255,0,0);
169 //video::SColor c_outside(255,0,0,0);
170 //video::SColor c_inside(255,192,192,192);
171 s32 x1 = rect.UpperLeftCorner.X;
172 s32 y1 = rect.UpperLeftCorner.Y;
173 s32 x2 = rect.LowerRightCorner.X;
174 s32 y2 = rect.LowerRightCorner.Y;
175 // Black base borders
176 driver->draw2DRectangle(c_outside,
178 v2s32(x1 - padding, y1 - padding),
179 v2s32(x2 + padding, y1)
181 driver->draw2DRectangle(c_outside,
183 v2s32(x1 - padding, y2),
184 v2s32(x2 + padding, y2 + padding)
186 driver->draw2DRectangle(c_outside,
188 v2s32(x1 - padding, y1),
191 driver->draw2DRectangle(c_outside,
194 v2s32(x2 + padding, y2)
196 /*// Light inside borders
197 driver->draw2DRectangle(c_inside,
199 v2s32(x1 - padding/2, y1 - padding/2),
200 v2s32(x2 + padding/2, y1)
202 driver->draw2DRectangle(c_inside,
204 v2s32(x1 - padding/2, y2),
205 v2s32(x2 + padding/2, y2 + padding/2)
207 driver->draw2DRectangle(c_inside,
209 v2s32(x1 - padding/2, y1),
212 driver->draw2DRectangle(c_inside,
215 v2s32(x2 + padding/2, y2)
220 video::SColor bgcolor2(128,0,0,0);
221 driver->draw2DRectangle(bgcolor2, rect, NULL);
222 drawItemStack(driver, font, item, rect, NULL, gamedef);
228 video::ITexture *heart_texture =
229 gamedef->getTextureSource()->getTextureRaw("heart.png");
232 v2s32 p = pos + v2s32(0, -20);
233 for(s32 i=0; i<halfheartcount/2; i++)
235 const video::SColor color(255,255,255,255);
236 const video::SColor colors[] = {color,color,color,color};
237 core::rect<s32> rect(0,0,16,16);
239 driver->draw2DImage(heart_texture, rect,
240 core::rect<s32>(core::position2d<s32>(0,0),
241 core::dimension2di(heart_texture->getOriginalSize())),
245 if(halfheartcount % 2 == 1)
247 const video::SColor color(255,255,255,255);
248 const video::SColor colors[] = {color,color,color,color};
249 core::rect<s32> rect(0,0,16/2,16);
251 core::dimension2di srcd(heart_texture->getOriginalSize());
253 driver->draw2DImage(heart_texture, rect,
254 core::rect<s32>(core::position2d<s32>(0,0), srcd),
262 Check if a node is pointable
264 inline bool isPointableNode(const MapNode& n,
265 Client *client, bool liquids_pointable)
267 const ContentFeatures &features = client->getNodeDefManager()->get(n);
268 return features.pointable ||
269 (liquids_pointable && features.isLiquid());
273 Find what the player is pointing at
275 PointedThing getPointedThing(Client *client, v3f player_position,
276 v3f camera_direction, v3f camera_position,
277 core::line3d<f32> shootline, f32 d,
278 bool liquids_pointable,
279 bool look_for_object,
280 core::aabbox3d<f32> &hilightbox,
281 bool &should_show_hilightbox,
282 ClientActiveObject *&selected_object)
286 hilightbox = core::aabbox3d<f32>(0,0,0,0,0,0);
287 should_show_hilightbox = false;
288 selected_object = NULL;
290 INodeDefManager *nodedef = client->getNodeDefManager();
291 ClientMap &map = client->getEnv().getClientMap();
293 // First try to find a pointed at active object
296 selected_object = client->getSelectedActiveObject(d*BS,
297 camera_position, shootline);
299 if(selected_object != NULL)
301 core::aabbox3d<f32> *selection_box
302 = selected_object->getSelectionBox();
303 // Box should exist because object was returned in the
305 assert(selection_box);
307 v3f pos = selected_object->getPosition();
309 hilightbox = core::aabbox3d<f32>(
310 selection_box->MinEdge + pos,
311 selection_box->MaxEdge + pos
314 should_show_hilightbox = selected_object->doShowSelectionBox();
316 result.type = POINTEDTHING_OBJECT;
317 result.object_id = selected_object->getId();
321 // That didn't work, try to find a pointed at node
323 f32 mindistance = BS * 1001;
325 v3s16 pos_i = floatToInt(player_position, BS);
327 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
331 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
332 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
333 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
334 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
335 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
336 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
338 for(s16 y = ystart; y <= yend; y++)
339 for(s16 z = zstart; z <= zend; z++)
340 for(s16 x = xstart; x <= xend; x++)
345 n = map.getNode(v3s16(x,y,z));
347 catch(InvalidPositionException &e)
351 if(!isPointableNode(n, client, liquids_pointable))
355 v3f npf = intToFloat(np, BS);
360 v3s16(0,0,1), // back
362 v3s16(1,0,0), // right
363 v3s16(0,0,-1), // front
364 v3s16(0,-1,0), // bottom
365 v3s16(-1,0,0), // left
368 const ContentFeatures &f = nodedef->get(n);
370 if(f.selection_box.type == NODEBOX_FIXED)
372 core::aabbox3d<f32> box = f.selection_box.fixed;
376 v3s16 facedirs[6] = {
385 core::aabbox3d<f32> faceboxes[6] = {
388 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
389 box.MinEdge.X+d, box.MaxEdge.Y, box.MaxEdge.Z
393 box.MaxEdge.X-d, box.MinEdge.Y, box.MinEdge.Z,
394 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
398 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
399 box.MaxEdge.X, box.MinEdge.Y+d, box.MaxEdge.Z
403 box.MinEdge.X, box.MaxEdge.Y-d, box.MinEdge.Z,
404 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
408 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
409 box.MaxEdge.X, box.MaxEdge.Y, box.MinEdge.Z+d
413 box.MinEdge.X, box.MinEdge.Y, box.MaxEdge.Z-d,
414 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
418 for(u16 i=0; i<6; i++)
420 v3f facedir_f(facedirs[i].X, facedirs[i].Y, facedirs[i].Z);
421 v3f centerpoint = npf + facedir_f * BS/2;
422 f32 distance = (centerpoint - camera_position).getLength();
423 if(distance >= mindistance)
425 if(!faceboxes[i].intersectsWithLine(shootline))
427 result.type = POINTEDTHING_NODE;
428 result.node_undersurface = np;
429 result.node_abovesurface = np+facedirs[i];
430 mindistance = distance;
432 should_show_hilightbox = true;
435 else if(f.selection_box.type == NODEBOX_WALLMOUNTED)
437 v3s16 dir = n.getWallMountedDir(nodedef);
438 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
439 dir_f *= BS/2 - BS/6 - BS/20;
440 v3f cpf = npf + dir_f;
441 f32 distance = (cpf - camera_position).getLength();
443 core::aabbox3d<f32> box;
446 if(dir == v3s16(0,1,0)){
447 box = f.selection_box.wall_top;
450 else if(dir == v3s16(0,-1,0)){
451 box = f.selection_box.wall_bottom;
457 f.selection_box.wall_side.MinEdge,
458 f.selection_box.wall_side.MaxEdge
461 for(s32 i=0; i<2; i++)
463 if(dir == v3s16(-1,0,0))
464 vertices[i].rotateXZBy(0);
465 if(dir == v3s16(1,0,0))
466 vertices[i].rotateXZBy(180);
467 if(dir == v3s16(0,0,-1))
468 vertices[i].rotateXZBy(90);
469 if(dir == v3s16(0,0,1))
470 vertices[i].rotateXZBy(-90);
473 box = core::aabbox3d<f32>(vertices[0]);
474 box.addInternalPoint(vertices[1]);
480 if(distance < mindistance)
482 if(box.intersectsWithLine(shootline))
484 result.type = POINTEDTHING_NODE;
485 result.node_undersurface = np;
486 result.node_abovesurface = np;
487 mindistance = distance;
489 should_show_hilightbox = true;
493 else // NODEBOX_REGULAR
495 for(u16 i=0; i<6; i++)
497 v3f dir_f = v3f(dirs[i].X,
498 dirs[i].Y, dirs[i].Z);
499 v3f centerpoint = npf + dir_f * BS/2;
501 (centerpoint - camera_position).getLength();
503 if(distance < mindistance)
505 core::CMatrix4<f32> m;
506 m.buildRotateFromTo(v3f(0,0,1), dir_f);
508 // This is the back face
510 v3f(BS/2, BS/2, BS/2),
511 v3f(-BS/2, -BS/2, BS/2+d)
514 for(u16 j=0; j<2; j++)
516 m.rotateVect(corners[j]);
520 core::aabbox3d<f32> facebox(corners[0]);
521 facebox.addInternalPoint(corners[1]);
523 if(facebox.intersectsWithLine(shootline))
525 result.type = POINTEDTHING_NODE;
526 result.node_undersurface = np;
527 result.node_abovesurface = np + dirs[i];
528 mindistance = distance;
530 //hilightbox = facebox;
532 const float d = 0.502;
533 core::aabbox3d<f32> nodebox
534 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
535 v3f nodepos_f = intToFloat(np, BS);
536 nodebox.MinEdge += nodepos_f;
537 nodebox.MaxEdge += nodepos_f;
538 hilightbox = nodebox;
539 should_show_hilightbox = true;
541 } // if distance < mindistance
550 Draws a screen with a single text on it.
551 Text will be removed when the screen is drawn the next time.
553 /*gui::IGUIStaticText **/
554 void draw_load_screen(const std::wstring &text,
555 video::IVideoDriver* driver, gui::IGUIFont* font)
557 v2u32 screensize = driver->getScreenSize();
558 const wchar_t *loadingtext = text.c_str();
559 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
560 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
561 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
562 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
564 gui::IGUIStaticText *guitext = guienv->addStaticText(
565 loadingtext, textrect, false, false);
566 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
568 driver->beginScene(true, true, video::SColor(255,0,0,0));
577 /* Profiler display */
579 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
580 gui::IGUIFont *font, u32 text_height,
581 u32 show_profiler, u32 show_profiler_max)
583 if(show_profiler == 0)
585 guitext_profiler->setVisible(false);
590 std::ostringstream os(std::ios_base::binary);
591 g_profiler->printPage(os, show_profiler, show_profiler_max);
592 std::wstring text = narrow_to_wide(os.str());
593 guitext_profiler->setText(text.c_str());
594 guitext_profiler->setVisible(true);
596 s32 w = font->getDimension(text.c_str()).Width;
599 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
600 8+(text_height+5)*2 +
601 font->getDimension(text.c_str()).Height);
602 guitext_profiler->setRelativePosition(rect);
603 guitext_profiler->setVisible(true);
611 Profiler::GraphValues values;
617 Meta(float initial=0, video::SColor color=
618 video::SColor(255,255,255,255)):
624 std::list<Piece> m_log;
632 void put(const Profiler::GraphValues &values)
635 piece.values = values;
636 m_log.push_back(piece);
637 while(m_log.size() > m_log_max_size)
638 m_log.erase(m_log.begin());
641 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
642 gui::IGUIFont* font) const
644 std::map<std::string, Meta> m_meta;
645 for(std::list<Piece>::const_iterator k = m_log.begin();
646 k != m_log.end(); k++)
648 const Piece &piece = *k;
649 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
650 i != piece.values.end(); i++){
651 const std::string &id = i->first;
652 const float &value = i->second;
653 std::map<std::string, Meta>::iterator j =
655 if(j == m_meta.end()){
656 m_meta[id] = Meta(value);
659 if(value < j->second.min)
660 j->second.min = value;
661 if(value > j->second.max)
662 j->second.max = value;
667 static const video::SColor usable_colors[] = {
668 video::SColor(255,255,100,100),
669 video::SColor(255,90,225,90),
670 video::SColor(255,100,100,255),
671 video::SColor(255,255,150,50),
672 video::SColor(255,220,220,100)
674 static const u32 usable_colors_count =
675 sizeof(usable_colors) / sizeof(*usable_colors);
676 u32 next_color_i = 0;
677 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
678 i != m_meta.end(); i++){
679 Meta &meta = i->second;
680 video::SColor color(255,200,200,200);
681 if(next_color_i < usable_colors_count)
682 color = usable_colors[next_color_i++];
687 s32 textx = x_left + m_log_max_size + 15;
688 s32 textx2 = textx + 200 - 15;
692 u32 num_graphs = m_meta.size();
693 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
695 video::SColor bgcolor(120,0,0,0);
696 driver->draw2DRectangle(bgcolor, rect, NULL);
700 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
701 i != m_meta.end(); i++){
702 const std::string &id = i->first;
703 const Meta &meta = i->second;
705 s32 y = y_bottom - meta_i * 50;
706 float show_min = meta.min;
707 float show_max = meta.max;
708 if(show_min >= -0.0001 && show_max >= -0.0001){
709 if(show_min <= show_max * 0.5)
714 snprintf(buf, 10, "%.3g", show_max);
715 font->draw(narrow_to_wide(buf).c_str(),
716 core::rect<s32>(textx, y - graphh,
717 textx2, y - graphh + texth),
719 snprintf(buf, 10, "%.3g", show_min);
720 font->draw(narrow_to_wide(buf).c_str(),
721 core::rect<s32>(textx, y - texth,
724 font->draw(narrow_to_wide(id).c_str(),
725 core::rect<s32>(textx, y - graphh/2 - texth/2,
726 textx2, y - graphh/2 + texth/2),
729 s32 graph1h = graphh;
730 bool relativegraph = (show_min != 0 && show_min != show_max);
731 float lastscaledvalue = 0.0;
732 bool lastscaledvalue_exists = false;
733 for(std::list<Piece>::const_iterator j = m_log.begin();
734 j != m_log.end(); j++)
736 const Piece &piece = *j;
738 bool value_exists = false;
739 Profiler::GraphValues::const_iterator k =
740 piece.values.find(id);
741 if(k != piece.values.end()){
747 lastscaledvalue_exists = false;
750 float scaledvalue = 1.0;
751 if(show_max != show_min)
752 scaledvalue = (value - show_min) / (show_max - show_min);
753 if(scaledvalue == 1.0 && value == 0){
755 lastscaledvalue_exists = false;
759 if(lastscaledvalue_exists){
760 s32 ivalue1 = lastscaledvalue * graph1h;
761 s32 ivalue2 = scaledvalue * graph1h;
762 driver->draw2DLine(v2s32(x-1, graph1y - ivalue1),
763 v2s32(x, graph1y - ivalue2), meta.color);
765 lastscaledvalue = scaledvalue;
766 lastscaledvalue_exists = true;
768 s32 ivalue = scaledvalue * graph1h;
769 driver->draw2DLine(v2s32(x, graph1y),
770 v2s32(x, graph1y - ivalue), meta.color);
783 IrrlichtDevice *device,
786 std::string playername,
787 std::string password,
788 std::string address, // If "", local server is used
790 std::wstring &error_message,
791 std::string configpath,
792 ChatBackend &chat_backend,
793 const SubgameSpec &gamespec, // Used for local game,
794 bool simple_singleplayer_mode
797 video::IVideoDriver* driver = device->getVideoDriver();
798 scene::ISceneManager* smgr = device->getSceneManager();
800 // Calculate text height using the font
801 u32 text_height = font->getDimension(L"Random test string").Height;
803 v2u32 screensize(0,0);
804 v2u32 last_screensize(0,0);
805 screensize = driver->getScreenSize();
807 const s32 hotbar_itemcount = 8;
808 //const s32 hotbar_imagesize = 36;
809 //const s32 hotbar_imagesize = 64;
810 s32 hotbar_imagesize = 48;
813 Draw "Loading" screen
816 draw_load_screen(L"Loading...", driver, font);
818 // Create texture source
819 IWritableTextureSource *tsrc = createTextureSource(device);
821 // These will be filled by data received from the server
822 // Create item definition manager
823 IWritableItemDefManager *itemdef = createItemDefManager();
824 // Create node definition manager
825 IWritableNodeDefManager *nodedef = createNodeDefManager();
827 // Add chat log output for errors to be shown in chat
828 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
830 // Create UI for modifying quicktune values
831 QuicktuneShortcutter quicktune;
835 SharedPtr will delete it when it goes out of scope.
837 SharedPtr<Server> server;
839 draw_load_screen(L"Creating server...", driver, font);
840 infostream<<"Creating server"<<std::endl;
841 server = new Server(map_dir, configpath, gamespec,
842 simple_singleplayer_mode);
846 do{ // Client scope (breakable do-while(0))
852 draw_load_screen(L"Creating client...", driver, font);
853 infostream<<"Creating client"<<std::endl;
855 MapDrawControl draw_control;
857 Client client(device, playername.c_str(), password, draw_control,
858 tsrc, itemdef, nodedef);
860 // Client acts as our GameDef
861 IGameDef *gamedef = &client;
863 draw_load_screen(L"Resolving address...", driver, font);
864 Address connect_address(0,0,0,0, port);
867 //connect_address.Resolve("localhost");
868 connect_address.setAddress(127,0,0,1);
870 connect_address.Resolve(address.c_str());
872 catch(ResolveError &e)
874 error_message = L"Couldn't resolve address";
875 errorstream<<wide_to_narrow(error_message)<<std::endl;
876 // Break out of client scope
881 Attempt to connect to the server
884 infostream<<"Connecting to server at ";
885 connect_address.print(&infostream);
886 infostream<<std::endl;
887 client.connect(connect_address);
890 Wait for server to accept connection
892 bool could_connect = false;
893 bool connect_aborted = false;
895 float frametime = 0.033;
896 float time_counter = 0.0;
900 // Update client and server
901 client.step(frametime);
903 server->step(frametime);
906 if(client.connectedAndInitialized()){
907 could_connect = true;
911 if(client.accessDenied()){
912 error_message = L"Access denied. Reason: "
913 +client.accessDeniedReason();
914 errorstream<<wide_to_narrow(error_message)<<std::endl;
917 if(input->wasKeyDown(EscapeKey)){
918 connect_aborted = true;
919 infostream<<"Connect aborted [Escape]"<<std::endl;
924 std::wostringstream ss;
925 ss<<L"Connecting to server... (press Escape to cancel)\n";
926 std::wstring animation = L"/-\\|";
927 ss<<animation[(int)(time_counter/0.2)%4];
928 draw_load_screen(ss.str(), driver, font);
931 sleep_ms(1000*frametime);
932 time_counter += frametime;
935 catch(con::PeerNotFoundException &e)
939 Handle failure to connect
942 if(error_message == L"" && !connect_aborted){
943 error_message = L"Connection failed";
944 errorstream<<wide_to_narrow(error_message)<<std::endl;
946 // Break out of client scope
951 Wait until content has been received
953 bool got_content = false;
954 bool content_aborted = false;
956 float frametime = 0.033;
957 float time_counter = 0.0;
961 // Update client and server
962 client.step(frametime);
964 server->step(frametime);
967 if(client.texturesReceived() &&
968 client.itemdefReceived() &&
969 client.nodedefReceived()){
974 if(!client.connectedAndInitialized()){
975 error_message = L"Client disconnected";
976 errorstream<<wide_to_narrow(error_message)<<std::endl;
979 if(input->wasKeyDown(EscapeKey)){
980 content_aborted = true;
981 infostream<<"Connect aborted [Escape]"<<std::endl;
986 std::wostringstream ss;
987 ss<<L"Waiting content... (press Escape to cancel)\n";
989 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
990 ss<<L" Item definitions\n";
991 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
992 ss<<L" Node definitions\n";
993 //ss<<(client.texturesReceived()?L"[X]":L"[ ]");
994 ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
997 draw_load_screen(ss.str(), driver, font);
1000 sleep_ms(1000*frametime);
1001 time_counter += frametime;
1006 if(error_message == L"" && !content_aborted){
1007 error_message = L"Something failed";
1008 errorstream<<wide_to_narrow(error_message)<<std::endl;
1010 // Break out of client scope
1015 After all content has been received:
1016 Update cached textures, meshes and materials
1018 client.afterContentReceived();
1021 Create the camera node
1023 Camera camera(smgr, draw_control);
1024 if (!camera.successfullyCreated(error_message))
1027 f32 camera_yaw = 0; // "right/left"
1028 f32 camera_pitch = 0; // "up/down"
1034 Clouds *clouds = NULL;
1035 if(g_settings->getBool("enable_clouds"))
1037 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1045 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1051 FarMesh *farmesh = NULL;
1052 if(g_settings->getBool("enable_farmesh"))
1054 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1058 A copy of the local inventory
1060 Inventory local_inventory(itemdef);
1066 // First line of debug text
1067 gui::IGUIStaticText *guitext = guienv->addStaticText(
1069 core::rect<s32>(5, 5, 795, 5+text_height),
1071 // Second line of debug text
1072 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1074 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1076 // At the middle of the screen
1077 // Object infos are shown in this
1078 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1080 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1083 // Status text (displays info when showing and hiding GUI stuff, etc.)
1084 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1086 core::rect<s32>(0,0,0,0),
1088 guitext_status->setVisible(false);
1090 std::wstring statustext;
1091 float statustext_time = 0;
1094 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1096 core::rect<s32>(0,0,0,0),
1097 //false, false); // Disable word wrap as of now
1099 // Remove stale "recent" chat messages from previous connections
1100 chat_backend.clearRecentChat();
1101 // Chat backend and console
1102 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1104 // Profiler text (size is updated when text is updated)
1105 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1107 core::rect<s32>(0,0,0,0),
1109 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1110 guitext_profiler->setVisible(false);
1113 Some statistics are collected in these
1116 u32 beginscenetime = 0;
1118 u32 endscenetime = 0;
1120 float recent_turn_speed = 0.0;
1122 ProfilerGraph graph;
1123 // Initially clear the profiler
1124 Profiler::GraphValues dummyvalues;
1125 g_profiler->graphGet(dummyvalues);
1127 float nodig_delay_timer = 0.0;
1128 float dig_time = 0.0;
1130 PointedThing pointed_old;
1131 bool digging = false;
1132 bool ldown_for_dig = false;
1134 float damage_flash_timer = 0;
1135 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1137 const float object_hit_delay = 0.2;
1138 float object_hit_delay_timer = 0.0;
1139 float time_from_last_punch = 10;
1141 bool invert_mouse = g_settings->getBool("invert_mouse");
1143 bool respawn_menu_active = false;
1144 bool update_wielded_item_trigger = false;
1146 bool show_hud = true;
1147 bool show_chat = true;
1148 bool force_fog_off = false;
1149 bool disable_camera_update = false;
1150 bool show_debug = g_settings->getBool("show_debug");
1151 bool show_profiler_graph = false;
1152 u32 show_profiler = 0;
1153 u32 show_profiler_max = 3; // Number of pages
1155 float time_of_day = 0;
1156 float time_of_day_smooth = 0;
1162 bool first_loop_after_window_activation = true;
1164 // TODO: Convert the static interval timers to these
1165 // Interval limiter for profiler
1166 IntervalLimiter m_profiler_interval;
1168 // Time is in milliseconds
1169 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1170 // NOTE: So we have to use getTime() and call run()s between them
1171 u32 lasttime = device->getTimer()->getTime();
1175 if(device->run() == false || kill == true)
1178 // Time of frame without fps limit
1182 // not using getRealTime is necessary for wine
1183 u32 time = device->getTimer()->getTime();
1185 busytime_u32 = time - lasttime;
1188 busytime = busytime_u32 / 1000.0;
1191 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1193 // Necessary for device->getTimer()->getTime()
1201 float fps_max = g_settings->getFloat("fps_max");
1202 u32 frametime_min = 1000./fps_max;
1204 if(busytime_u32 < frametime_min)
1206 u32 sleeptime = frametime_min - busytime_u32;
1207 device->sleep(sleeptime);
1208 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1212 // Necessary for device->getTimer()->getTime()
1216 Time difference calculation
1218 f32 dtime; // in seconds
1220 u32 time = device->getTimer()->getTime();
1222 dtime = (time - lasttime) / 1000.0;
1227 g_profiler->graphAdd("mainloop_dtime", dtime);
1231 if(nodig_delay_timer >= 0)
1232 nodig_delay_timer -= dtime;
1233 if(object_hit_delay_timer >= 0)
1234 object_hit_delay_timer -= dtime;
1235 time_from_last_punch += dtime;
1237 g_profiler->add("Elapsed time", dtime);
1238 g_profiler->avg("FPS", 1./dtime);
1241 Time average and jitter calculation
1244 static f32 dtime_avg1 = 0.0;
1245 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1246 f32 dtime_jitter1 = dtime - dtime_avg1;
1248 static f32 dtime_jitter1_max_sample = 0.0;
1249 static f32 dtime_jitter1_max_fraction = 0.0;
1251 static f32 jitter1_max = 0.0;
1252 static f32 counter = 0.0;
1253 if(dtime_jitter1 > jitter1_max)
1254 jitter1_max = dtime_jitter1;
1259 dtime_jitter1_max_sample = jitter1_max;
1260 dtime_jitter1_max_fraction
1261 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1267 Busytime average and jitter calculation
1270 static f32 busytime_avg1 = 0.0;
1271 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1272 f32 busytime_jitter1 = busytime - busytime_avg1;
1274 static f32 busytime_jitter1_max_sample = 0.0;
1275 static f32 busytime_jitter1_min_sample = 0.0;
1277 static f32 jitter1_max = 0.0;
1278 static f32 jitter1_min = 0.0;
1279 static f32 counter = 0.0;
1280 if(busytime_jitter1 > jitter1_max)
1281 jitter1_max = busytime_jitter1;
1282 if(busytime_jitter1 < jitter1_min)
1283 jitter1_min = busytime_jitter1;
1287 busytime_jitter1_max_sample = jitter1_max;
1288 busytime_jitter1_min_sample = jitter1_min;
1295 Handle miscellaneous stuff
1298 if(client.accessDenied())
1300 error_message = L"Access denied. Reason: "
1301 +client.accessDeniedReason();
1302 errorstream<<wide_to_narrow(error_message)<<std::endl;
1306 if(g_gamecallback->disconnect_requested)
1308 g_gamecallback->disconnect_requested = false;
1312 if(g_gamecallback->changepassword_requested)
1314 (new GUIPasswordChange(guienv, guiroot, -1,
1315 &g_menumgr, &client))->drop();
1316 g_gamecallback->changepassword_requested = false;
1320 Process TextureSource's queue
1322 tsrc->processQueue();
1327 last_screensize = screensize;
1328 screensize = driver->getScreenSize();
1329 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1330 //bool screensize_changed = screensize != last_screensize;
1333 if(screensize.Y <= 800)
1334 hotbar_imagesize = 32;
1335 else if(screensize.Y <= 1280)
1336 hotbar_imagesize = 48;
1338 hotbar_imagesize = 64;
1340 // Hilight boxes collected during the loop and displayed
1341 core::list< core::aabbox3d<f32> > hilightboxes;
1344 std::wstring infotext;
1347 Debug info for client
1350 static float counter = 0.0;
1355 client.printDebugInfo(infostream);
1362 float profiler_print_interval =
1363 g_settings->getFloat("profiler_print_interval");
1364 bool print_to_log = true;
1365 if(profiler_print_interval == 0){
1366 print_to_log = false;
1367 profiler_print_interval = 5;
1369 if(m_profiler_interval.step(dtime, profiler_print_interval))
1372 infostream<<"Profiler:"<<std::endl;
1373 g_profiler->print(infostream);
1376 update_profiler_gui(guitext_profiler, font, text_height,
1377 show_profiler, show_profiler_max);
1379 g_profiler->clear();
1383 Direct handling of user input
1386 // Reset input if window not active or some menu is active
1387 if(device->isWindowActive() == false
1388 || noMenuActive() == false
1389 || guienv->hasFocus(gui_chat_console))
1394 // Input handler step() (used by the random input generator)
1398 Launch menus and trigger stuff according to keys
1400 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1402 // drop selected item
1403 IDropAction *a = new IDropAction();
1405 a->from_inv.setCurrentPlayer();
1406 a->from_list = "main";
1407 a->from_i = client.getPlayerItem();
1408 client.inventoryAction(a);
1410 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1412 infostream<<"the_game: "
1413 <<"Launching inventory"<<std::endl;
1415 GUIInventoryMenu *menu =
1416 new GUIInventoryMenu(guienv, guiroot, -1,
1417 &g_menumgr, v2s16(8,7),
1420 InventoryLocation inventoryloc;
1421 inventoryloc.setCurrentPlayer();
1423 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1424 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1425 "list", inventoryloc, "main",
1426 v2s32(0, 3), v2s32(8, 4)));
1427 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1428 "list", inventoryloc, "craft",
1429 v2s32(3, 0), v2s32(3, 3)));
1430 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1431 "list", inventoryloc, "craftpreview",
1432 v2s32(7, 1), v2s32(1, 1)));
1434 menu->setDrawSpec(draw_spec);
1438 else if(input->wasKeyDown(EscapeKey))
1440 infostream<<"the_game: "
1441 <<"Launching pause menu"<<std::endl;
1442 // It will delete itself by itself
1443 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1444 &g_menumgr, simple_singleplayer_mode))->drop();
1446 // Move mouse cursor on top of the disconnect button
1447 if(simple_singleplayer_mode)
1448 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1450 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1452 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1454 TextDest *dest = new TextDestChat(&client);
1456 (new GUITextInputMenu(guienv, guiroot, -1,
1460 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1462 TextDest *dest = new TextDestChat(&client);
1464 (new GUITextInputMenu(guienv, guiroot, -1,
1468 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1470 if (!gui_chat_console->isOpenInhibited())
1472 // Open up to over half of the screen
1473 gui_chat_console->openConsole(0.6);
1474 guienv->setFocus(gui_chat_console);
1477 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1479 if(g_settings->getBool("free_move"))
1481 g_settings->set("free_move","false");
1482 statustext = L"free_move disabled";
1483 statustext_time = 0;
1487 g_settings->set("free_move","true");
1488 statustext = L"free_move enabled";
1489 statustext_time = 0;
1492 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1494 if(g_settings->getBool("fast_move"))
1496 g_settings->set("fast_move","false");
1497 statustext = L"fast_move disabled";
1498 statustext_time = 0;
1502 g_settings->set("fast_move","true");
1503 statustext = L"fast_move enabled";
1504 statustext_time = 0;
1507 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1509 irr::video::IImage* const image = driver->createScreenShot();
1511 irr::c8 filename[256];
1512 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1513 g_settings->get("screenshot_path").c_str(),
1514 device->getTimer()->getRealTime());
1515 if (driver->writeImageToFile(image, filename)) {
1516 std::wstringstream sstr;
1517 sstr<<"Saved screenshot to '"<<filename<<"'";
1518 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1519 statustext = sstr.str();
1520 statustext_time = 0;
1522 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1527 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1529 show_hud = !show_hud;
1531 statustext = L"HUD shown";
1533 statustext = L"HUD hidden";
1534 statustext_time = 0;
1536 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1538 show_chat = !show_chat;
1540 statustext = L"Chat shown";
1542 statustext = L"Chat hidden";
1543 statustext_time = 0;
1545 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1547 force_fog_off = !force_fog_off;
1549 statustext = L"Fog disabled";
1551 statustext = L"Fog enabled";
1552 statustext_time = 0;
1554 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1556 disable_camera_update = !disable_camera_update;
1557 if(disable_camera_update)
1558 statustext = L"Camera update disabled";
1560 statustext = L"Camera update enabled";
1561 statustext_time = 0;
1563 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1565 // Initial / 3x toggle: Chat only
1566 // 1x toggle: Debug text with chat
1567 // 2x toggle: Debug text with profiler graph
1571 show_profiler_graph = false;
1572 statustext = L"Debug info shown";
1573 statustext_time = 0;
1575 else if(show_profiler_graph)
1578 show_profiler_graph = false;
1579 statustext = L"Debug info and profiler graph hidden";
1580 statustext_time = 0;
1584 show_profiler_graph = true;
1585 statustext = L"Profiler graph shown";
1586 statustext_time = 0;
1589 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1591 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1593 // FIXME: This updates the profiler with incomplete values
1594 update_profiler_gui(guitext_profiler, font, text_height,
1595 show_profiler, show_profiler_max);
1597 if(show_profiler != 0)
1599 std::wstringstream sstr;
1600 sstr<<"Profiler shown (page "<<show_profiler
1601 <<" of "<<show_profiler_max<<")";
1602 statustext = sstr.str();
1603 statustext_time = 0;
1607 statustext = L"Profiler hidden";
1608 statustext_time = 0;
1611 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1613 s16 range = g_settings->getS16("viewing_range_nodes_min");
1614 s16 range_new = range + 10;
1615 g_settings->set("viewing_range_nodes_min", itos(range_new));
1616 statustext = narrow_to_wide(
1617 "Minimum viewing range changed to "
1619 statustext_time = 0;
1621 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1623 s16 range = g_settings->getS16("viewing_range_nodes_min");
1624 s16 range_new = range - 10;
1627 g_settings->set("viewing_range_nodes_min",
1629 statustext = narrow_to_wide(
1630 "Minimum viewing range changed to "
1632 statustext_time = 0;
1635 // Handle QuicktuneShortcutter
1636 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1638 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1640 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1642 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1645 std::string msg = quicktune.getMessage();
1647 statustext = narrow_to_wide(msg);
1648 statustext_time = 0;
1652 // Item selection with mouse wheel
1653 u16 new_playeritem = client.getPlayerItem();
1655 s32 wheel = input->getMouseWheel();
1656 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1657 hotbar_itemcount-1);
1661 if(new_playeritem < max_item)
1668 if(new_playeritem > 0)
1671 new_playeritem = max_item;
1676 for(u16 i=0; i<10; i++)
1678 const KeyPress *kp = NumberKey + (i + 1) % 10;
1679 if(input->wasKeyDown(*kp))
1681 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1685 infostream<<"Selected item: "
1686 <<new_playeritem<<std::endl;
1691 // Viewing range selection
1692 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1694 draw_control.range_all = !draw_control.range_all;
1695 if(draw_control.range_all)
1697 infostream<<"Enabled full viewing range"<<std::endl;
1698 statustext = L"Enabled full viewing range";
1699 statustext_time = 0;
1703 infostream<<"Disabled full viewing range"<<std::endl;
1704 statustext = L"Disabled full viewing range";
1705 statustext_time = 0;
1709 // Print debug stacks
1710 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1712 dstream<<"-----------------------------------------"
1714 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1715 dstream<<"-----------------------------------------"
1717 debug_stacks_print();
1721 Mouse and camera control
1722 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1725 float turn_amount = 0;
1726 if((device->isWindowActive() && noMenuActive()) || random_input)
1730 // Mac OSX gets upset if this is set every frame
1731 if(device->getCursorControl()->isVisible())
1732 device->getCursorControl()->setVisible(false);
1735 if(first_loop_after_window_activation){
1736 //infostream<<"window active, first loop"<<std::endl;
1737 first_loop_after_window_activation = false;
1740 s32 dx = input->getMousePos().X - displaycenter.X;
1741 s32 dy = input->getMousePos().Y - displaycenter.Y;
1744 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1746 /*const float keyspeed = 500;
1747 if(input->isKeyDown(irr::KEY_UP))
1748 dy -= dtime * keyspeed;
1749 if(input->isKeyDown(irr::KEY_DOWN))
1750 dy += dtime * keyspeed;
1751 if(input->isKeyDown(irr::KEY_LEFT))
1752 dx -= dtime * keyspeed;
1753 if(input->isKeyDown(irr::KEY_RIGHT))
1754 dx += dtime * keyspeed;*/
1758 camera_pitch += dy*d;
1759 if(camera_pitch < -89.5) camera_pitch = -89.5;
1760 if(camera_pitch > 89.5) camera_pitch = 89.5;
1762 turn_amount = v2f(dx, dy).getLength() * d;
1764 input->setMousePos(displaycenter.X, displaycenter.Y);
1767 // Mac OSX gets upset if this is set every frame
1768 if(device->getCursorControl()->isVisible() == false)
1769 device->getCursorControl()->setVisible(true);
1771 //infostream<<"window inactive"<<std::endl;
1772 first_loop_after_window_activation = true;
1774 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1775 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1778 Player speed control
1790 PlayerControl control(
1791 input->isKeyDown(getKeySetting("keymap_forward")),
1792 input->isKeyDown(getKeySetting("keymap_backward")),
1793 input->isKeyDown(getKeySetting("keymap_left")),
1794 input->isKeyDown(getKeySetting("keymap_right")),
1795 input->isKeyDown(getKeySetting("keymap_jump")),
1796 input->isKeyDown(getKeySetting("keymap_special1")),
1797 input->isKeyDown(getKeySetting("keymap_sneak")),
1801 client.setPlayerControl(control);
1810 //TimeTaker timer("server->step(dtime)");
1811 server->step(dtime);
1819 //TimeTaker timer("client.step(dtime)");
1821 //client.step(dtime_avg1);
1825 // Read client events
1828 ClientEvent event = client.getClientEvent();
1829 if(event.type == CE_NONE)
1833 else if(event.type == CE_PLAYER_DAMAGE)
1835 //u16 damage = event.player_damage.amount;
1836 //infostream<<"Player damage: "<<damage<<std::endl;
1837 damage_flash_timer = 0.05;
1838 if(event.player_damage.amount >= 2){
1839 damage_flash_timer += 0.05 * event.player_damage.amount;
1842 else if(event.type == CE_PLAYER_FORCE_MOVE)
1844 camera_yaw = event.player_force_move.yaw;
1845 camera_pitch = event.player_force_move.pitch;
1847 else if(event.type == CE_DEATHSCREEN)
1849 if(respawn_menu_active)
1852 /*bool set_camera_point_target =
1853 event.deathscreen.set_camera_point_target;
1854 v3f camera_point_target;
1855 camera_point_target.X = event.deathscreen.camera_point_target_x;
1856 camera_point_target.Y = event.deathscreen.camera_point_target_y;
1857 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1858 MainRespawnInitiator *respawner =
1859 new MainRespawnInitiator(
1860 &respawn_menu_active, &client);
1861 GUIDeathScreen *menu =
1862 new GUIDeathScreen(guienv, guiroot, -1,
1863 &g_menumgr, respawner);
1866 chat_backend.addMessage(L"", L"You died.");
1868 /* Handle visualization */
1870 damage_flash_timer = 0;
1872 /*LocalPlayer* player = client.getLocalPlayer();
1873 player->setPosition(player->getPosition() + v3f(0,-BS,0));
1874 camera.update(player, busytime, screensize);*/
1876 else if(event.type == CE_TEXTURES_UPDATED)
1878 update_wielded_item_trigger = true;
1883 //TimeTaker //timer2("//timer2");
1886 For interaction purposes, get info about the held item
1888 - Is it a usable item?
1889 - Can it point to liquids?
1891 ItemStack playeritem;
1892 bool playeritem_usable = false;
1893 bool playeritem_liquids_pointable = false;
1895 InventoryList *mlist = local_inventory.getList("main");
1898 playeritem = mlist->getItem(client.getPlayerItem());
1899 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1900 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1903 ToolCapabilities playeritem_toolcap =
1904 playeritem.getToolCapabilities(itemdef);
1910 LocalPlayer* player = client.getEnv().getLocalPlayer();
1911 float full_punch_interval = playeritem_toolcap.full_punch_interval;
1912 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
1913 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
1914 camera.update(player, busytime, screensize, tool_reload_ratio);
1917 v3f player_position = player->getPosition();
1918 v3f camera_position = camera.getPosition();
1919 v3f camera_direction = camera.getDirection();
1920 f32 camera_fov = camera.getFovMax();
1922 if(!disable_camera_update){
1923 client.getEnv().getClientMap().updateCamera(camera_position,
1924 camera_direction, camera_fov);
1928 //TimeTaker //timer3("//timer3");
1931 Calculate what block is the crosshair pointing to
1934 //u32 t1 = device->getTimer()->getRealTime();
1936 f32 d = 4; // max. distance
1937 core::line3d<f32> shootline(camera_position,
1938 camera_position + camera_direction * BS * (d+1));
1940 core::aabbox3d<f32> hilightbox;
1941 bool should_show_hilightbox = false;
1942 ClientActiveObject *selected_object = NULL;
1944 PointedThing pointed = getPointedThing(
1946 &client, player_position, camera_direction,
1947 camera_position, shootline, d,
1948 playeritem_liquids_pointable, !ldown_for_dig,
1950 hilightbox, should_show_hilightbox,
1953 if(pointed != pointed_old)
1955 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
1956 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
1962 if(should_show_hilightbox)
1963 hilightboxes.push_back(hilightbox);
1967 - releasing left mouse button
1968 - pointing away from node
1972 if(input->getLeftReleased())
1974 infostream<<"Left button released"
1975 <<" (stopped digging)"<<std::endl;
1978 else if(pointed != pointed_old)
1980 if (pointed.type == POINTEDTHING_NODE
1981 && pointed_old.type == POINTEDTHING_NODE
1982 && pointed.node_undersurface == pointed_old.node_undersurface)
1984 // Still pointing to the same node,
1985 // but a different face. Don't reset.
1989 infostream<<"Pointing away from node"
1990 <<" (stopped digging)"<<std::endl;
1996 client.interact(1, pointed_old);
1997 client.setCrack(-1, v3s16(0,0,0));
2001 if(!digging && ldown_for_dig && !input->getLeftState())
2003 ldown_for_dig = false;
2006 bool left_punch = false;
2008 if(playeritem_usable && input->getLeftState())
2010 if(input->getLeftClicked())
2011 client.interact(4, pointed);
2013 else if(pointed.type == POINTEDTHING_NODE)
2015 v3s16 nodepos = pointed.node_undersurface;
2016 v3s16 neighbourpos = pointed.node_abovesurface;
2019 Check information text of node
2022 ClientMap &map = client.getEnv().getClientMap();
2023 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2025 infotext = narrow_to_wide(meta->infoText());
2027 MapNode n = map.getNode(nodepos);
2028 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
2029 infotext = L"Unknown node: ";
2030 infotext += narrow_to_wide(nodedef->get(n).name);
2038 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2042 infostream<<"Started digging"<<std::endl;
2043 client.interact(0, pointed);
2045 ldown_for_dig = true;
2047 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2049 // Get digging parameters
2050 DigParams params = getDigParams(nodedef->get(n).groups,
2051 &playeritem_toolcap);
2052 // If can't dig, try hand
2053 if(!params.diggable){
2054 const ItemDefinition &hand = itemdef->get("");
2055 const ToolCapabilities *tp = hand.tool_capabilities;
2057 params = getDigParams(nodedef->get(n).groups, tp);
2060 float dig_time_complete = 0.0;
2062 if(params.diggable == false)
2064 // I guess nobody will wait for this long
2065 dig_time_complete = 10000000.0;
2069 dig_time_complete = params.time;
2072 if(dig_time_complete >= 0.001)
2074 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
2075 * dig_time/dig_time_complete);
2077 // This is for torches
2080 dig_index = CRACK_ANIMATION_LENGTH;
2083 // Don't show cracks if not diggable
2084 if(dig_time_complete >= 100000.0)
2087 else if(dig_index < CRACK_ANIMATION_LENGTH)
2089 //TimeTaker timer("client.setTempMod");
2090 //infostream<<"dig_index="<<dig_index<<std::endl;
2091 client.setCrack(dig_index, nodepos);
2095 infostream<<"Digging completed"<<std::endl;
2096 client.interact(2, pointed);
2097 client.setCrack(-1, v3s16(0,0,0));
2098 client.removeNode(nodepos);
2103 nodig_delay_timer = dig_time_complete
2104 / (float)CRACK_ANIMATION_LENGTH;
2106 // We don't want a corresponding delay to
2107 // very time consuming nodes
2108 if(nodig_delay_timer > 0.5)
2110 nodig_delay_timer = 0.5;
2112 // We want a slight delay to very little
2113 // time consuming nodes
2114 float mindelay = 0.15;
2115 if(nodig_delay_timer < mindelay)
2117 nodig_delay_timer = mindelay;
2123 camera.setDigging(0); // left click animation
2126 if(input->getRightClicked())
2128 infostream<<"Ground right-clicked"<<std::endl;
2130 // If metadata provides an inventory view, activate it
2131 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2133 infostream<<"Launching custom inventory view"<<std::endl;
2135 InventoryLocation inventoryloc;
2136 inventoryloc.setNodeMeta(nodepos);
2143 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2145 GUIInventoryMenu::makeDrawSpecArrayFromString(
2147 meta->getInventoryDrawSpecString(),
2150 GUIInventoryMenu *menu =
2151 new GUIInventoryMenu(guienv, guiroot, -1,
2152 &g_menumgr, invsize,
2154 menu->setDrawSpec(draw_spec);
2157 // If metadata provides text input, activate text input
2158 else if(meta && meta->allowsTextInput() && !random_input)
2160 infostream<<"Launching metadata text input"<<std::endl;
2162 // Get a new text for it
2164 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2166 std::wstring wtext = narrow_to_wide(meta->getText());
2168 (new GUITextInputMenu(guienv, guiroot, -1,
2172 // Otherwise report right click to server
2175 client.interact(3, pointed);
2176 camera.setDigging(1); // right click animation
2180 else if(pointed.type == POINTEDTHING_OBJECT)
2182 infotext = narrow_to_wide(selected_object->infoText());
2184 if(infotext == L"" && show_debug){
2185 infotext = narrow_to_wide(selected_object->debugInfoText());
2188 //if(input->getLeftClicked())
2189 if(input->getLeftState())
2191 bool do_punch = false;
2192 bool do_punch_damage = false;
2193 if(object_hit_delay_timer <= 0.0){
2195 do_punch_damage = true;
2196 object_hit_delay_timer = object_hit_delay;
2198 if(input->getLeftClicked()){
2202 infostream<<"Left-clicked object"<<std::endl;
2205 if(do_punch_damage){
2206 // Report direct punch
2207 v3f objpos = selected_object->getPosition();
2208 v3f dir = (objpos - player_position).normalize();
2210 bool disable_send = selected_object->directReportPunch(
2211 dir, &playeritem, time_from_last_punch);
2212 time_from_last_punch = 0;
2214 client.interact(0, pointed);
2217 else if(input->getRightClicked())
2219 infostream<<"Right-clicked object"<<std::endl;
2220 client.interact(3, pointed); // place
2223 else if(input->getLeftState())
2225 // When button is held down in air, show continuous animation
2229 pointed_old = pointed;
2231 if(left_punch || input->getLeftClicked())
2233 camera.setDigging(0); // left click animation
2236 input->resetLeftClicked();
2237 input->resetRightClicked();
2239 input->resetLeftReleased();
2240 input->resetRightReleased();
2243 Calculate stuff for drawing
2253 fog_range = BS*farmesh_range;
2257 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2259 if(draw_control.range_all)
2260 fog_range = 100000*BS;
2264 Calculate general brightness
2266 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2267 float time_brightness = (float)decode_light(
2268 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2269 float direct_brightness = 0;
2270 bool sunlight_seen = false;
2271 if(g_settings->getBool("free_move")){
2272 direct_brightness = time_brightness;
2273 sunlight_seen = true;
2275 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2276 float old_brightness = sky->getBrightness();
2277 direct_brightness = (float)client.getEnv().getClientMap()
2278 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2279 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2283 time_of_day = client.getEnv().getTimeOfDayF();
2285 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2286 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2287 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2288 time_of_day_smooth = time_of_day;
2290 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2291 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2292 + (time_of_day+1.0) * todsm;
2294 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2295 + time_of_day * todsm;
2297 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2300 float brightness = sky->getBrightness();
2301 video::SColor bgcolor = sky->getBgColor();
2302 video::SColor skycolor = sky->getSkyColor();
2308 if(sky->getCloudsVisible()){
2309 clouds->setVisible(true);
2310 clouds->step(dtime);
2311 clouds->update(v2f(player_position.X, player_position.Z),
2312 sky->getCloudColor());
2314 clouds->setVisible(false);
2323 farmesh_range = draw_control.wanted_range * 10;
2324 if(draw_control.range_all && farmesh_range < 500)
2325 farmesh_range = 500;
2326 if(farmesh_range > 1000)
2327 farmesh_range = 1000;
2329 farmesh->step(dtime);
2330 farmesh->update(v2f(player_position.X, player_position.Z),
2331 brightness, farmesh_range);
2338 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2342 video::EFT_FOG_LINEAR,
2354 video::EFT_FOG_LINEAR,
2364 Update gui stuff (0ms)
2367 //TimeTaker guiupdatetimer("Gui updating");
2369 const char program_name_and_version[] =
2370 "Minetest-c55 " VERSION_STRING;
2374 static float drawtime_avg = 0;
2375 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2376 /*static float beginscenetime_avg = 0;
2377 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2378 static float scenetime_avg = 0;
2379 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2380 static float endscenetime_avg = 0;
2381 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2384 snprintf(temptext, 300, "%s ("
2387 " drawtime=%.0f, dtime_jitter = % .1f %%"
2388 ", v_range = %.1f, RTT = %.3f",
2389 program_name_and_version,
2390 draw_control.range_all,
2392 dtime_jitter1_max_fraction * 100.0,
2393 draw_control.wanted_range,
2397 guitext->setText(narrow_to_wide(temptext).c_str());
2398 guitext->setVisible(true);
2400 else if(show_hud || show_chat)
2402 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2403 guitext->setVisible(true);
2407 guitext->setVisible(false);
2413 snprintf(temptext, 300,
2414 "(% .1f, % .1f, % .1f)"
2416 player_position.X/BS,
2417 player_position.Y/BS,
2418 player_position.Z/BS,
2419 wrapDegrees_0_360(camera_yaw));
2421 guitext2->setText(narrow_to_wide(temptext).c_str());
2422 guitext2->setVisible(true);
2426 guitext2->setVisible(false);
2430 guitext_info->setText(infotext.c_str());
2431 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2435 float statustext_time_max = 1.5;
2436 if(!statustext.empty())
2438 statustext_time += dtime;
2439 if(statustext_time >= statustext_time_max)
2442 statustext_time = 0;
2445 guitext_status->setText(statustext.c_str());
2446 guitext_status->setVisible(!statustext.empty());
2448 if(!statustext.empty())
2450 s32 status_y = screensize.Y - 130;
2451 core::rect<s32> rect(
2453 status_y - guitext_status->getTextHeight(),
2457 guitext_status->setRelativePosition(rect);
2460 video::SColor initial_color(255,0,0,0);
2461 if(guienv->getSkin())
2462 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2463 video::SColor final_color = initial_color;
2464 final_color.setAlpha(0);
2465 video::SColor fade_color =
2466 initial_color.getInterpolated_quadratic(
2469 pow(statustext_time / (float)statustext_time_max, 2.0f));
2470 guitext_status->setOverrideColor(fade_color);
2471 guitext_status->enableOverrideColor(true);
2476 Get chat messages from client
2479 // Get new messages from error log buffer
2480 while(!chat_log_error_buf.empty())
2482 chat_backend.addMessage(L"", narrow_to_wide(
2483 chat_log_error_buf.get()));
2485 // Get new messages from client
2486 std::wstring message;
2487 while(client.getChatMessage(message))
2489 chat_backend.addUnparsedMessage(message);
2491 // Remove old messages
2492 chat_backend.step(dtime);
2494 // Display all messages in a static text element
2495 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2496 std::wstring recent_chat = chat_backend.getRecentChat();
2497 guitext_chat->setText(recent_chat.c_str());
2499 // Update gui element size and position
2500 s32 chat_y = 5+(text_height+5);
2502 chat_y += (text_height+5);
2503 core::rect<s32> rect(
2507 chat_y + guitext_chat->getTextHeight()
2509 guitext_chat->setRelativePosition(rect);
2511 // Don't show chat if disabled or empty or profiler is enabled
2512 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2520 if(client.getPlayerItem() != new_playeritem)
2522 client.selectPlayerItem(new_playeritem);
2524 if(client.getLocalInventoryUpdated())
2526 //infostream<<"Updating local inventory"<<std::endl;
2527 client.getLocalInventory(local_inventory);
2529 update_wielded_item_trigger = true;
2531 if(update_wielded_item_trigger)
2533 update_wielded_item_trigger = false;
2534 // Update wielded tool
2535 InventoryList *mlist = local_inventory.getList("main");
2538 item = mlist->getItem(client.getPlayerItem());
2539 camera.wield(item, gamedef);
2546 TimeTaker tt_draw("mainloop: draw");
2550 TimeTaker timer("beginScene");
2551 //driver->beginScene(false, true, bgcolor);
2552 //driver->beginScene(true, true, bgcolor);
2553 driver->beginScene(true, true, skycolor);
2554 beginscenetime = timer.stop(true);
2559 //infostream<<"smgr->drawAll()"<<std::endl;
2561 TimeTaker timer("smgr");
2563 scenetime = timer.stop(true);
2567 //TimeTaker timer9("auxiliary drawings");
2571 //TimeTaker //timer10("//timer10");
2577 driver->setMaterial(m);
2579 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2583 for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2584 i != hilightboxes.end(); i++)
2586 /*infostream<<"hilightbox min="
2587 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2589 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2591 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2600 // Warning: This clears the Z buffer.
2601 camera.drawWieldedTool();
2608 client.getEnv().getClientMap().renderPostFx();
2614 if(show_profiler_graph)
2616 graph.draw(10, screensize.Y - 10, driver, font);
2624 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2625 displaycenter + core::vector2d<s32>(10,0),
2626 video::SColor(255,255,255,255));
2627 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2628 displaycenter + core::vector2d<s32>(0,10),
2629 video::SColor(255,255,255,255));
2635 //TimeTaker //timer11("//timer11");
2648 draw_hotbar(driver, font, gamedef,
2649 v2s32(displaycenter.X, screensize.Y),
2650 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2651 client.getHP(), client.getPlayerItem());
2657 if(damage_flash_timer > 0.0)
2659 damage_flash_timer -= dtime;
2661 video::SColor color(128,255,0,0);
2662 driver->draw2DRectangle(color,
2663 core::rect<s32>(0,0,screensize.X,screensize.Y),
2671 TimeTaker timer("endScene");
2673 endscenetime = timer.stop(true);
2676 drawtime = tt_draw.stop(true);
2677 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2683 static s16 lastFPS = 0;
2684 //u16 fps = driver->getFPS();
2685 u16 fps = (1.0/dtime_avg1);
2689 core::stringw str = L"Minetest [";
2690 str += driver->getName();
2694 device->setWindowCaption(str.c_str());
2699 Log times and stuff for visualization
2701 Profiler::GraphValues values;
2702 g_profiler->graphGet(values);
2711 if(gui_chat_console)
2712 gui_chat_console->drop();
2715 Draw a "shutting down" screen, which will be shown while the map
2716 generator and other stuff quits
2719 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2720 draw_load_screen(L"Shutting down stuff...", driver, font);
2721 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2724 gui_shuttingdowntext->remove();*/
2727 chat_backend.addMessage(L"", L"# Disconnected.");
2728 chat_backend.addMessage(L"", L"");
2730 // Client scope (client is destructed before destructing *def and tsrc)