3 Copyright (C) 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.
20 #include "common_irrlicht.h"
24 #include "guiPauseMenu.h"
25 #include "guiInventoryMenu.h"
26 #include "guiTextInputMenu.h"
27 #include "guiFurnaceMenu.h"
28 #include "materials.h"
33 Setting this to 1 enables a special camera mode that forces
34 the renderers to think that the camera statically points from
35 the starting place to a static direction.
37 This allows one to move around with the player and see what
38 is actually drawn behind solid things and behind the player.
40 #define FIELD_OF_VIEW_TEST 0
43 MapDrawControl draw_control;
52 ChatLine(const std::wstring &a_text):
65 // Inventory actions from the menu are buffered here before sending
66 Queue<InventoryAction*> inventory_action_queue;
67 // This is a copy of the inventory that the client's environment has
68 Inventory local_inventory;
70 u16 g_selected_item = 0;
76 struct TextDestSign : public TextDest
78 TextDestSign(v3s16 blockpos, s16 id, Client *client)
80 m_blockpos = blockpos;
84 void gotText(std::wstring text)
86 std::string ntext = wide_to_narrow(text);
87 dstream<<"Changing text of a sign object: "
89 m_client->sendSignText(m_blockpos, m_id, ntext);
97 struct TextDestChat : public TextDest
99 TextDestChat(Client *client)
103 void gotText(std::wstring text)
105 // Discard empty line
109 // Parse command (server command starts with "/#")
110 if(text[0] == L'/' && text[1] != L'#')
112 std::wstring reply = L"Local: ";
114 reply += L"Local commands not yet supported. "
115 L"Server prefix is \"/#\".";
117 m_client->addChatMessage(reply);
122 m_client->sendChatMessage(text);
124 m_client->addChatMessage(text);
130 struct TextDestSignNode : public TextDest
132 TextDestSignNode(v3s16 p, Client *client)
137 void gotText(std::wstring text)
139 std::string ntext = wide_to_narrow(text);
140 dstream<<"Changing text of a sign node: "
142 m_client->sendSignNodeText(m_p, ntext);
150 Render distance feedback loop
152 void updateViewingRange(f32 frametime_in, Client *client)
154 if(draw_control.range_all == true)
157 static f32 added_frametime = 0;
158 static s16 added_frames = 0;
160 added_frametime += frametime_in;
163 // Actually this counter kind of sucks because frametime is busytime
164 static f32 counter = 0;
165 counter -= frametime_in;
171 /*dstream<<__FUNCTION_NAME
172 <<": Collected "<<added_frames<<" frames, total of "
173 <<added_frametime<<"s."<<std::endl;*/
175 /*dstream<<"draw_control.blocks_drawn="
176 <<draw_control.blocks_drawn
177 <<", draw_control.blocks_would_have_drawn="
178 <<draw_control.blocks_would_have_drawn
181 float range_min = g_settings.getS16("viewing_range_nodes_min");
182 float range_max = g_settings.getS16("viewing_range_nodes_max");
184 draw_control.wanted_min_range = range_min;
185 draw_control.wanted_max_blocks = (1.2*draw_control.blocks_drawn)+1;
187 float block_draw_ratio = 1.0;
188 if(draw_control.blocks_would_have_drawn != 0)
190 block_draw_ratio = (float)draw_control.blocks_drawn
191 / (float)draw_control.blocks_would_have_drawn;
194 // Calculate the average frametime in the case that all wanted
195 // blocks had been drawn
196 f32 frametime = added_frametime / added_frames / block_draw_ratio;
198 added_frametime = 0.0;
201 float wanted_fps = g_settings.getFloat("wanted_fps");
202 float wanted_frametime = 1.0 / wanted_fps;
204 f32 wanted_frametime_change = wanted_frametime - frametime;
205 //dstream<<"wanted_frametime_change="<<wanted_frametime_change<<std::endl;
207 // If needed frametime change is small, just return
208 if(fabs(wanted_frametime_change) < wanted_frametime*0.4)
210 //dstream<<"ignoring small wanted_frametime_change"<<std::endl;
214 float range = draw_control.wanted_range;
215 float new_range = range;
217 static s16 range_old = 0;
218 static f32 frametime_old = 0;
220 float d_range = range - range_old;
221 f32 d_frametime = frametime - frametime_old;
222 // A sane default of 30ms per 50 nodes of range
223 static f32 time_per_range = 30. / 50;
226 time_per_range = d_frametime / d_range;
229 // The minimum allowed calculated frametime-range derivative:
230 // Practically this sets the maximum speed of changing the range.
231 // The lower this value, the higher the maximum changing speed.
232 // A low value here results in wobbly range (0.001)
233 // A high value here results in slow changing range (0.0025)
234 // SUGG: This could be dynamically adjusted so that when
235 // the camera is turning, this is lower
236 //float min_time_per_range = 0.0015;
237 float min_time_per_range = 0.0010;
238 //float min_time_per_range = 0.05 / range;
239 if(time_per_range < min_time_per_range)
241 time_per_range = min_time_per_range;
242 //dstream<<"time_per_range="<<time_per_range<<" (min)"<<std::endl;
246 //dstream<<"time_per_range="<<time_per_range<<std::endl;
249 f32 wanted_range_change = wanted_frametime_change / time_per_range;
250 // Dampen the change a bit to kill oscillations
251 //wanted_range_change *= 0.9;
252 //wanted_range_change *= 0.75;
253 wanted_range_change *= 0.5;
254 //dstream<<"wanted_range_change="<<wanted_range_change<<std::endl;
256 // If needed range change is very small, just return
257 if(fabs(wanted_range_change) < 0.001)
259 //dstream<<"ignoring small wanted_range_change"<<std::endl;
263 new_range += wanted_range_change;
264 //dstream<<"new_range="<<new_range/*<<std::endl*/;
266 //float new_range_unclamped = new_range;
267 if(new_range < range_min)
268 new_range = range_min;
269 if(new_range > range_max)
270 new_range = range_max;
272 /*if(new_range != new_range_unclamped)
273 dstream<<", clamped to "<<new_range<<std::endl;
275 dstream<<std::endl;*/
277 draw_control.wanted_range = new_range;
279 range_old = new_range;
280 frametime_old = frametime;
286 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
287 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
288 Inventory *inventory, s32 halfheartcount)
290 InventoryList *mainlist = inventory->getList("main");
293 dstream<<"WARNING: draw_hotbar(): mainlist == NULL"<<std::endl;
297 s32 padding = imgsize/12;
298 //s32 height = imgsize + padding*2;
299 s32 width = itemcount*(imgsize+padding*2);
301 // Position of upper left corner of bar
302 v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
304 // Draw background color
305 /*core::rect<s32> barrect(0,0,width,height);
307 video::SColor bgcolor(255,128,128,128);
308 driver->draw2DRectangle(bgcolor, barrect, NULL);*/
310 core::rect<s32> imgrect(0,0,imgsize,imgsize);
312 for(s32 i=0; i<itemcount; i++)
314 InventoryItem *item = mainlist->getItem(i);
316 core::rect<s32> rect = imgrect + pos
317 + v2s32(padding+i*(imgsize+padding*2), padding);
319 if(g_selected_item == i)
321 driver->draw2DRectangle(video::SColor(255,255,0,0),
322 core::rect<s32>(rect.UpperLeftCorner - v2s32(1,1)*padding,
323 rect.LowerRightCorner + v2s32(1,1)*padding),
328 video::SColor bgcolor2(128,0,0,0);
329 driver->draw2DRectangle(bgcolor2, rect, NULL);
334 drawInventoryItem(driver, font, item, rect, NULL);
342 video::ITexture *heart_texture =
343 driver->getTexture(porting::getDataPath("heart.png").c_str());
344 v2s32 p = pos + v2s32(0, -20);
345 for(s32 i=0; i<halfheartcount/2; i++)
347 const video::SColor color(255,255,255,255);
348 const video::SColor colors[] = {color,color,color,color};
349 core::rect<s32> rect(0,0,16,16);
351 driver->draw2DImage(heart_texture, rect,
352 core::rect<s32>(core::position2d<s32>(0,0),
353 core::dimension2di(heart_texture->getOriginalSize())),
357 if(halfheartcount % 2 == 1)
359 const video::SColor color(255,255,255,255);
360 const video::SColor colors[] = {color,color,color,color};
361 core::rect<s32> rect(0,0,16/2,16);
363 core::dimension2di srcd(heart_texture->getOriginalSize());
365 driver->draw2DImage(heart_texture, rect,
366 core::rect<s32>(core::position2d<s32>(0,0), srcd),
374 Find what the player is pointing at
376 void getPointedNode(Client *client, v3f player_position,
377 v3f camera_direction, v3f camera_position,
378 bool &nodefound, core::line3d<f32> shootline,
379 v3s16 &nodepos, v3s16 &neighbourpos,
380 core::aabbox3d<f32> &nodehilightbox,
383 f32 mindistance = BS * 1001;
385 v3s16 pos_i = floatToInt(player_position, BS);
387 /*std::cout<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
391 s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
392 s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
393 s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
394 s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
395 s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
396 s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
398 for(s16 y = ystart; y <= yend; y++)
399 for(s16 z = zstart; z <= zend; z++)
400 for(s16 x = xstart; x <= xend; x++)
405 n = client->getNode(v3s16(x,y,z));
406 if(content_pointable(n.d) == false)
409 catch(InvalidPositionException &e)
415 v3f npf = intToFloat(np, BS);
420 v3s16(0,0,1), // back
422 v3s16(1,0,0), // right
423 v3s16(0,0,-1), // front
424 v3s16(0,-1,0), // bottom
425 v3s16(-1,0,0), // left
431 if(n.d == CONTENT_TORCH)
433 v3s16 dir = unpackDir(n.dir);
434 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
435 dir_f *= BS/2 - BS/6 - BS/20;
436 v3f cpf = npf + dir_f;
437 f32 distance = (cpf - camera_position).getLength();
439 core::aabbox3d<f32> box;
442 if(dir == v3s16(0,-1,0))
444 box = core::aabbox3d<f32>(
445 npf - v3f(BS/6, BS/2, BS/6),
446 npf + v3f(BS/6, -BS/2+BS/3*2, BS/6)
450 else if(dir == v3s16(0,1,0))
452 box = core::aabbox3d<f32>(
453 npf - v3f(BS/6, -BS/2+BS/3*2, BS/6),
454 npf + v3f(BS/6, BS/2, BS/6)
460 box = core::aabbox3d<f32>(
461 cpf - v3f(BS/6, BS/3, BS/6),
462 cpf + v3f(BS/6, BS/3, BS/6)
466 if(distance < mindistance)
468 if(box.intersectsWithLine(shootline))
473 mindistance = distance;
474 nodehilightbox = box;
478 else if(n.d == CONTENT_SIGN_WALL)
480 v3s16 dir = unpackDir(n.dir);
481 v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
482 dir_f *= BS/2 - BS/6 - BS/20;
483 v3f cpf = npf + dir_f;
484 f32 distance = (cpf - camera_position).getLength();
488 v3f(BS*0.42,-BS*0.35,-BS*0.4),
489 v3f(BS*0.49, BS*0.35, BS*0.4),
492 for(s32 i=0; i<2; i++)
494 if(dir == v3s16(1,0,0))
495 vertices[i].rotateXZBy(0);
496 if(dir == v3s16(-1,0,0))
497 vertices[i].rotateXZBy(180);
498 if(dir == v3s16(0,0,1))
499 vertices[i].rotateXZBy(90);
500 if(dir == v3s16(0,0,-1))
501 vertices[i].rotateXZBy(-90);
502 if(dir == v3s16(0,-1,0))
503 vertices[i].rotateXYBy(-90);
504 if(dir == v3s16(0,1,0))
505 vertices[i].rotateXYBy(90);
510 core::aabbox3d<f32> box;
512 box = core::aabbox3d<f32>(vertices[0]);
513 box.addInternalPoint(vertices[1]);
515 if(distance < mindistance)
517 if(box.intersectsWithLine(shootline))
522 mindistance = distance;
523 nodehilightbox = box;
532 for(u16 i=0; i<6; i++)
534 v3f dir_f = v3f(dirs[i].X,
535 dirs[i].Y, dirs[i].Z);
536 v3f centerpoint = npf + dir_f * BS/2;
538 (centerpoint - camera_position).getLength();
540 if(distance < mindistance)
542 core::CMatrix4<f32> m;
543 m.buildRotateFromTo(v3f(0,0,1), dir_f);
545 // This is the back face
547 v3f(BS/2, BS/2, BS/2),
548 v3f(-BS/2, -BS/2, BS/2+d)
551 for(u16 j=0; j<2; j++)
553 m.rotateVect(corners[j]);
557 core::aabbox3d<f32> facebox(corners[0]);
558 facebox.addInternalPoint(corners[1]);
560 if(facebox.intersectsWithLine(shootline))
564 neighbourpos = np + dirs[i];
565 mindistance = distance;
567 //nodehilightbox = facebox;
569 const float d = 0.502;
570 core::aabbox3d<f32> nodebox
571 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
572 v3f nodepos_f = intToFloat(nodepos, BS);
573 nodebox.MinEdge += nodepos_f;
574 nodebox.MaxEdge += nodepos_f;
575 nodehilightbox = nodebox;
577 } // if distance < mindistance
587 IrrlichtDevice *device,
590 std::string playername,
593 std::wstring &error_message
596 video::IVideoDriver* driver = device->getVideoDriver();
597 scene::ISceneManager* smgr = device->getSceneManager();
599 v2u32 screensize(0,0);
600 v2u32 last_screensize(0,0);
601 screensize = driver->getScreenSize();
603 const s32 hotbar_itemcount = 8;
604 const s32 hotbar_imagesize = 36;
606 // The color of the sky
608 //video::SColor skycolor = video::SColor(255,90,140,200);
609 //video::SColor skycolor = video::SColor(255,166,202,244);
610 //video::SColor skycolor = video::SColor(255,120,185,244);
611 video::SColor skycolor = video::SColor(255,140,186,250);
614 Draw "Loading" screen
616 const wchar_t *text = L"Loading and connecting...";
617 u32 text_height = font->getDimension(text).Height;
618 core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
619 core::vector2d<s32> textsize(300, text_height);
620 core::rect<s32> textrect(center - textsize/2, center + textsize/2);
622 gui::IGUIStaticText *gui_loadingtext = guienv->addStaticText(
623 text, textrect, false, false);
624 gui_loadingtext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
626 driver->beginScene(true, true, video::SColor(255,0,0,0));
630 std::cout<<DTIME<<"Creating server and client"<<std::endl;
634 SharedPtr will delete it when it goes out of scope.
636 SharedPtr<Server> server;
638 server = new Server(map_dir);
646 Client client(device, playername.c_str(), draw_control);
648 Address connect_address(0,0,0,0, port);
651 //connect_address.Resolve("localhost");
652 connect_address.setAddress(127,0,0,1);
654 connect_address.Resolve(address.c_str());
656 catch(ResolveError &e)
658 std::cout<<DTIME<<"Couldn't resolve address"<<std::endl;
660 error_message = L"Couldn't resolve address";
661 gui_loadingtext->remove();
666 Attempt to connect to the server
669 dstream<<DTIME<<"Connecting to server at ";
670 connect_address.print(&dstream);
672 client.connect(connect_address);
674 bool could_connect = false;
677 float time_counter = 0.0;
680 if(client.connectedAndInitialized())
682 could_connect = true;
685 // Wait for 10 seconds
686 if(time_counter >= 10.0)
692 driver->beginScene(true, true, video::SColor(255,0,0,0));
696 // Update client and server
708 catch(con::PeerNotFoundException &e)
711 if(could_connect == false)
713 std::cout<<DTIME<<"Timed out."<<std::endl;
714 error_message = L"Connection timed out.";
715 gui_loadingtext->remove();
722 /*scene::ISceneNode* skybox;
723 skybox = smgr->addSkyBoxSceneNode(
724 driver->getTexture(porting::getDataPath("skybox2.png").c_str()),
725 driver->getTexture(porting::getDataPath("skybox3.png").c_str()),
726 driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
727 driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
728 driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
729 driver->getTexture(porting::getDataPath("skybox1.png").c_str()));*/
732 Create the camera node
735 scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(
737 v3f(BS*100, BS*2, BS*100), // Look from
738 v3f(BS*100+1, BS*2, BS*100), // Look to
744 error_message = L"Failed to create the camera node";
748 camera->setFOV(FOV_ANGLE);
750 // Just so big a value that everything rendered is visible
751 camera->setFarValue(100000*BS);
753 f32 camera_yaw = 0; // "right/left"
754 f32 camera_pitch = 0; // "up/down"
760 float cloud_height = BS*100;
761 //float cloud_height = BS*55;
762 //float cloud_height = BS*20;
763 Clouds *clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1,
770 gui_loadingtext->remove();
776 // First line of debug text
777 gui::IGUIStaticText *guitext = guienv->addStaticText(
779 core::rect<s32>(5, 5, 795, 5+text_height),
781 // Second line of debug text
782 gui::IGUIStaticText *guitext2 = guienv->addStaticText(
784 core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
787 // At the middle of the screen
788 // Object infos are shown in this
789 gui::IGUIStaticText *guitext_info = guienv->addStaticText(
791 core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
795 gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
797 core::rect<s32>(0,0,0,0),
798 false, false); // Disable word wrap as of now
800 //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
801 core::list<ChatLine> chat_lines;
803 /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
804 (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
805 /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
806 (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
808 // Test the text input system
809 /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
811 /*GUIMessageMenu *menu =
812 new GUIMessageMenu(guienv, guiroot, -1,
818 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
819 &g_menumgr))->drop();
822 /*guitext2->setVisible(true);
823 guitext_info->setVisible(true);
824 guitext_chat->setVisible(true);*/
826 //s32 guitext_chat_pad_bottom = 70;
829 Some statistics are collected in these
832 u32 beginscenetime = 0;
834 u32 endscenetime = 0;
837 //throw con::PeerNotFoundException("lol");
839 core::list<float> frametime_log;
841 float damage_flash_timer = 0;
847 bool first_loop_after_window_activation = true;
849 // Time is in milliseconds
850 // NOTE: getRealTime() causes strange problems in wine (imprecision?)
851 // NOTE: So we have to use getTime() and call run()s between them
852 u32 lasttime = device->getTimer()->getTime();
854 while(device->run() && kill == false)
856 if(g_gamecallback->disconnect_requested)
858 g_gamecallback->disconnect_requested = false;
863 Process TextureSource's queue
865 ((TextureSource*)g_texturesource)->processQueue();
870 last_screensize = screensize;
871 screensize = driver->getScreenSize();
872 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
873 //bool screensize_changed = screensize != last_screensize;
875 // Hilight boxes collected during the loop and displayed
876 core::list< core::aabbox3d<f32> > hilightboxes;
879 std::wstring infotext;
881 // When screen size changes, update positions and sizes of stuff
882 /*if(screensize_changed)
884 v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
885 quick_inventory->updatePosition(pos);
888 //TimeTaker //timer1("//timer1");
890 // Time of frame without fps limit
894 // not using getRealTime is necessary for wine
895 u32 time = device->getTimer()->getTime();
897 busytime_u32 = time - lasttime;
900 busytime = busytime_u32 / 1000.0;
903 //std::cout<<"busytime_u32="<<busytime_u32<<std::endl;
905 // Necessary for device->getTimer()->getTime()
912 updateViewingRange(busytime, &client);
919 float fps_max = g_settings.getFloat("fps_max");
920 u32 frametime_min = 1000./fps_max;
922 if(busytime_u32 < frametime_min)
924 u32 sleeptime = frametime_min - busytime_u32;
925 device->sleep(sleeptime);
929 // Necessary for device->getTimer()->getTime()
933 Time difference calculation
935 f32 dtime; // in seconds
937 u32 time = device->getTimer()->getTime();
939 dtime = (time - lasttime) / 1000.0;
945 Log frametime for visualization
947 frametime_log.push_back(dtime);
948 if(frametime_log.size() > 100)
950 core::list<float>::Iterator i = frametime_log.begin();
951 frametime_log.erase(i);
955 Visualize frametime in terminal
957 /*for(u32 i=0; i<dtime*400; i++)
959 std::cout<<std::endl;*/
962 Time average and jitter calculation
965 static f32 dtime_avg1 = 0.0;
966 dtime_avg1 = dtime_avg1 * 0.98 + dtime * 0.02;
967 f32 dtime_jitter1 = dtime - dtime_avg1;
969 static f32 dtime_jitter1_max_sample = 0.0;
970 static f32 dtime_jitter1_max_fraction = 0.0;
972 static f32 jitter1_max = 0.0;
973 static f32 counter = 0.0;
974 if(dtime_jitter1 > jitter1_max)
975 jitter1_max = dtime_jitter1;
980 dtime_jitter1_max_sample = jitter1_max;
981 dtime_jitter1_max_fraction
982 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
988 Busytime average and jitter calculation
991 static f32 busytime_avg1 = 0.0;
992 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
993 f32 busytime_jitter1 = busytime - busytime_avg1;
995 static f32 busytime_jitter1_max_sample = 0.0;
996 static f32 busytime_jitter1_min_sample = 0.0;
998 static f32 jitter1_max = 0.0;
999 static f32 jitter1_min = 0.0;
1000 static f32 counter = 0.0;
1001 if(busytime_jitter1 > jitter1_max)
1002 jitter1_max = busytime_jitter1;
1003 if(busytime_jitter1 < jitter1_min)
1004 jitter1_min = busytime_jitter1;
1008 busytime_jitter1_max_sample = jitter1_max;
1009 busytime_jitter1_min_sample = jitter1_min;
1016 Debug info for client
1019 static float counter = 0.0;
1024 client.printDebugInfo(std::cout);
1029 Direct handling of user input
1032 // Reset input if window not active or some menu is active
1033 if(device->isWindowActive() == false || noMenuActive() == false)
1038 // Input handler step() (used by the random input generator)
1042 Launch menus according to keys
1044 if(input->wasKeyDown(irr::KEY_KEY_I))
1046 dstream<<DTIME<<"the_game: "
1047 <<"Launching inventory"<<std::endl;
1049 GUIInventoryMenu *menu =
1050 new GUIInventoryMenu(guienv, guiroot, -1,
1051 &g_menumgr, v2s16(8,7),
1052 client.getInventoryContext(),
1055 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1056 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1057 "list", "current_player", "main",
1058 v2s32(0, 3), v2s32(8, 4)));
1059 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1060 "list", "current_player", "craft",
1061 v2s32(3, 0), v2s32(3, 3)));
1062 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1063 "list", "current_player", "craftresult",
1064 v2s32(7, 1), v2s32(1, 1)));
1066 menu->setDrawSpec(draw_spec);
1070 else if(input->wasKeyDown(irr::KEY_ESCAPE))
1072 dstream<<DTIME<<"the_game: "
1073 <<"Launching pause menu"<<std::endl;
1074 // It will delete itself by itself
1075 (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1076 &g_menumgr))->drop();
1078 else if(input->wasKeyDown(irr::KEY_KEY_T))
1080 TextDest *dest = new TextDestChat(&client);
1082 (new GUITextInputMenu(guienv, guiroot, -1,
1087 // Item selection with mouse wheel
1089 s32 wheel = input->getMouseWheel();
1090 u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1091 hotbar_itemcount-1);
1095 if(g_selected_item < max_item)
1098 g_selected_item = 0;
1102 if(g_selected_item > 0)
1105 g_selected_item = max_item;
1110 for(u16 i=0; i<10; i++)
1112 s32 keycode = irr::KEY_KEY_1 + i;
1114 keycode = irr::KEY_KEY_0;
1115 if(input->wasKeyDown((irr::EKEY_CODE)keycode))
1117 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1119 g_selected_item = i;
1121 dstream<<DTIME<<"Selected item: "
1122 <<g_selected_item<<std::endl;
1127 // Viewing range selection
1128 if(input->wasKeyDown(irr::KEY_KEY_R))
1130 if(draw_control.range_all)
1132 draw_control.range_all = false;
1133 dstream<<DTIME<<"Disabled full viewing range"<<std::endl;
1137 draw_control.range_all = true;
1138 dstream<<DTIME<<"Enabled full viewing range"<<std::endl;
1142 // Print debug stacks
1143 if(input->wasKeyDown(irr::KEY_KEY_P))
1145 dstream<<"-----------------------------------------"
1147 dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1148 dstream<<"-----------------------------------------"
1150 debug_stacks_print();
1154 Player speed control
1167 PlayerControl control(
1168 input->isKeyDown(irr::KEY_KEY_W),
1169 input->isKeyDown(irr::KEY_KEY_S),
1170 input->isKeyDown(irr::KEY_KEY_A),
1171 input->isKeyDown(irr::KEY_KEY_D),
1172 input->isKeyDown(irr::KEY_SPACE),
1173 input->isKeyDown(irr::KEY_KEY_E),
1174 input->isKeyDown(irr::KEY_LSHIFT)
1175 || input->isKeyDown(irr::KEY_RSHIFT),
1179 client.setPlayerControl(control);
1188 //TimeTaker timer("server->step(dtime)");
1189 server->step(dtime);
1197 //TimeTaker timer("client.step(dtime)");
1199 //client.step(dtime_avg1);
1202 // Read client events
1205 ClientEvent event = client.getClientEvent();
1206 if(event.type == CE_NONE)
1210 else if(event.type == CE_PLAYER_DAMAGE)
1212 //u16 damage = event.player_damage.amount;
1213 //dstream<<"Player damage: "<<damage<<std::endl;
1214 damage_flash_timer = 0.05;
1216 else if(event.type == CE_PLAYER_FORCE_MOVE)
1218 camera_yaw = event.player_force_move.yaw;
1219 camera_pitch = event.player_force_move.pitch;
1223 // Get player position
1224 v3f player_position = client.getPlayerPosition();
1226 //TimeTaker //timer2("//timer2");
1229 Mouse and camera control
1232 if((device->isWindowActive() && noMenuActive()) || random_input)
1235 device->getCursorControl()->setVisible(false);
1237 if(first_loop_after_window_activation){
1238 //std::cout<<"window active, first loop"<<std::endl;
1239 first_loop_after_window_activation = false;
1242 s32 dx = input->getMousePos().X - displaycenter.X;
1243 s32 dy = input->getMousePos().Y - displaycenter.Y;
1244 //std::cout<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1246 const float keyspeed = 500;
1247 if(input->isKeyDown(irr::KEY_UP))
1248 dy -= dtime * keyspeed;
1249 if(input->isKeyDown(irr::KEY_DOWN))
1250 dy += dtime * keyspeed;
1251 if(input->isKeyDown(irr::KEY_LEFT))
1252 dx -= dtime * keyspeed;
1253 if(input->isKeyDown(irr::KEY_RIGHT))
1254 dx += dtime * keyspeed;
1256 camera_yaw -= dx*0.2;
1257 camera_pitch += dy*0.2;
1258 if(camera_pitch < -89.5) camera_pitch = -89.5;
1259 if(camera_pitch > 89.5) camera_pitch = 89.5;
1261 input->setMousePos(displaycenter.X, displaycenter.Y);
1264 device->getCursorControl()->setVisible(true);
1266 //std::cout<<"window inactive"<<std::endl;
1267 first_loop_after_window_activation = true;
1270 camera_yaw = wrapDegrees(camera_yaw);
1271 camera_pitch = wrapDegrees(camera_pitch);
1273 v3f camera_direction = v3f(0,0,1);
1274 camera_direction.rotateYZBy(camera_pitch);
1275 camera_direction.rotateXZBy(camera_yaw);
1277 // This is at the height of the eyes of the current figure
1278 //v3f camera_position = player_position + v3f(0, BS+BS/2, 0);
1279 // This is more like in minecraft
1280 v3f camera_position = player_position + v3f(0, BS+BS*0.625, 0);
1282 camera->setPosition(camera_position);
1283 // *100.0 helps in large map coordinates
1284 camera->setTarget(camera_position + camera_direction * 100.0);
1286 if(FIELD_OF_VIEW_TEST){
1287 client.updateCamera(v3f(0,0,0), v3f(0,0,1));
1290 //TimeTaker timer("client.updateCamera");
1291 client.updateCamera(camera_position, camera_direction);
1295 //TimeTaker //timer3("//timer3");
1298 Calculate what block is the crosshair pointing to
1301 //u32 t1 = device->getTimer()->getRealTime();
1303 //f32 d = 4; // max. distance
1304 f32 d = 4; // max. distance
1305 core::line3d<f32> shootline(camera_position,
1306 camera_position + camera_direction * BS * (d+1));
1308 MapBlockObject *selected_object = client.getSelectedObject
1309 (d*BS, camera_position, shootline);
1311 ClientActiveObject *selected_active_object
1312 = client.getSelectedActiveObject
1313 (d*BS, camera_position, shootline);
1315 if(selected_object != NULL)
1317 //dstream<<"Client returned selected_object != NULL"<<std::endl;
1319 core::aabbox3d<f32> box_on_map
1320 = selected_object->getSelectionBoxOnMap();
1322 hilightboxes.push_back(box_on_map);
1324 infotext = narrow_to_wide(selected_object->infoText());
1326 if(input->getLeftClicked())
1328 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1329 client.clickObject(0, selected_object->getBlock()->getPos(),
1330 selected_object->getId(), g_selected_item);
1332 else if(input->getRightClicked())
1334 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1336 Check if we want to modify the object ourselves
1338 if(selected_object->getTypeId() == MAPBLOCKOBJECT_TYPE_SIGN)
1340 dstream<<"Sign object right-clicked"<<std::endl;
1342 if(random_input == false)
1344 // Get a new text for it
1346 TextDest *dest = new TextDestSign(
1347 selected_object->getBlock()->getPos(),
1348 selected_object->getId(),
1351 SignObject *sign_object = (SignObject*)selected_object;
1353 std::wstring wtext =
1354 narrow_to_wide(sign_object->getText());
1356 (new GUITextInputMenu(guienv, guiroot, -1,
1362 Otherwise pass the event to the server as-is
1366 client.clickObject(1, selected_object->getBlock()->getPos(),
1367 selected_object->getId(), g_selected_item);
1371 else if(selected_active_object != NULL)
1373 //dstream<<"Client returned selected_active_object != NULL"<<std::endl;
1375 core::aabbox3d<f32> *selection_box
1376 = selected_active_object->getSelectionBox();
1377 // Box should exist because object was returned in the
1379 assert(selection_box);
1381 v3f pos = selected_active_object->getPosition();
1383 core::aabbox3d<f32> box_on_map(
1384 selection_box->MinEdge + pos,
1385 selection_box->MaxEdge + pos
1388 hilightboxes.push_back(box_on_map);
1390 //infotext = narrow_to_wide("A ClientActiveObject");
1391 infotext = narrow_to_wide(selected_active_object->infoText());
1393 if(input->getLeftClicked())
1395 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1396 client.clickActiveObject(0,
1397 selected_active_object->getId(), g_selected_item);
1399 else if(input->getRightClicked())
1401 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1404 else // selected_object == NULL
1408 Find out which node we are pointing at
1411 bool nodefound = false;
1414 core::aabbox3d<f32> nodehilightbox;
1416 getPointedNode(&client, player_position,
1417 camera_direction, camera_position,
1418 nodefound, shootline,
1419 nodepos, neighbourpos,
1422 static float nodig_delay_counter = 0.0;
1426 static v3s16 nodepos_old(-32768,-32768,-32768);
1428 static float dig_time = 0.0;
1429 static u16 dig_index = 0;
1435 hilightboxes.push_back(nodehilightbox);
1438 Check information text of node
1441 NodeMetadata *meta = client.getNodeMetadata(nodepos);
1444 infotext = narrow_to_wide(meta->infoText());
1447 //MapNode node = client.getNode(nodepos);
1453 if(input->getLeftReleased())
1455 client.clearTempMod(nodepos);
1459 if(nodig_delay_counter > 0.0)
1461 nodig_delay_counter -= dtime;
1465 if(nodepos != nodepos_old)
1467 std::cout<<DTIME<<"Pointing at ("<<nodepos.X<<","
1468 <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1470 if(nodepos_old != v3s16(-32768,-32768,-32768))
1472 client.clearTempMod(nodepos_old);
1477 if(input->getLeftClicked() ||
1478 (input->getLeftState() && nodepos != nodepos_old))
1480 dstream<<DTIME<<"Started digging"<<std::endl;
1481 client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1483 if(input->getLeftClicked())
1485 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1487 if(input->getLeftState())
1489 MapNode n = client.getNode(nodepos);
1491 // Get tool name. Default is "" = bare hands
1492 std::string toolname = "";
1493 InventoryList *mlist = local_inventory.getList("main");
1496 InventoryItem *item = mlist->getItem(g_selected_item);
1497 if(item && (std::string)item->getName() == "ToolItem")
1499 ToolItem *titem = (ToolItem*)item;
1500 toolname = titem->getToolName();
1504 // Get digging properties for material and tool
1506 DiggingProperties prop =
1507 getDiggingProperties(material, toolname);
1509 float dig_time_complete = 0.0;
1511 if(prop.diggable == false)
1513 /*dstream<<"Material "<<(int)material
1514 <<" not diggable with \""
1515 <<toolname<<"\""<<std::endl;*/
1516 // I guess nobody will wait for this long
1517 dig_time_complete = 10000000.0;
1521 dig_time_complete = prop.time;
1524 if(dig_time_complete >= 0.001)
1526 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1527 * dig_time/dig_time_complete);
1529 // This is for torches
1532 dig_index = CRACK_ANIMATION_LENGTH;
1535 if(dig_index < CRACK_ANIMATION_LENGTH)
1537 //TimeTaker timer("client.setTempMod");
1538 //dstream<<"dig_index="<<dig_index<<std::endl;
1539 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1543 dstream<<DTIME<<"Digging completed"<<std::endl;
1544 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1545 client.clearTempMod(nodepos);
1546 client.removeNode(nodepos);
1550 nodig_delay_counter = dig_time_complete
1551 / (float)CRACK_ANIMATION_LENGTH;
1553 // We don't want a corresponding delay to
1554 // very time consuming nodes
1555 if(nodig_delay_counter > 0.5)
1557 nodig_delay_counter = 0.5;
1559 // We want a slight delay to very little
1560 // time consuming nodes
1561 float mindelay = 0.15;
1562 if(nodig_delay_counter < mindelay)
1564 nodig_delay_counter = mindelay;
1572 if(input->getRightClicked())
1574 std::cout<<DTIME<<"Ground right-clicked"<<std::endl;
1576 if(meta && meta->typeId() == CONTENT_SIGN_WALL && !random_input)
1578 dstream<<"Sign node right-clicked"<<std::endl;
1580 SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
1582 // Get a new text for it
1584 TextDest *dest = new TextDestSignNode(nodepos, &client);
1586 std::wstring wtext =
1587 narrow_to_wide(signmeta->getText());
1589 (new GUITextInputMenu(guienv, guiroot, -1,
1593 else if(meta && meta->typeId() == CONTENT_CHEST && !random_input)
1595 dstream<<"Chest node right-clicked"<<std::endl;
1597 //ChestNodeMetadata *chestmeta = (ChestNodeMetadata*)meta;
1599 std::string chest_inv_id;
1600 chest_inv_id += "nodemeta:";
1601 chest_inv_id += itos(nodepos.X);
1602 chest_inv_id += ",";
1603 chest_inv_id += itos(nodepos.Y);
1604 chest_inv_id += ",";
1605 chest_inv_id += itos(nodepos.Z);
1607 GUIInventoryMenu *menu =
1608 new GUIInventoryMenu(guienv, guiroot, -1,
1609 &g_menumgr, v2s16(8,9),
1610 client.getInventoryContext(),
1613 core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1615 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1616 "list", chest_inv_id, "0",
1617 v2s32(0, 0), v2s32(8, 4)));
1618 draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1619 "list", "current_player", "main",
1620 v2s32(0, 5), v2s32(8, 4)));
1622 menu->setDrawSpec(draw_spec);
1627 else if(meta && meta->typeId() == CONTENT_FURNACE && !random_input)
1629 dstream<<"Furnace node right-clicked"<<std::endl;
1631 GUIFurnaceMenu *menu =
1632 new GUIFurnaceMenu(guienv, guiroot, -1,
1633 &g_menumgr, nodepos, &client);
1640 client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1644 nodepos_old = nodepos;
1649 } // selected_object == NULL
1651 input->resetLeftClicked();
1652 input->resetRightClicked();
1654 if(input->getLeftReleased())
1656 std::cout<<DTIME<<"Left button released (stopped digging)"
1658 client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1660 if(input->getRightReleased())
1662 //std::cout<<DTIME<<"Right released"<<std::endl;
1666 input->resetLeftReleased();
1667 input->resetRightReleased();
1670 Calculate stuff for drawing
1673 camera->setAspectRatio((f32)screensize.X / (f32)screensize.Y);
1675 u32 daynight_ratio = client.getDayNightRatio();
1676 u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1677 video::SColor bgcolor = video::SColor(
1679 skycolor.getRed() * l / 255,
1680 skycolor.getGreen() * l / 255,
1681 skycolor.getBlue() * l / 255);
1686 clouds->step(dtime);
1687 clouds->update(v2f(player_position.X, player_position.Z), (float)l/255.0);
1693 if(g_settings.getBool("enable_fog") == true)
1695 f32 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
1696 if(draw_control.range_all)
1701 video::EFT_FOG_LINEAR,
1713 video::EFT_FOG_LINEAR,
1724 Update gui stuff (0ms)
1727 //TimeTaker guiupdatetimer("Gui updating");
1730 static float drawtime_avg = 0;
1731 drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
1732 static float beginscenetime_avg = 0;
1733 beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
1734 static float scenetime_avg = 0;
1735 scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
1736 static float endscenetime_avg = 0;
1737 endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
1740 snprintf(temptext, 300, "Minetest-c55 %s ("
1743 " drawtime=%.0f, beginscenetime=%.0f"
1744 ", scenetime=%.0f, endscenetime=%.0f",
1746 draw_control.range_all,
1753 guitext->setText(narrow_to_wide(temptext).c_str());
1758 snprintf(temptext, 300,
1759 "(% .1f, % .1f, % .1f)"
1760 " (% .3f < btime_jitter < % .3f"
1761 ", dtime_jitter = % .1f %%"
1762 ", v_range = %.1f)",
1763 player_position.X/BS,
1764 player_position.Y/BS,
1765 player_position.Z/BS,
1766 busytime_jitter1_min_sample,
1767 busytime_jitter1_max_sample,
1768 dtime_jitter1_max_fraction * 100.0,
1769 draw_control.wanted_range
1772 guitext2->setText(narrow_to_wide(temptext).c_str());
1776 guitext_info->setText(infotext.c_str());
1780 Get chat messages from client
1784 std::wstring message;
1785 while(client.getChatMessage(message))
1787 chat_lines.push_back(ChatLine(message));
1788 /*if(chat_lines.size() > 6)
1790 core::list<ChatLine>::Iterator
1791 i = chat_lines.begin();
1792 chat_lines.erase(i);
1795 // Append them to form the whole static text and throw
1796 // it to the gui element
1798 // This will correspond to the line number counted from
1799 // top to bottom, from size-1 to 0
1800 s16 line_number = chat_lines.size();
1801 // Count of messages to be removed from the top
1802 u16 to_be_removed_count = 0;
1803 for(core::list<ChatLine>::Iterator
1804 i = chat_lines.begin();
1805 i != chat_lines.end(); i++)
1807 // After this, line number is valid for this loop
1812 This results in a maximum age of 60*6 to the
1813 lowermost line and a maximum of 6 lines
1815 float allowed_age = (6-line_number) * 60.0;
1817 if((*i).age > allowed_age)
1819 to_be_removed_count++;
1822 whole += (*i).text + L'\n';
1824 for(u16 i=0; i<to_be_removed_count; i++)
1826 core::list<ChatLine>::Iterator
1827 it = chat_lines.begin();
1828 chat_lines.erase(it);
1830 guitext_chat->setText(whole.c_str());
1832 // Update gui element size and position
1834 /*core::rect<s32> rect(
1836 screensize.Y - guitext_chat_pad_bottom
1837 - text_height*chat_lines.size(),
1839 screensize.Y - guitext_chat_pad_bottom
1841 core::rect<s32> rect(
1845 50 + text_height*chat_lines.size()
1848 guitext_chat->setRelativePosition(rect);
1850 if(chat_lines.size() == 0)
1851 guitext_chat->setVisible(false);
1853 guitext_chat->setVisible(true);
1860 static u16 old_selected_item = 65535;
1861 if(client.getLocalInventoryUpdated()
1862 || g_selected_item != old_selected_item)
1864 old_selected_item = g_selected_item;
1865 //std::cout<<"Updating local inventory"<<std::endl;
1866 client.getLocalInventory(local_inventory);
1870 Send actions returned by the inventory menu
1872 while(inventory_action_queue.size() != 0)
1874 InventoryAction *a = inventory_action_queue.pop_front();
1876 client.sendInventoryAction(a);
1885 TimeTaker drawtimer("Drawing");
1889 TimeTaker timer("beginScene");
1890 driver->beginScene(true, true, bgcolor);
1891 //driver->beginScene(false, true, bgcolor);
1892 beginscenetime = timer.stop(true);
1897 //std::cout<<DTIME<<"smgr->drawAll()"<<std::endl;
1900 TimeTaker timer("smgr");
1902 scenetime = timer.stop(true);
1906 //TimeTaker timer9("auxiliary drawings");
1910 //TimeTaker //timer10("//timer10");
1916 driver->setMaterial(m);
1918 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
1920 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
1921 i != hilightboxes.end(); i++)
1923 /*std::cout<<"hilightbox min="
1924 <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
1926 <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
1928 driver->draw3DBox(*i, video::SColor(255,0,0,0));
1934 if(g_settings.getBool("frametime_graph") == true)
1937 for(core::list<float>::Iterator
1938 i = frametime_log.begin();
1939 i != frametime_log.end();
1942 driver->draw2DLine(v2s32(x,50),
1943 v2s32(x,50+(*i)*1000),
1944 video::SColor(255,255,255,255));
1952 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
1953 displaycenter + core::vector2d<s32>(10,0),
1954 video::SColor(255,255,255,255));
1955 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
1956 displaycenter + core::vector2d<s32>(0,10),
1957 video::SColor(255,255,255,255));
1962 //TimeTaker //timer11("//timer11");
1974 draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y),
1975 hotbar_imagesize, hotbar_itemcount, &local_inventory,
1982 if(damage_flash_timer > 0.0)
1984 damage_flash_timer -= dtime;
1986 video::SColor color(128,255,0,0);
1987 driver->draw2DRectangle(color,
1988 core::rect<s32>(0,0,screensize.X,screensize.Y),
1996 TimeTaker timer("endScene");
1998 endscenetime = timer.stop(true);
2001 drawtime = drawtimer.stop(true);
2007 static s16 lastFPS = 0;
2008 //u16 fps = driver->getFPS();
2009 u16 fps = (1.0/dtime_avg1);
2013 core::stringw str = L"Minetest [";
2014 str += driver->getName();
2018 device->setWindowCaption(str.c_str());