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"
61 Setting this to 1 enables a special camera mode that forces
62 the renderers to think that the camera statically points from
63 the starting place to a static direction.
65 This allows one to move around with the player and see what
66 is actually drawn behind solid things and behind the player.
68 #define FIELD_OF_VIEW_TEST 0
75 struct TextDestChat : public TextDest
77 TextDestChat(Client *client)
81 void gotText(std::wstring text)
83 m_client->typeChatMessage(text);
89 struct TextDestNodeMetadata : public TextDest
91 TextDestNodeMetadata(v3s16 p, Client *client)
96 void gotText(std::wstring text)
98 std::string ntext = wide_to_narrow(text);
99 infostream<<"Changing text of a sign node: "
101 m_client->sendSignNodeText(m_p, ntext);
108 /* Respawn menu callback */
110 class MainRespawnInitiator: public IRespawnInitiator
113 MainRespawnInitiator(bool *active, Client *client):
114 m_active(active), m_client(client)
121 m_client->sendRespawn();
131 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
133 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
134 Inventory *inventory, s32 halfheartcount, u16 playeritem)
136 InventoryList *mainlist = inventory->getList("main");
139 errorstream<<"draw_hotbar(): mainlist == NULL"<<std::endl;
143 s32 padding = imgsize/12;
144 //s32 height = imgsize + padding*2;
145 s32 width = itemcount*(imgsize+padding*2);
147 // Position of upper left corner of bar
148 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
150 // Draw background color
151 /*core::rect<s32> barrect(0,0,width,height);
153 video::SColor bgcolor(255,128,128,128);
154 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
156 core::rect<s32> imgrect(0,0,imgsize,imgsize);
158 for(s32 i=0; i<itemcount; i++)
160 const ItemStack &item = mainlist->getItem(i);
162 core::rect<s32> rect = imgrect + pos
163 + v2s32(padding+i*(imgsize+padding*2), padding);
167 video::SColor c_outside(255,255,0,0);
168 //video::SColor c_outside(255,0,0,0);
169 //video::SColor c_inside(255,192,192,192);
170 s32 x1 = rect.UpperLeftCorner.X;
171 s32 y1 = rect.UpperLeftCorner.Y;
172 s32 x2 = rect.LowerRightCorner.X;
173 s32 y2 = rect.LowerRightCorner.Y;
174 // Black base borders
175 driver->draw2DRectangle(c_outside,
177 v2s32(x1 - padding, y1 - padding),
178 v2s32(x2 + padding, y1)
180 driver->draw2DRectangle(c_outside,
182 v2s32(x1 - padding, y2),
183 v2s32(x2 + padding, y2 + padding)
185 driver->draw2DRectangle(c_outside,
187 v2s32(x1 - padding, y1),
190 driver->draw2DRectangle(c_outside,
193 v2s32(x2 + padding, y2)
195 /*// Light inside borders
196 driver->draw2DRectangle(c_inside,
198 v2s32(x1 - padding/2, y1 - padding/2),
199 v2s32(x2 + padding/2, y1)
201 driver->draw2DRectangle(c_inside,
203 v2s32(x1 - padding/2, y2),
204 v2s32(x2 + padding/2, y2 + padding/2)
206 driver->draw2DRectangle(c_inside,
208 v2s32(x1 - padding/2, y1),
211 driver->draw2DRectangle(c_inside,
214 v2s32(x2 + padding/2, y2)
219 video::SColor bgcolor2(128,0,0,0);
220 driver->draw2DRectangle(bgcolor2, rect, NULL);
221 drawItemStack(driver, font, item, rect, NULL, gamedef);
227 video::ITexture *heart_texture =
228 gamedef->getTextureSource()->getTextureRaw("heart.png");
231 v2s32 p = pos + v2s32(0, -20);
232 for(s32 i=0; i<halfheartcount/2; i++)
234 const video::SColor color(255,255,255,255);
235 const video::SColor colors[] = {color,color,color,color};
236 core::rect<s32> rect(0,0,16,16);
238 driver->draw2DImage(heart_texture, rect,
239 core::rect<s32>(core::position2d<s32>(0,0),
240 core::dimension2di(heart_texture->getOriginalSize())),
244 if(halfheartcount % 2 == 1)
246 const video::SColor color(255,255,255,255);
247 const video::SColor colors[] = {color,color,color,color};
248 core::rect<s32> rect(0,0,16/2,16);
250 core::dimension2di srcd(heart_texture->getOriginalSize());
252 driver->draw2DImage(heart_texture, rect,
253 core::rect<s32>(core::position2d<s32>(0,0), srcd),
261 Check if a node is pointable
263 inline bool isPointableNode(const MapNode& n,
264 Client *client, bool liquids_pointable)
266 const ContentFeatures &features = client->getNodeDefManager()->get(n);
267 return features.pointable ||
268 (liquids_pointable && features.isLiquid());
272 Find what the player is pointing at
274 PointedThing getPointedThing(Client *client, v3f player_position,
275 v3f camera_direction, v3f camera_position,
276 core::line3d<f32> shootline, f32 d,
277 bool liquids_pointable,
278 bool look_for_object,
279 core::aabbox3d<f32> &hilightbox,
280 bool &should_show_hilightbox,
281 ClientActiveObject *&selected_object)
285 hilightbox = core::aabbox3d<f32>(0,0,0,0,0,0);
286 should_show_hilightbox = false;
287 selected_object = NULL;
289 INodeDefManager *nodedef = client->getNodeDefManager();
290 ClientMap &map = client->getEnv().getClientMap();
292 // First try to find a pointed at active object
295 selected_object = client->getSelectedActiveObject(d*BS,
296 camera_position, shootline);
298 if(selected_object != NULL)
300 core::aabbox3d<f32> *selection_box
301 = selected_object->getSelectionBox();
302 // Box should exist because object was returned in the
304 assert(selection_box);
306 v3f pos = selected_object->getPosition();
308 hilightbox = core::aabbox3d<f32>(
309 selection_box->MinEdge + pos,
310 selection_box->MaxEdge + pos
313 should_show_hilightbox = selected_object->doShowSelectionBox();
315 result.type = POINTEDTHING_OBJECT;
316 result.object_id = selected_object->getId();
320 // That didn't work, try to find a pointed at node
322 f32 mindistance = BS * 1001;
324 v3s16 pos_i = floatToInt(player_position, BS);
326 /*infostream<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
330 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
331 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
332 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
333 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
334 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
335 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
337 for(s16 y = ystart; y <= yend; y++)
338 for(s16 z = zstart; z <= zend; z++)
339 for(s16 x = xstart; x <= xend; x++)
344 n = map.getNode(v3s16(x,y,z));
346 catch(InvalidPositionException &e)
350 if(!isPointableNode(n, client, liquids_pointable))
354 v3f npf = intToFloat(np, BS);
359 v3s16(0,0,1), // back
361 v3s16(1,0,0), // right
362 v3s16(0,0,-1), // front
363 v3s16(0,-1,0), // bottom
364 v3s16(-1,0,0), // left
367 const ContentFeatures &f = nodedef->get(n);
369 if(f.selection_box.type == NODEBOX_FIXED)
371 core::aabbox3d<f32> box = f.selection_box.fixed;
375 v3s16 facedirs[6] = {
384 core::aabbox3d<f32> faceboxes[6] = {
387 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
388 box.MinEdge.X+d, box.MaxEdge.Y, box.MaxEdge.Z
392 box.MaxEdge.X-d, box.MinEdge.Y, box.MinEdge.Z,
393 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
397 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
398 box.MaxEdge.X, box.MinEdge.Y+d, box.MaxEdge.Z
402 box.MinEdge.X, box.MaxEdge.Y-d, box.MinEdge.Z,
403 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
407 box.MinEdge.X, box.MinEdge.Y, box.MinEdge.Z,
408 box.MaxEdge.X, box.MaxEdge.Y, box.MinEdge.Z+d
412 box.MinEdge.X, box.MinEdge.Y, box.MaxEdge.Z-d,
413 box.MaxEdge.X, box.MaxEdge.Y, box.MaxEdge.Z
417 for(u16 i=0; i<6; i++)
419 v3f facedir_f(facedirs[i].X, facedirs[i].Y, facedirs[i].Z);
420 v3f centerpoint = npf + facedir_f * BS/2;
421 f32 distance = (centerpoint - camera_position).getLength();
422 if(distance >= mindistance)
424 if(!faceboxes[i].intersectsWithLine(shootline))
426 result.type = POINTEDTHING_NODE;
427 result.node_undersurface = np;
428 result.node_abovesurface = np+facedirs[i];
429 mindistance = distance;
431 should_show_hilightbox = true;
434 else if(f.selection_box.type == NODEBOX_WALLMOUNTED)
436 v3s16 dir = n.getWallMountedDir(nodedef);
437 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
438 dir_f *= BS/2 - BS/6 - BS/20;
439 v3f cpf = npf + dir_f;
440 f32 distance = (cpf - camera_position).getLength();
442 core::aabbox3d<f32> box;
445 if(dir == v3s16(0,1,0)){
446 box = f.selection_box.wall_top;
449 else if(dir == v3s16(0,-1,0)){
450 box = f.selection_box.wall_bottom;
456 f.selection_box.wall_side.MinEdge,
457 f.selection_box.wall_side.MaxEdge
460 for(s32 i=0; i<2; i++)
462 if(dir == v3s16(-1,0,0))
463 vertices[i].rotateXZBy(0);
464 if(dir == v3s16(1,0,0))
465 vertices[i].rotateXZBy(180);
466 if(dir == v3s16(0,0,-1))
467 vertices[i].rotateXZBy(90);
468 if(dir == v3s16(0,0,1))
469 vertices[i].rotateXZBy(-90);
472 box = core::aabbox3d<f32>(vertices[0]);
473 box.addInternalPoint(vertices[1]);
479 if(distance < mindistance)
481 if(box.intersectsWithLine(shootline))
483 result.type = POINTEDTHING_NODE;
484 result.node_undersurface = np;
485 result.node_abovesurface = np;
486 mindistance = distance;
488 should_show_hilightbox = true;
492 else // NODEBOX_REGULAR
494 for(u16 i=0; i<6; i++)
496 v3f dir_f = v3f(dirs[i].X,
497 dirs[i].Y, dirs[i].Z);
498 v3f centerpoint = npf + dir_f * BS/2;
500 (centerpoint - camera_position).getLength();
502 if(distance < mindistance)
504 core::CMatrix4<f32> m;
505 m.buildRotateFromTo(v3f(0,0,1), dir_f);
507 // This is the back face
509 v3f(BS/2, BS/2, BS/2),
510 v3f(-BS/2, -BS/2, BS/2+d)
513 for(u16 j=0; j<2; j++)
515 m.rotateVect(corners[j]);
519 core::aabbox3d<f32> facebox(corners[0]);
520 facebox.addInternalPoint(corners[1]);
522 if(facebox.intersectsWithLine(shootline))
524 result.type = POINTEDTHING_NODE;
525 result.node_undersurface = np;
526 result.node_abovesurface = np + dirs[i];
527 mindistance = distance;
529 //hilightbox = facebox;
531 const float d = 0.502;
532 core::aabbox3d<f32> nodebox
533 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
534 v3f nodepos_f = intToFloat(np, BS);
535 nodebox.MinEdge += nodepos_f;
536 nodebox.MaxEdge += nodepos_f;
537 hilightbox = nodebox;
538 should_show_hilightbox = true;
540 } // if distance < mindistance
549 Draws a screen with a single text on it.
550 Text will be removed when the screen is drawn the next time.
552 /*gui::IGUIStaticText **/
553 void draw_load_screen(const std::wstring &text,
554 video::IVideoDriver* driver, gui::IGUIFont* font)
556 v2u32 screensize = driver->getScreenSize();
557 const wchar_t *loadingtext = text.c_str();
558 core::vector2d<u32> textsize_u = font->getDimension(loadingtext);
559 core::vector2d<s32> textsize(textsize_u.X,textsize_u.Y);
560 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
561 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
563 gui::IGUIStaticText *guitext = guienv->addStaticText(
564 loadingtext, textrect, false, false);
565 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
567 driver->beginScene(true, true, video::SColor(255,0,0,0));
576 /* Profiler display */
578 void update_profiler_gui(gui::IGUIStaticText *guitext_profiler,
579 gui::IGUIFont *font, u32 text_height,
580 u32 show_profiler, u32 show_profiler_max)
582 if(show_profiler == 0)
584 guitext_profiler->setVisible(false);
589 std::ostringstream os(std::ios_base::binary);
590 g_profiler->printPage(os, show_profiler, show_profiler_max);
591 std::wstring text = narrow_to_wide(os.str());
592 guitext_profiler->setText(text.c_str());
593 guitext_profiler->setVisible(true);
595 s32 w = font->getDimension(text.c_str()).Width;
598 core::rect<s32> rect(6, 4+(text_height+5)*2, 12+w,
599 8+(text_height+5)*2 +
600 font->getDimension(text.c_str()).Height);
601 guitext_profiler->setRelativePosition(rect);
602 guitext_profiler->setVisible(true);
610 Profiler::GraphValues values;
616 Meta(float initial=0, video::SColor color=
617 video::SColor(255,255,255,255)):
623 std::list<Piece> m_log;
631 void put(const Profiler::GraphValues &values)
634 piece.values = values;
635 m_log.push_back(piece);
636 while(m_log.size() > m_log_max_size)
637 m_log.erase(m_log.begin());
640 void draw(s32 x_left, s32 y_bottom, video::IVideoDriver *driver,
641 gui::IGUIFont* font) const
643 std::map<std::string, Meta> m_meta;
644 for(std::list<Piece>::const_iterator k = m_log.begin();
645 k != m_log.end(); k++)
647 const Piece &piece = *k;
648 for(Profiler::GraphValues::const_iterator i = piece.values.begin();
649 i != piece.values.end(); i++){
650 const std::string &id = i->first;
651 const float &value = i->second;
652 std::map<std::string, Meta>::iterator j =
654 if(j == m_meta.end()){
655 m_meta[id] = Meta(value);
658 if(value < j->second.min)
659 j->second.min = value;
660 if(value > j->second.max)
661 j->second.max = value;
666 static const video::SColor usable_colors[] = {
667 video::SColor(255,255,100,100),
668 video::SColor(255,90,225,90),
669 video::SColor(255,100,100,255)
671 static const u32 usable_colors_count =
672 sizeof(usable_colors) / sizeof(*usable_colors);
673 u32 next_color_i = 0;
674 for(std::map<std::string, Meta>::iterator i = m_meta.begin();
675 i != m_meta.end(); i++){
676 Meta &meta = i->second;
677 video::SColor color(255,200,200,200);
678 if(next_color_i < usable_colors_count)
679 color = usable_colors[next_color_i++];
684 s32 textx = x_left + m_log_max_size + 15;
685 s32 textx2 = textx + 200 - 15;
689 u32 num_graphs = m_meta.size();
690 core::rect<s32> rect(x_left, y_bottom - num_graphs*graphh,
692 video::SColor bgcolor(120,0,0,0);
693 driver->draw2DRectangle(bgcolor, rect, NULL);
697 for(std::map<std::string, Meta>::const_iterator i = m_meta.begin();
698 i != m_meta.end(); i++){
699 const std::string &id = i->first;
700 const Meta &meta = i->second;
702 s32 y = y_bottom - meta_i * 50;
703 float show_min = meta.min;
704 float show_max = meta.max;
705 if(show_min >= 0 && show_max >= 0){
706 if(show_min <= show_max * 0.5)
711 snprintf(buf, 10, "%.3g", show_max);
712 font->draw(narrow_to_wide(buf).c_str(),
713 core::rect<s32>(textx, y - graphh,
714 textx2, y - graphh + texth),
716 snprintf(buf, 10, "%.3g", show_min);
717 font->draw(narrow_to_wide(buf).c_str(),
718 core::rect<s32>(textx, y - texth,
721 font->draw(narrow_to_wide(id).c_str(),
722 core::rect<s32>(textx, y - graphh/2 - texth/2,
723 textx2, y - graphh/2 + texth/2),
725 for(std::list<Piece>::const_iterator j = m_log.begin();
726 j != m_log.end(); j++)
728 const Piece &piece = *j;
730 bool value_exists = false;
731 Profiler::GraphValues::const_iterator k =
732 piece.values.find(id);
733 if(k != piece.values.end()){
741 float scaledvalue = 1.0;
742 if(show_max != show_min)
743 scaledvalue = (value - show_min) / (show_max - show_min);
744 if(scaledvalue == 1.0 && value == 0){
748 s32 ivalue = scaledvalue * graphh;
749 driver->draw2DLine(v2s32(x, y),
750 v2s32(x, y - ivalue),
763 IrrlichtDevice *device,
766 std::string playername,
767 std::string password,
768 std::string address, // If "", local server is used
770 std::wstring &error_message,
771 std::string configpath,
772 ChatBackend &chat_backend,
773 const SubgameSpec &gamespec, // Used for local game,
774 bool simple_singleplayer_mode
777 video::IVideoDriver* driver = device->getVideoDriver();
778 scene::ISceneManager* smgr = device->getSceneManager();
780 // Calculate text height using the font
781 u32 text_height = font->getDimension(L"Random test string").Height;
783 v2u32 screensize(0,0);
784 v2u32 last_screensize(0,0);
785 screensize = driver->getScreenSize();
787 const s32 hotbar_itemcount = 8;
788 //const s32 hotbar_imagesize = 36;
789 //const s32 hotbar_imagesize = 64;
790 s32 hotbar_imagesize = 48;
793 Draw "Loading" screen
796 draw_load_screen(L"Loading...", driver, font);
798 // Create texture source
799 IWritableTextureSource *tsrc = createTextureSource(device);
801 // These will be filled by data received from the server
802 // Create item definition manager
803 IWritableItemDefManager *itemdef = createItemDefManager();
804 // Create node definition manager
805 IWritableNodeDefManager *nodedef = createNodeDefManager();
807 // Add chat log output for errors to be shown in chat
808 LogOutputBuffer chat_log_error_buf(LMT_ERROR);
810 // Create UI for modifying quicktune values
811 QuicktuneShortcutter quicktune;
815 SharedPtr will delete it when it goes out of scope.
817 SharedPtr<Server> server;
819 draw_load_screen(L"Creating server...", driver, font);
820 infostream<<"Creating server"<<std::endl;
821 server = new Server(map_dir, configpath, gamespec,
822 simple_singleplayer_mode);
826 do{ // Client scope (breakable do-while(0))
832 draw_load_screen(L"Creating client...", driver, font);
833 infostream<<"Creating client"<<std::endl;
835 MapDrawControl draw_control;
837 Client client(device, playername.c_str(), password, draw_control,
838 tsrc, itemdef, nodedef);
840 // Client acts as our GameDef
841 IGameDef *gamedef = &client;
843 draw_load_screen(L"Resolving address...", driver, font);
844 Address connect_address(0,0,0,0, port);
847 //connect_address.Resolve("localhost");
848 connect_address.setAddress(127,0,0,1);
850 connect_address.Resolve(address.c_str());
852 catch(ResolveError &e)
854 error_message = L"Couldn't resolve address";
855 errorstream<<wide_to_narrow(error_message)<<std::endl;
856 // Break out of client scope
861 Attempt to connect to the server
864 infostream<<"Connecting to server at ";
865 connect_address.print(&infostream);
866 infostream<<std::endl;
867 client.connect(connect_address);
870 Wait for server to accept connection
872 bool could_connect = false;
873 bool connect_aborted = false;
875 float frametime = 0.033;
876 float time_counter = 0.0;
880 // Update client and server
881 client.step(frametime);
883 server->step(frametime);
886 if(client.connectedAndInitialized()){
887 could_connect = true;
891 if(client.accessDenied()){
892 error_message = L"Access denied. Reason: "
893 +client.accessDeniedReason();
894 errorstream<<wide_to_narrow(error_message)<<std::endl;
897 if(input->wasKeyDown(EscapeKey)){
898 connect_aborted = true;
899 infostream<<"Connect aborted [Escape]"<<std::endl;
904 std::wostringstream ss;
905 ss<<L"Connecting to server... (press Escape to cancel)\n";
906 std::wstring animation = L"/-\\|";
907 ss<<animation[(int)(time_counter/0.2)%4];
908 draw_load_screen(ss.str(), driver, font);
911 sleep_ms(1000*frametime);
912 time_counter += frametime;
915 catch(con::PeerNotFoundException &e)
919 Handle failure to connect
922 if(error_message == L"" && !connect_aborted){
923 error_message = L"Connection failed";
924 errorstream<<wide_to_narrow(error_message)<<std::endl;
926 // Break out of client scope
931 Wait until content has been received
933 bool got_content = false;
934 bool content_aborted = false;
936 float frametime = 0.033;
937 float time_counter = 0.0;
941 // Update client and server
942 client.step(frametime);
944 server->step(frametime);
947 if(client.texturesReceived() &&
948 client.itemdefReceived() &&
949 client.nodedefReceived()){
954 if(!client.connectedAndInitialized()){
955 error_message = L"Client disconnected";
956 errorstream<<wide_to_narrow(error_message)<<std::endl;
959 if(input->wasKeyDown(EscapeKey)){
960 content_aborted = true;
961 infostream<<"Connect aborted [Escape]"<<std::endl;
966 std::wostringstream ss;
967 ss<<L"Waiting content... (press Escape to cancel)\n";
969 ss<<(client.itemdefReceived()?L"[X]":L"[ ]");
970 ss<<L" Item definitions\n";
971 ss<<(client.nodedefReceived()?L"[X]":L"[ ]");
972 ss<<L" Node definitions\n";
973 //ss<<(client.texturesReceived()?L"[X]":L"[ ]");
974 ss<<L"["<<(int)(client.textureReceiveProgress()*100+0.5)<<L"%] ";
977 draw_load_screen(ss.str(), driver, font);
980 sleep_ms(1000*frametime);
981 time_counter += frametime;
986 if(error_message == L"" && !content_aborted){
987 error_message = L"Something failed";
988 errorstream<<wide_to_narrow(error_message)<<std::endl;
990 // Break out of client scope
995 After all content has been received:
996 Update cached textures, meshes and materials
998 client.afterContentReceived();
1001 Create the camera node
1003 Camera camera(smgr, draw_control);
1004 if (!camera.successfullyCreated(error_message))
1007 f32 camera_yaw = 0; // "right/left"
1008 f32 camera_pitch = 0; // "up/down"
1014 Clouds *clouds = NULL;
1015 if(g_settings->getBool("enable_clouds"))
1017 clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1, time(0));
1025 sky = new Sky(smgr->getRootSceneNode(), smgr, -1);
1031 FarMesh *farmesh = NULL;
1032 if(g_settings->getBool("enable_farmesh"))
1034 farmesh = new FarMesh(smgr->getRootSceneNode(), smgr, -1, client.getMapSeed(), &client);
1038 A copy of the local inventory
1040 Inventory local_inventory(itemdef);
1046 // First line of debug text
1047 gui::IGUIStaticText *guitext = guienv->addStaticText(
1049 core::rect<s32>(5, 5, 795, 5+text_height),
1051 // Second line of debug text
1052 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
1054 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
1056 // At the middle of the screen
1057 // Object infos are shown in this
1058 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
1060 core::rect<s32>(0,0,400,text_height*5+5) + v2s32(100,200),
1063 // Status text (displays info when showing and hiding GUI stuff, etc.)
1064 gui::IGUIStaticText *guitext_status = guienv->addStaticText(
1066 core::rect<s32>(0,0,0,0),
1068 guitext_status->setVisible(false);
1070 std::wstring statustext;
1071 float statustext_time = 0;
1074 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
1076 core::rect<s32>(0,0,0,0),
1077 //false, false); // Disable word wrap as of now
1079 // Remove stale "recent" chat messages from previous connections
1080 chat_backend.clearRecentChat();
1081 // Chat backend and console
1082 GUIChatConsole *gui_chat_console = new GUIChatConsole(guienv, guienv->getRootGUIElement(), -1, &chat_backend, &client);
1084 // Profiler text (size is updated when text is updated)
1085 gui::IGUIStaticText *guitext_profiler = guienv->addStaticText(
1087 core::rect<s32>(0,0,0,0),
1089 guitext_profiler->setBackgroundColor(video::SColor(120,0,0,0));
1090 guitext_profiler->setVisible(false);
1093 Some statistics are collected in these
1096 u32 beginscenetime = 0;
1098 u32 endscenetime = 0;
1100 float recent_turn_speed = 0.0;
1102 ProfilerGraph graph;
1104 float nodig_delay_timer = 0.0;
1105 float dig_time = 0.0;
1107 PointedThing pointed_old;
1108 bool digging = false;
1109 bool ldown_for_dig = false;
1111 float damage_flash_timer = 0;
1112 s16 farmesh_range = 20*MAP_BLOCKSIZE;
1114 const float object_hit_delay = 0.2;
1115 float object_hit_delay_timer = 0.0;
1116 float time_from_last_punch = 10;
1118 bool invert_mouse = g_settings->getBool("invert_mouse");
1120 bool respawn_menu_active = false;
1121 bool update_wielded_item_trigger = false;
1123 bool show_hud = true;
1124 bool show_chat = true;
1125 bool force_fog_off = false;
1126 bool disable_camera_update = false;
1127 bool show_debug = g_settings->getBool("show_debug");
1128 bool show_profiler_graph = false;
1129 u32 show_profiler = 0;
1130 u32 show_profiler_max = 3; // Number of pages
1132 float time_of_day = 0;
1133 float time_of_day_smooth = 0;
1139 bool first_loop_after_window_activation = true;
1141 // TODO: Convert the static interval timers to these
1142 // Interval limiter for profiler
1143 IntervalLimiter m_profiler_interval;
1145 // Time is in milliseconds
1146 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
1147 // NOTE: So we have to use getTime() and call run()s between them
1148 u32 lasttime = device->getTimer()->getTime();
1152 if(device->run() == false || kill == true)
1155 // Time of frame without fps limit
1159 // not using getRealTime is necessary for wine
1160 u32 time = device->getTimer()->getTime();
1162 busytime_u32 = time - lasttime;
1165 busytime = busytime_u32 / 1000.0;
1168 g_profiler->graphAdd("mainloop_other", busytime - (float)drawtime/1000.0f);
1170 // Necessary for device->getTimer()->getTime()
1178 float fps_max = g_settings->getFloat("fps_max");
1179 u32 frametime_min = 1000./fps_max;
1181 if(busytime_u32 < frametime_min)
1183 u32 sleeptime = frametime_min - busytime_u32;
1184 device->sleep(sleeptime);
1185 g_profiler->graphAdd("mainloop_sleep", (float)sleeptime/1000.0f);
1189 // Necessary for device->getTimer()->getTime()
1193 Time difference calculation
1195 f32 dtime; // in seconds
1197 u32 time = device->getTimer()->getTime();
1199 dtime = (time - lasttime) / 1000.0;
1206 if(nodig_delay_timer >= 0)
1207 nodig_delay_timer -= dtime;
1208 if(object_hit_delay_timer >= 0)
1209 object_hit_delay_timer -= dtime;
1210 time_from_last_punch += dtime;
1212 g_profiler->add("Elapsed time", dtime);
1213 g_profiler->avg("FPS", 1./dtime);
1216 Time average and jitter calculation
1219 static f32 dtime_avg1 = 0.0;
1220 dtime_avg1 = dtime_avg1 * 0.96 + dtime * 0.04;
1221 f32 dtime_jitter1 = dtime - dtime_avg1;
1223 static f32 dtime_jitter1_max_sample = 0.0;
1224 static f32 dtime_jitter1_max_fraction = 0.0;
1226 static f32 jitter1_max = 0.0;
1227 static f32 counter = 0.0;
1228 if(dtime_jitter1 > jitter1_max)
1229 jitter1_max = dtime_jitter1;
1234 dtime_jitter1_max_sample = jitter1_max;
1235 dtime_jitter1_max_fraction
1236 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1242 Busytime average and jitter calculation
1245 static f32 busytime_avg1 = 0.0;
1246 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1247 f32 busytime_jitter1 = busytime - busytime_avg1;
1249 static f32 busytime_jitter1_max_sample = 0.0;
1250 static f32 busytime_jitter1_min_sample = 0.0;
1252 static f32 jitter1_max = 0.0;
1253 static f32 jitter1_min = 0.0;
1254 static f32 counter = 0.0;
1255 if(busytime_jitter1 > jitter1_max)
1256 jitter1_max = busytime_jitter1;
1257 if(busytime_jitter1 < jitter1_min)
1258 jitter1_min = busytime_jitter1;
1262 busytime_jitter1_max_sample = jitter1_max;
1263 busytime_jitter1_min_sample = jitter1_min;
1270 Handle miscellaneous stuff
1273 if(client.accessDenied())
1275 error_message = L"Access denied. Reason: "
1276 +client.accessDeniedReason();
1277 errorstream<<wide_to_narrow(error_message)<<std::endl;
1281 if(g_gamecallback->disconnect_requested)
1283 g_gamecallback->disconnect_requested = false;
1287 if(g_gamecallback->changepassword_requested)
1289 (new GUIPasswordChange(guienv, guiroot, -1,
1290 &g_menumgr, &client))->drop();
1291 g_gamecallback->changepassword_requested = false;
1295 Process TextureSource's queue
1297 tsrc->processQueue();
1302 last_screensize = screensize;
1303 screensize = driver->getScreenSize();
1304 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
1305 //bool screensize_changed = screensize != last_screensize;
1308 if(screensize.Y <= 800)
1309 hotbar_imagesize = 32;
1310 else if(screensize.Y <= 1280)
1311 hotbar_imagesize = 48;
1313 hotbar_imagesize = 64;
1315 // Hilight boxes collected during the loop and displayed
1316 core::list< core::aabbox3d<f32> > hilightboxes;
1319 std::wstring infotext;
1322 Debug info for client
1325 static float counter = 0.0;
1330 client.printDebugInfo(infostream);
1337 float profiler_print_interval =
1338 g_settings->getFloat("profiler_print_interval");
1339 bool print_to_log = true;
1340 if(profiler_print_interval == 0){
1341 print_to_log = false;
1342 profiler_print_interval = 5;
1344 if(m_profiler_interval.step(dtime, profiler_print_interval))
1347 infostream<<"Profiler:"<<std::endl;
1348 g_profiler->print(infostream);
1351 update_profiler_gui(guitext_profiler, font, text_height,
1352 show_profiler, show_profiler_max);
1354 g_profiler->clear();
1358 Direct handling of user input
1361 // Reset input if window not active or some menu is active
1362 if(device->isWindowActive() == false
1363 || noMenuActive() == false
1364 || guienv->hasFocus(gui_chat_console))
1369 // Input handler step() (used by the random input generator)
1373 Launch menus and trigger stuff according to keys
1375 if(input->wasKeyDown(getKeySetting("keymap_drop")))
1377 // drop selected item
1378 IDropAction *a = new IDropAction();
1380 a->from_inv.setCurrentPlayer();
1381 a->from_list = "main";
1382 a->from_i = client.getPlayerItem();
1383 client.inventoryAction(a);
1385 else if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1387 infostream<<"the_game: "
1388 <<"Launching inventory"<<std::endl;
1390 GUIInventoryMenu *menu =
1391 new GUIInventoryMenu(guienv, guiroot, -1,
1392 &g_menumgr, v2s16(8,7),
1395 InventoryLocation inventoryloc;
1396 inventoryloc.setCurrentPlayer();
1398 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1399 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1400 "list", inventoryloc, "main",
1401 v2s32(0, 3), v2s32(8, 4)));
1402 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1403 "list", inventoryloc, "craft",
1404 v2s32(3, 0), v2s32(3, 3)));
1405 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1406 "list", inventoryloc, "craftpreview",
1407 v2s32(7, 1), v2s32(1, 1)));
1409 menu->setDrawSpec(draw_spec);
1413 else if(input->wasKeyDown(EscapeKey))
1415 infostream<<"the_game: "
1416 <<"Launching pause menu"<<std::endl;
1417 // It will delete itself by itself
1418 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1419 &g_menumgr, simple_singleplayer_mode))->drop();
1421 // Move mouse cursor on top of the disconnect button
1422 if(simple_singleplayer_mode)
1423 input->setMousePos(displaycenter.X, displaycenter.Y+0);
1425 input->setMousePos(displaycenter.X, displaycenter.Y+25);
1427 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1429 TextDest *dest = new TextDestChat(&client);
1431 (new GUITextInputMenu(guienv, guiroot, -1,
1435 else if(input->wasKeyDown(getKeySetting("keymap_cmd")))
1437 TextDest *dest = new TextDestChat(&client);
1439 (new GUITextInputMenu(guienv, guiroot, -1,
1443 else if(input->wasKeyDown(getKeySetting("keymap_console")))
1445 if (!gui_chat_console->isOpenInhibited())
1447 // Open up to over half of the screen
1448 gui_chat_console->openConsole(0.6);
1449 guienv->setFocus(gui_chat_console);
1452 else if(input->wasKeyDown(getKeySetting("keymap_freemove")))
1454 if(g_settings->getBool("free_move"))
1456 g_settings->set("free_move","false");
1457 statustext = L"free_move disabled";
1458 statustext_time = 0;
1462 g_settings->set("free_move","true");
1463 statustext = L"free_move enabled";
1464 statustext_time = 0;
1467 else if(input->wasKeyDown(getKeySetting("keymap_fastmove")))
1469 if(g_settings->getBool("fast_move"))
1471 g_settings->set("fast_move","false");
1472 statustext = L"fast_move disabled";
1473 statustext_time = 0;
1477 g_settings->set("fast_move","true");
1478 statustext = L"fast_move enabled";
1479 statustext_time = 0;
1482 else if(input->wasKeyDown(getKeySetting("keymap_screenshot")))
1484 irr::video::IImage* const image = driver->createScreenShot();
1486 irr::c8 filename[256];
1487 snprintf(filename, 256, "%s" DIR_DELIM "screenshot_%u.png",
1488 g_settings->get("screenshot_path").c_str(),
1489 device->getTimer()->getRealTime());
1490 if (driver->writeImageToFile(image, filename)) {
1491 std::wstringstream sstr;
1492 sstr<<"Saved screenshot to '"<<filename<<"'";
1493 infostream<<"Saved screenshot to '"<<filename<<"'"<<std::endl;
1494 statustext = sstr.str();
1495 statustext_time = 0;
1497 infostream<<"Failed to save screenshot '"<<filename<<"'"<<std::endl;
1502 else if(input->wasKeyDown(getKeySetting("keymap_toggle_hud")))
1504 show_hud = !show_hud;
1506 statustext = L"HUD shown";
1508 statustext = L"HUD hidden";
1509 statustext_time = 0;
1511 else if(input->wasKeyDown(getKeySetting("keymap_toggle_chat")))
1513 show_chat = !show_chat;
1515 statustext = L"Chat shown";
1517 statustext = L"Chat hidden";
1518 statustext_time = 0;
1520 else if(input->wasKeyDown(getKeySetting("keymap_toggle_force_fog_off")))
1522 force_fog_off = !force_fog_off;
1524 statustext = L"Fog disabled";
1526 statustext = L"Fog enabled";
1527 statustext_time = 0;
1529 else if(input->wasKeyDown(getKeySetting("keymap_toggle_update_camera")))
1531 disable_camera_update = !disable_camera_update;
1532 if(disable_camera_update)
1533 statustext = L"Camera update disabled";
1535 statustext = L"Camera update enabled";
1536 statustext_time = 0;
1538 else if(input->wasKeyDown(getKeySetting("keymap_toggle_debug")))
1540 // Initial / 3x toggle: Chat only
1541 // 1x toggle: Debug text with chat
1542 // 2x toggle: Debug text with profiler graph
1546 show_profiler_graph = false;
1547 statustext = L"Debug info shown";
1548 statustext_time = 0;
1550 else if(show_profiler_graph)
1553 show_profiler_graph = false;
1554 statustext = L"Debug info and profiler graph hidden";
1555 statustext_time = 0;
1559 show_profiler_graph = true;
1560 statustext = L"Profiler graph shown";
1561 statustext_time = 0;
1564 else if(input->wasKeyDown(getKeySetting("keymap_toggle_profiler")))
1566 show_profiler = (show_profiler + 1) % (show_profiler_max + 1);
1568 // FIXME: This updates the profiler with incomplete values
1569 update_profiler_gui(guitext_profiler, font, text_height,
1570 show_profiler, show_profiler_max);
1572 if(show_profiler != 0)
1574 std::wstringstream sstr;
1575 sstr<<"Profiler shown (page "<<show_profiler
1576 <<" of "<<show_profiler_max<<")";
1577 statustext = sstr.str();
1578 statustext_time = 0;
1582 statustext = L"Profiler hidden";
1583 statustext_time = 0;
1586 else if(input->wasKeyDown(getKeySetting("keymap_increase_viewing_range_min")))
1588 s16 range = g_settings->getS16("viewing_range_nodes_min");
1589 s16 range_new = range + 10;
1590 g_settings->set("viewing_range_nodes_min", itos(range_new));
1591 statustext = narrow_to_wide(
1592 "Minimum viewing range changed to "
1594 statustext_time = 0;
1596 else if(input->wasKeyDown(getKeySetting("keymap_decrease_viewing_range_min")))
1598 s16 range = g_settings->getS16("viewing_range_nodes_min");
1599 s16 range_new = range - 10;
1602 g_settings->set("viewing_range_nodes_min",
1604 statustext = narrow_to_wide(
1605 "Minimum viewing range changed to "
1607 statustext_time = 0;
1610 // Handle QuicktuneShortcutter
1611 if(input->wasKeyDown(getKeySetting("keymap_quicktune_next")))
1613 if(input->wasKeyDown(getKeySetting("keymap_quicktune_prev")))
1615 if(input->wasKeyDown(getKeySetting("keymap_quicktune_inc")))
1617 if(input->wasKeyDown(getKeySetting("keymap_quicktune_dec")))
1620 std::string msg = quicktune.getMessage();
1622 statustext = narrow_to_wide(msg);
1623 statustext_time = 0;
1627 // Item selection with mouse wheel
1628 u16 new_playeritem = client.getPlayerItem();
1630 s32 wheel = input->getMouseWheel();
1631 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1632 hotbar_itemcount-1);
1636 if(new_playeritem < max_item)
1643 if(new_playeritem > 0)
1646 new_playeritem = max_item;
1651 for(u16 i=0; i<10; i++)
1653 const KeyPress *kp = NumberKey + (i + 1) % 10;
1654 if(input->wasKeyDown(*kp))
1656 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1660 infostream<<"Selected item: "
1661 <<new_playeritem<<std::endl;
1666 // Viewing range selection
1667 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1669 draw_control.range_all = !draw_control.range_all;
1670 if(draw_control.range_all)
1672 infostream<<"Enabled full viewing range"<<std::endl;
1673 statustext = L"Enabled full viewing range";
1674 statustext_time = 0;
1678 infostream<<"Disabled full viewing range"<<std::endl;
1679 statustext = L"Disabled full viewing range";
1680 statustext_time = 0;
1684 // Print debug stacks
1685 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1687 dstream<<"-----------------------------------------"
1689 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1690 dstream<<"-----------------------------------------"
1692 debug_stacks_print();
1696 Mouse and camera control
1697 NOTE: Do this before client.setPlayerControl() to not cause a camera lag of one frame
1700 float turn_amount = 0;
1701 if((device->isWindowActive() && noMenuActive()) || random_input)
1705 // Mac OSX gets upset if this is set every frame
1706 if(device->getCursorControl()->isVisible())
1707 device->getCursorControl()->setVisible(false);
1710 if(first_loop_after_window_activation){
1711 //infostream<<"window active, first loop"<<std::endl;
1712 first_loop_after_window_activation = false;
1715 s32 dx = input->getMousePos().X - displaycenter.X;
1716 s32 dy = input->getMousePos().Y - displaycenter.Y;
1719 //infostream<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1721 /*const float keyspeed = 500;
1722 if(input->isKeyDown(irr::KEY_UP))
1723 dy -= dtime * keyspeed;
1724 if(input->isKeyDown(irr::KEY_DOWN))
1725 dy += dtime * keyspeed;
1726 if(input->isKeyDown(irr::KEY_LEFT))
1727 dx -= dtime * keyspeed;
1728 if(input->isKeyDown(irr::KEY_RIGHT))
1729 dx += dtime * keyspeed;*/
1733 camera_pitch += dy*d;
1734 if(camera_pitch < -89.5) camera_pitch = -89.5;
1735 if(camera_pitch > 89.5) camera_pitch = 89.5;
1737 turn_amount = v2f(dx, dy).getLength() * d;
1739 input->setMousePos(displaycenter.X, displaycenter.Y);
1742 // Mac OSX gets upset if this is set every frame
1743 if(device->getCursorControl()->isVisible() == false)
1744 device->getCursorControl()->setVisible(true);
1746 //infostream<<"window inactive"<<std::endl;
1747 first_loop_after_window_activation = true;
1749 recent_turn_speed = recent_turn_speed * 0.9 + turn_amount * 0.1;
1750 //std::cerr<<"recent_turn_speed = "<<recent_turn_speed<<std::endl;
1753 Player speed control
1765 PlayerControl control(
1766 input->isKeyDown(getKeySetting("keymap_forward")),
1767 input->isKeyDown(getKeySetting("keymap_backward")),
1768 input->isKeyDown(getKeySetting("keymap_left")),
1769 input->isKeyDown(getKeySetting("keymap_right")),
1770 input->isKeyDown(getKeySetting("keymap_jump")),
1771 input->isKeyDown(getKeySetting("keymap_special1")),
1772 input->isKeyDown(getKeySetting("keymap_sneak")),
1776 client.setPlayerControl(control);
1785 //TimeTaker timer("server->step(dtime)");
1786 server->step(dtime);
1794 //TimeTaker timer("client.step(dtime)");
1796 //client.step(dtime_avg1);
1800 // Read client events
1803 ClientEvent event = client.getClientEvent();
1804 if(event.type == CE_NONE)
1808 else if(event.type == CE_PLAYER_DAMAGE)
1810 //u16 damage = event.player_damage.amount;
1811 //infostream<<"Player damage: "<<damage<<std::endl;
1812 damage_flash_timer = 0.05;
1813 if(event.player_damage.amount >= 2){
1814 damage_flash_timer += 0.05 * event.player_damage.amount;
1817 else if(event.type == CE_PLAYER_FORCE_MOVE)
1819 camera_yaw = event.player_force_move.yaw;
1820 camera_pitch = event.player_force_move.pitch;
1822 else if(event.type == CE_DEATHSCREEN)
1824 if(respawn_menu_active)
1827 /*bool set_camera_point_target =
1828 event.deathscreen.set_camera_point_target;
1829 v3f camera_point_target;
1830 camera_point_target.X = event.deathscreen.camera_point_target_x;
1831 camera_point_target.Y = event.deathscreen.camera_point_target_y;
1832 camera_point_target.Z = event.deathscreen.camera_point_target_z;*/
1833 MainRespawnInitiator *respawner =
1834 new MainRespawnInitiator(
1835 &respawn_menu_active, &client);
1836 GUIDeathScreen *menu =
1837 new GUIDeathScreen(guienv, guiroot, -1,
1838 &g_menumgr, respawner);
1841 chat_backend.addMessage(L"", L"You died.");
1843 /* Handle visualization */
1845 damage_flash_timer = 0;
1847 /*LocalPlayer* player = client.getLocalPlayer();
1848 player->setPosition(player->getPosition() + v3f(0,-BS,0));
1849 camera.update(player, busytime, screensize);*/
1851 else if(event.type == CE_TEXTURES_UPDATED)
1853 update_wielded_item_trigger = true;
1858 //TimeTaker //timer2("//timer2");
1861 For interaction purposes, get info about the held item
1863 - Is it a usable item?
1864 - Can it point to liquids?
1866 ItemStack playeritem;
1867 bool playeritem_usable = false;
1868 bool playeritem_liquids_pointable = false;
1870 InventoryList *mlist = local_inventory.getList("main");
1873 playeritem = mlist->getItem(client.getPlayerItem());
1874 playeritem_usable = playeritem.getDefinition(itemdef).usable;
1875 playeritem_liquids_pointable = playeritem.getDefinition(itemdef).liquids_pointable;
1878 ToolCapabilities playeritem_toolcap =
1879 playeritem.getToolCapabilities(itemdef);
1885 LocalPlayer* player = client.getEnv().getLocalPlayer();
1886 float full_punch_interval = playeritem_toolcap.full_punch_interval;
1887 float tool_reload_ratio = time_from_last_punch / full_punch_interval;
1888 tool_reload_ratio = MYMIN(tool_reload_ratio, 1.0);
1889 camera.update(player, busytime, screensize, tool_reload_ratio);
1892 v3f player_position = player->getPosition();
1893 v3f camera_position = camera.getPosition();
1894 v3f camera_direction = camera.getDirection();
1895 f32 camera_fov = camera.getFovMax();
1897 if(!disable_camera_update){
1898 client.getEnv().getClientMap().updateCamera(camera_position,
1899 camera_direction, camera_fov);
1903 //TimeTaker //timer3("//timer3");
1906 Calculate what block is the crosshair pointing to
1909 //u32 t1 = device->getTimer()->getRealTime();
1911 f32 d = 4; // max. distance
1912 core::line3d<f32> shootline(camera_position,
1913 camera_position + camera_direction * BS * (d+1));
1915 core::aabbox3d<f32> hilightbox;
1916 bool should_show_hilightbox = false;
1917 ClientActiveObject *selected_object = NULL;
1919 PointedThing pointed = getPointedThing(
1921 &client, player_position, camera_direction,
1922 camera_position, shootline, d,
1923 playeritem_liquids_pointable, !ldown_for_dig,
1925 hilightbox, should_show_hilightbox,
1928 if(pointed != pointed_old)
1930 infostream<<"Pointing at "<<pointed.dump()<<std::endl;
1931 //dstream<<"Pointing at "<<pointed.dump()<<std::endl;
1937 if(should_show_hilightbox)
1938 hilightboxes.push_back(hilightbox);
1942 - releasing left mouse button
1943 - pointing away from node
1947 if(input->getLeftReleased())
1949 infostream<<"Left button released"
1950 <<" (stopped digging)"<<std::endl;
1953 else if(pointed != pointed_old)
1955 if (pointed.type == POINTEDTHING_NODE
1956 && pointed_old.type == POINTEDTHING_NODE
1957 && pointed.node_undersurface == pointed_old.node_undersurface)
1959 // Still pointing to the same node,
1960 // but a different face. Don't reset.
1964 infostream<<"Pointing away from node"
1965 <<" (stopped digging)"<<std::endl;
1971 client.interact(1, pointed_old);
1972 client.setCrack(-1, v3s16(0,0,0));
1976 if(!digging && ldown_for_dig && !input->getLeftState())
1978 ldown_for_dig = false;
1981 bool left_punch = false;
1983 if(playeritem_usable && input->getLeftState())
1985 if(input->getLeftClicked())
1986 client.interact(4, pointed);
1988 else if(pointed.type == POINTEDTHING_NODE)
1990 v3s16 nodepos = pointed.node_undersurface;
1991 v3s16 neighbourpos = pointed.node_abovesurface;
1994 Check information text of node
1997 ClientMap &map = client.getEnv().getClientMap();
1998 NodeMetadata *meta = map.getNodeMetadata(nodepos);
2000 infotext = narrow_to_wide(meta->infoText());
2002 MapNode n = map.getNode(nodepos);
2003 if(nodedef->get(n).tname_tiles[0] == "unknown_block.png"){
2004 infotext = L"Unknown node: ";
2005 infotext += narrow_to_wide(nodedef->get(n).name);
2013 if(nodig_delay_timer <= 0.0 && input->getLeftState())
2017 infostream<<"Started digging"<<std::endl;
2018 client.interact(0, pointed);
2020 ldown_for_dig = true;
2022 MapNode n = client.getEnv().getClientMap().getNode(nodepos);
2024 // Get digging parameters
2025 DigParams params = getDigParams(nodedef->get(n).groups,
2026 &playeritem_toolcap);
2027 // If can't dig, try hand
2028 if(!params.diggable){
2029 const ItemDefinition &hand = itemdef->get("");
2030 const ToolCapabilities *tp = hand.tool_capabilities;
2032 params = getDigParams(nodedef->get(n).groups, tp);
2035 float dig_time_complete = 0.0;
2037 if(params.diggable == false)
2039 // I guess nobody will wait for this long
2040 dig_time_complete = 10000000.0;
2044 dig_time_complete = params.time;
2047 if(dig_time_complete >= 0.001)
2049 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
2050 * dig_time/dig_time_complete);
2052 // This is for torches
2055 dig_index = CRACK_ANIMATION_LENGTH;
2058 // Don't show cracks if not diggable
2059 if(dig_time_complete >= 100000.0)
2062 else if(dig_index < CRACK_ANIMATION_LENGTH)
2064 //TimeTaker timer("client.setTempMod");
2065 //infostream<<"dig_index="<<dig_index<<std::endl;
2066 client.setCrack(dig_index, nodepos);
2070 infostream<<"Digging completed"<<std::endl;
2071 client.interact(2, pointed);
2072 client.setCrack(-1, v3s16(0,0,0));
2073 client.removeNode(nodepos);
2078 nodig_delay_timer = dig_time_complete
2079 / (float)CRACK_ANIMATION_LENGTH;
2081 // We don't want a corresponding delay to
2082 // very time consuming nodes
2083 if(nodig_delay_timer > 0.5)
2085 nodig_delay_timer = 0.5;
2087 // We want a slight delay to very little
2088 // time consuming nodes
2089 float mindelay = 0.15;
2090 if(nodig_delay_timer < mindelay)
2092 nodig_delay_timer = mindelay;
2098 camera.setDigging(0); // left click animation
2101 if(input->getRightClicked())
2103 infostream<<"Ground right-clicked"<<std::endl;
2105 // If metadata provides an inventory view, activate it
2106 if(meta && meta->getInventoryDrawSpecString() != "" && !random_input)
2108 infostream<<"Launching custom inventory view"<<std::endl;
2110 InventoryLocation inventoryloc;
2111 inventoryloc.setNodeMeta(nodepos);
2118 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
2120 GUIInventoryMenu::makeDrawSpecArrayFromString(
2122 meta->getInventoryDrawSpecString(),
2125 GUIInventoryMenu *menu =
2126 new GUIInventoryMenu(guienv, guiroot, -1,
2127 &g_menumgr, invsize,
2129 menu->setDrawSpec(draw_spec);
2132 // If metadata provides text input, activate text input
2133 else if(meta && meta->allowsTextInput() && !random_input)
2135 infostream<<"Launching metadata text input"<<std::endl;
2137 // Get a new text for it
2139 TextDest *dest = new TextDestNodeMetadata(nodepos, &client);
2141 std::wstring wtext = narrow_to_wide(meta->getText());
2143 (new GUITextInputMenu(guienv, guiroot, -1,
2147 // Otherwise report right click to server
2150 client.interact(3, pointed);
2151 camera.setDigging(1); // right click animation
2155 else if(pointed.type == POINTEDTHING_OBJECT)
2157 infotext = narrow_to_wide(selected_object->infoText());
2159 if(infotext == L"" && show_debug){
2160 infotext = narrow_to_wide(selected_object->debugInfoText());
2163 //if(input->getLeftClicked())
2164 if(input->getLeftState())
2166 bool do_punch = false;
2167 bool do_punch_damage = false;
2168 if(object_hit_delay_timer <= 0.0){
2170 do_punch_damage = true;
2171 object_hit_delay_timer = object_hit_delay;
2173 if(input->getLeftClicked()){
2177 infostream<<"Left-clicked object"<<std::endl;
2180 if(do_punch_damage){
2181 // Report direct punch
2182 v3f objpos = selected_object->getPosition();
2183 v3f dir = (objpos - player_position).normalize();
2185 bool disable_send = selected_object->directReportPunch(
2186 dir, &playeritem, time_from_last_punch);
2187 time_from_last_punch = 0;
2189 client.interact(0, pointed);
2192 else if(input->getRightClicked())
2194 infostream<<"Right-clicked object"<<std::endl;
2195 client.interact(3, pointed); // place
2198 else if(input->getLeftState())
2200 // When button is held down in air, show continuous animation
2204 pointed_old = pointed;
2206 if(left_punch || input->getLeftClicked())
2208 camera.setDigging(0); // left click animation
2211 input->resetLeftClicked();
2212 input->resetRightClicked();
2214 input->resetLeftReleased();
2215 input->resetRightReleased();
2218 Calculate stuff for drawing
2228 fog_range = BS*farmesh_range;
2232 fog_range = draw_control.wanted_range*BS + 0.0*MAP_BLOCKSIZE*BS;
2234 if(draw_control.range_all)
2235 fog_range = 100000*BS;
2239 Calculate general brightness
2241 u32 daynight_ratio = client.getEnv().getDayNightRatio();
2242 float time_brightness = (float)decode_light(
2243 (daynight_ratio * LIGHT_SUN) / 1000) / 255.0;
2244 float direct_brightness = 0;
2245 bool sunlight_seen = false;
2246 if(g_settings->getBool("free_move")){
2247 direct_brightness = time_brightness;
2248 sunlight_seen = true;
2250 ScopeProfiler sp(g_profiler, "Detecting background light", SPT_AVG);
2251 float old_brightness = sky->getBrightness();
2252 direct_brightness = (float)client.getEnv().getClientMap()
2253 .getBackgroundBrightness(MYMIN(fog_range*1.2, 60*BS),
2254 daynight_ratio, (int)(old_brightness*255.5), &sunlight_seen)
2258 time_of_day = client.getEnv().getTimeOfDayF();
2260 if(fabs(time_of_day - time_of_day_smooth) > maxsm &&
2261 fabs(time_of_day - time_of_day_smooth + 1.0) > maxsm &&
2262 fabs(time_of_day - time_of_day_smooth - 1.0) > maxsm)
2263 time_of_day_smooth = time_of_day;
2265 if(time_of_day_smooth > 0.8 && time_of_day < 0.2)
2266 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2267 + (time_of_day+1.0) * todsm;
2269 time_of_day_smooth = time_of_day_smooth * (1.0-todsm)
2270 + time_of_day * todsm;
2272 sky->update(time_of_day_smooth, time_brightness, direct_brightness,
2275 float brightness = sky->getBrightness();
2276 video::SColor bgcolor = sky->getBgColor();
2277 video::SColor skycolor = sky->getSkyColor();
2283 if(sky->getCloudsVisible()){
2284 clouds->setVisible(true);
2285 clouds->step(dtime);
2286 clouds->update(v2f(player_position.X, player_position.Z),
2287 sky->getCloudColor());
2289 clouds->setVisible(false);
2298 farmesh_range = draw_control.wanted_range * 10;
2299 if(draw_control.range_all && farmesh_range < 500)
2300 farmesh_range = 500;
2301 if(farmesh_range > 1000)
2302 farmesh_range = 1000;
2304 farmesh->step(dtime);
2305 farmesh->update(v2f(player_position.X, player_position.Z),
2306 brightness, farmesh_range);
2313 if(g_settings->getBool("enable_fog") == true && !force_fog_off)
2317 video::EFT_FOG_LINEAR,
2329 video::EFT_FOG_LINEAR,
2339 Update gui stuff (0ms)
2342 //TimeTaker guiupdatetimer("Gui updating");
2344 const char program_name_and_version[] =
2345 "Minetest-c55 " VERSION_STRING;
2349 static float drawtime_avg = 0;
2350 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
2351 /*static float beginscenetime_avg = 0;
2352 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
2353 static float scenetime_avg = 0;
2354 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
2355 static float endscenetime_avg = 0;
2356 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;*/
2359 snprintf(temptext, 300, "%s ("
2362 " drawtime=%.0f, dtime_jitter = % .1f %%"
2363 ", v_range = %.1f, RTT = %.3f",
2364 program_name_and_version,
2365 draw_control.range_all,
2367 dtime_jitter1_max_fraction * 100.0,
2368 draw_control.wanted_range,
2372 guitext->setText(narrow_to_wide(temptext).c_str());
2373 guitext->setVisible(true);
2375 else if(show_hud || show_chat)
2377 guitext->setText(narrow_to_wide(program_name_and_version).c_str());
2378 guitext->setVisible(true);
2382 guitext->setVisible(false);
2388 snprintf(temptext, 300,
2389 "(% .1f, % .1f, % .1f)"
2391 player_position.X/BS,
2392 player_position.Y/BS,
2393 player_position.Z/BS,
2394 wrapDegrees_0_360(camera_yaw));
2396 guitext2->setText(narrow_to_wide(temptext).c_str());
2397 guitext2->setVisible(true);
2401 guitext2->setVisible(false);
2405 guitext_info->setText(infotext.c_str());
2406 guitext_info->setVisible(show_hud && g_menumgr.menuCount() == 0);
2410 float statustext_time_max = 3.0;
2411 if(!statustext.empty())
2413 statustext_time += dtime;
2414 if(statustext_time >= statustext_time_max)
2417 statustext_time = 0;
2420 guitext_status->setText(statustext.c_str());
2421 guitext_status->setVisible(!statustext.empty());
2423 if(!statustext.empty())
2425 s32 status_y = screensize.Y - 130;
2426 core::rect<s32> rect(
2428 status_y - guitext_status->getTextHeight(),
2432 guitext_status->setRelativePosition(rect);
2435 video::SColor initial_color(255,0,0,0);
2436 if(guienv->getSkin())
2437 initial_color = guienv->getSkin()->getColor(gui::EGDC_BUTTON_TEXT);
2438 video::SColor final_color = initial_color;
2439 final_color.setAlpha(0);
2440 video::SColor fade_color =
2441 initial_color.getInterpolated_quadratic(
2444 statustext_time / (float) statustext_time_max);
2445 guitext_status->setOverrideColor(fade_color);
2446 guitext_status->enableOverrideColor(true);
2451 Get chat messages from client
2454 // Get new messages from error log buffer
2455 while(!chat_log_error_buf.empty())
2457 chat_backend.addMessage(L"", narrow_to_wide(
2458 chat_log_error_buf.get()));
2460 // Get new messages from client
2461 std::wstring message;
2462 while(client.getChatMessage(message))
2464 chat_backend.addUnparsedMessage(message);
2466 // Remove old messages
2467 chat_backend.step(dtime);
2469 // Display all messages in a static text element
2470 u32 recent_chat_count = chat_backend.getRecentBuffer().getLineCount();
2471 std::wstring recent_chat = chat_backend.getRecentChat();
2472 guitext_chat->setText(recent_chat.c_str());
2474 // Update gui element size and position
2475 s32 chat_y = 5+(text_height+5);
2477 chat_y += (text_height+5);
2478 core::rect<s32> rect(
2482 chat_y + guitext_chat->getTextHeight()
2484 guitext_chat->setRelativePosition(rect);
2486 // Don't show chat if disabled or empty or profiler is enabled
2487 guitext_chat->setVisible(show_chat && recent_chat_count != 0
2495 if(client.getPlayerItem() != new_playeritem)
2497 client.selectPlayerItem(new_playeritem);
2499 if(client.getLocalInventoryUpdated())
2501 //infostream<<"Updating local inventory"<<std::endl;
2502 client.getLocalInventory(local_inventory);
2504 update_wielded_item_trigger = true;
2506 if(update_wielded_item_trigger)
2508 update_wielded_item_trigger = false;
2509 // Update wielded tool
2510 InventoryList *mlist = local_inventory.getList("main");
2513 item = mlist->getItem(client.getPlayerItem());
2514 camera.wield(item, gamedef);
2521 TimeTaker tt_draw("mainloop: draw");
2525 TimeTaker timer("beginScene");
2526 //driver->beginScene(false, true, bgcolor);
2527 //driver->beginScene(true, true, bgcolor);
2528 driver->beginScene(true, true, skycolor);
2529 beginscenetime = timer.stop(true);
2534 //infostream<<"smgr->drawAll()"<<std::endl;
2536 TimeTaker timer("smgr");
2538 scenetime = timer.stop(true);
2542 //TimeTaker timer9("auxiliary drawings");
2546 //TimeTaker //timer10("//timer10");
2552 driver->setMaterial(m);
2554 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
2558 for(core::list<aabb3f>::Iterator i=hilightboxes.begin();
2559 i != hilightboxes.end(); i++)
2561 /*infostream<<"hilightbox min="
2562 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
2564 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
2566 driver->draw3DBox(*i, video::SColor(255,0,0,0));
2575 // Warning: This clears the Z buffer.
2576 camera.drawWieldedTool();
2583 client.getEnv().getClientMap().renderPostFx();
2589 if(show_profiler_graph)
2591 graph.draw(10, screensize.Y - 10, driver, font);
2599 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2600 displaycenter + core::vector2d<s32>(10,0),
2601 video::SColor(255,255,255,255));
2602 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2603 displaycenter + core::vector2d<s32>(0,10),
2604 video::SColor(255,255,255,255));
2610 //TimeTaker //timer11("//timer11");
2623 draw_hotbar(driver, font, gamedef,
2624 v2s32(displaycenter.X, screensize.Y),
2625 hotbar_imagesize, hotbar_itemcount, &local_inventory,
2626 client.getHP(), client.getPlayerItem());
2632 if(damage_flash_timer > 0.0)
2634 damage_flash_timer -= dtime;
2636 video::SColor color(128,255,0,0);
2637 driver->draw2DRectangle(color,
2638 core::rect<s32>(0,0,screensize.X,screensize.Y),
2643 driver->clearZBuffer();
2644 // Draw some sky things
2645 //draw_horizon(driver, camera.getCameraNode());
2651 TimeTaker timer("endScene");
2653 endscenetime = timer.stop(true);
2656 drawtime = tt_draw.stop(true);
2657 g_profiler->graphAdd("mainloop_draw", (float)drawtime/1000.0f);
2663 static s16 lastFPS = 0;
2664 //u16 fps = driver->getFPS();
2665 u16 fps = (1.0/dtime_avg1);
2669 core::stringw str = L"Minetest [";
2670 str += driver->getName();
2674 device->setWindowCaption(str.c_str());
2679 Log times and stuff for visualization
2681 Profiler::GraphValues values;
2682 g_profiler->graphGet(values);
2691 if(gui_chat_console)
2692 gui_chat_console->drop();
2695 Draw a "shutting down" screen, which will be shown while the map
2696 generator and other stuff quits
2699 /*gui::IGUIStaticText *gui_shuttingdowntext = */
2700 draw_load_screen(L"Shutting down stuff...", driver, font);
2701 /*driver->beginScene(true, true, video::SColor(255,0,0,0));
2704 gui_shuttingdowntext->remove();*/
2707 chat_backend.addMessage(L"", L"# Disconnected.");
2708 chat_backend.addMessage(L"", L"");
2710 // Client scope (client is destructed before destructing *def and tsrc)