]> git.lizzy.rs Git - dragonfireclient.git/blob - src/game.cpp
removed a leftover debug print
[dragonfireclient.git] / src / game.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "common_irrlicht.h"
21 #include "game.h"
22 #include "client.h"
23 #include "server.h"
24 #include "guiPauseMenu.h"
25 #include "guiInventoryMenu.h"
26 #include "guiTextInputMenu.h"
27 #include "guiFurnaceMenu.h"
28 #include "materials.h"
29 #include "config.h"
30 #include "clouds.h"
31 #include "keycode.h"
32
33 /*
34         Setting this to 1 enables a special camera mode that forces
35         the renderers to think that the camera statically points from
36         the starting place to a static direction.
37
38         This allows one to move around with the player and see what
39         is actually drawn behind solid things and behind the player.
40 */
41 #define FIELD_OF_VIEW_TEST 0
42
43
44 MapDrawControl draw_control;
45
46 // Chat data
47 struct ChatLine
48 {
49         ChatLine():
50                 age(0.0)
51         {
52         }
53         ChatLine(const std::wstring &a_text):
54                 age(0.0),
55                 text(a_text)
56         {
57         }
58         float age;
59         std::wstring text;
60 };
61
62 /*
63         Inventory stuff
64 */
65
66 // Inventory actions from the menu are buffered here before sending
67 Queue<InventoryAction*> inventory_action_queue;
68 // This is a copy of the inventory that the client's environment has
69 Inventory local_inventory;
70
71 u16 g_selected_item = 0;
72
73 /*
74         Text input system
75 */
76
77 struct TextDestSign : public TextDest
78 {
79         TextDestSign(v3s16 blockpos, s16 id, Client *client)
80         {
81                 m_blockpos = blockpos;
82                 m_id = id;
83                 m_client = client;
84         }
85         void gotText(std::wstring text)
86         {
87                 std::string ntext = wide_to_narrow(text);
88                 dstream<<"Changing text of a sign object: "
89                                 <<ntext<<std::endl;
90                 m_client->sendSignText(m_blockpos, m_id, ntext);
91         }
92
93         v3s16 m_blockpos;
94         s16 m_id;
95         Client *m_client;
96 };
97
98 struct TextDestChat : public TextDest
99 {
100         TextDestChat(Client *client)
101         {
102                 m_client = client;
103         }
104         void gotText(std::wstring text)
105         {
106                 // Discard empty line
107                 if(text == L"")
108                         return;
109                 
110                 // Parse command (server command starts with "/#")
111                 if(text[0] == L'/' && text[1] != L'#')
112                 {
113                         std::wstring reply = L"Local: ";
114
115                         reply += L"Local commands not yet supported. "
116                                         L"Server prefix is \"/#\".";
117                         
118                         m_client->addChatMessage(reply);
119                         return;
120                 }
121
122                 // Send to others
123                 m_client->sendChatMessage(text);
124                 // Show locally
125                 m_client->addChatMessage(text);
126         }
127
128         Client *m_client;
129 };
130
131 struct TextDestSignNode : public TextDest
132 {
133         TextDestSignNode(v3s16 p, Client *client)
134         {
135                 m_p = p;
136                 m_client = client;
137         }
138         void gotText(std::wstring text)
139         {
140                 std::string ntext = wide_to_narrow(text);
141                 dstream<<"Changing text of a sign node: "
142                                 <<ntext<<std::endl;
143                 m_client->sendSignNodeText(m_p, ntext);
144         }
145
146         v3s16 m_p;
147         Client *m_client;
148 };
149
150 /*
151         Render distance feedback loop
152 */
153 void updateViewingRange(f32 frametime_in, Client *client)
154 {
155         if(draw_control.range_all == true)
156                 return;
157         
158         static f32 added_frametime = 0;
159         static s16 added_frames = 0;
160
161         added_frametime += frametime_in;
162         added_frames += 1;
163
164         // Actually this counter kind of sucks because frametime is busytime
165         static f32 counter = 0;
166         counter -= frametime_in;
167         if(counter > 0)
168                 return;
169         //counter = 0.1;
170         counter = 0.2;
171
172         /*dstream<<__FUNCTION_NAME
173                         <<": Collected "<<added_frames<<" frames, total of "
174                         <<added_frametime<<"s."<<std::endl;*/
175         
176         /*dstream<<"draw_control.blocks_drawn="
177                         <<draw_control.blocks_drawn
178                         <<", draw_control.blocks_would_have_drawn="
179                         <<draw_control.blocks_would_have_drawn
180                         <<std::endl;*/
181         
182         float range_min = g_settings.getS16("viewing_range_nodes_min");
183         float range_max = g_settings.getS16("viewing_range_nodes_max");
184         
185         // Limit minimum to keep the feedback loop stable
186         if(range_min < 5)
187                 range_min = 5;
188         
189         draw_control.wanted_min_range = range_min;
190         //draw_control.wanted_max_blocks = (1.5*draw_control.blocks_drawn)+1;
191         draw_control.wanted_max_blocks = (1.5*draw_control.blocks_would_have_drawn)+1;
192         if(draw_control.wanted_max_blocks < 10)
193                 draw_control.wanted_max_blocks = 10;
194         
195         float block_draw_ratio = 1.0;
196         if(draw_control.blocks_would_have_drawn != 0)
197         {
198                 block_draw_ratio = (float)draw_control.blocks_drawn
199                         / (float)draw_control.blocks_would_have_drawn;
200         }
201
202         // Calculate the average frametime in the case that all wanted
203         // blocks had been drawn
204         f32 frametime = added_frametime / added_frames / block_draw_ratio;
205         
206         added_frametime = 0.0;
207         added_frames = 0;
208         
209         float wanted_fps = g_settings.getFloat("wanted_fps");
210         float wanted_frametime = 1.0 / wanted_fps;
211         
212         f32 wanted_frametime_change = wanted_frametime - frametime;
213         //dstream<<"wanted_frametime_change="<<wanted_frametime_change<<std::endl;
214         
215         // If needed frametime change is small, just return
216         if(fabs(wanted_frametime_change) < wanted_frametime*0.4)
217         {
218                 //dstream<<"ignoring small wanted_frametime_change"<<std::endl;
219                 return;
220         }
221
222         float range = draw_control.wanted_range;
223         float new_range = range;
224
225         static s16 range_old = 0;
226         static f32 frametime_old = 0;
227         
228         float d_range = range - range_old;
229         f32 d_frametime = frametime - frametime_old;
230         // A sane default of 30ms per 50 nodes of range
231         static f32 time_per_range = 30. / 50;
232         if(d_range != 0)
233         {
234                 time_per_range = d_frametime / d_range;
235         }
236         
237         // The minimum allowed calculated frametime-range derivative:
238         // Practically this sets the maximum speed of changing the range.
239         // The lower this value, the higher the maximum changing speed.
240         // A low value here results in wobbly range (0.001)
241         // A high value here results in slow changing range (0.0025)
242         // SUGG: This could be dynamically adjusted so that when
243         //       the camera is turning, this is lower
244         //float min_time_per_range = 0.0015;
245         float min_time_per_range = 0.0010;
246         //float min_time_per_range = 0.05 / range;
247         if(time_per_range < min_time_per_range)
248         {
249                 time_per_range = min_time_per_range;
250                 //dstream<<"time_per_range="<<time_per_range<<" (min)"<<std::endl;
251         }
252         else
253         {
254                 //dstream<<"time_per_range="<<time_per_range<<std::endl;
255         }
256
257         f32 wanted_range_change = wanted_frametime_change / time_per_range;
258         // Dampen the change a bit to kill oscillations
259         //wanted_range_change *= 0.9;
260         //wanted_range_change *= 0.75;
261         wanted_range_change *= 0.5;
262         //dstream<<"wanted_range_change="<<wanted_range_change<<std::endl;
263
264         // If needed range change is very small, just return
265         if(fabs(wanted_range_change) < 0.001)
266         {
267                 //dstream<<"ignoring small wanted_range_change"<<std::endl;
268                 return;
269         }
270
271         new_range += wanted_range_change;
272         
273         float new_range_unclamped = new_range;
274         if(new_range < range_min)
275                 new_range = range_min;
276         if(new_range > range_max)
277                 new_range = range_max;
278         
279         /*dstream<<"new_range="<<new_range_unclamped
280                         <<", clamped to "<<new_range<<std::endl;*/
281
282         draw_control.wanted_range = new_range;
283
284         range_old = new_range;
285         frametime_old = frametime;
286 }
287
288 /*
289         Hotbar draw routine
290 */
291 void draw_hotbar(video::IVideoDriver *driver, gui::IGUIFont *font,
292                 v2s32 centerlowerpos, s32 imgsize, s32 itemcount,
293                 Inventory *inventory, s32 halfheartcount)
294 {
295         InventoryList *mainlist = inventory->getList("main");
296         if(mainlist == NULL)
297         {
298                 dstream<<"WARNING: draw_hotbar(): mainlist == NULL"<<std::endl;
299                 return;
300         }
301         
302         s32 padding = imgsize/12;
303         //s32 height = imgsize + padding*2;
304         s32 width = itemcount*(imgsize+padding*2);
305         
306         // Position of upper left corner of bar
307         v2s32 pos = centerlowerpos - v2s32(width/2, imgsize+padding*2);
308         
309         // Draw background color
310         /*core::rect<s32> barrect(0,0,width,height);
311         barrect += pos;
312         video::SColor bgcolor(255,128,128,128);
313         driver->draw2DRectangle(bgcolor, barrect, NULL);*/
314
315         core::rect<s32> imgrect(0,0,imgsize,imgsize);
316
317         for(s32 i=0; i<itemcount; i++)
318         {
319                 InventoryItem *item = mainlist->getItem(i);
320                 
321                 core::rect<s32> rect = imgrect + pos
322                                 + v2s32(padding+i*(imgsize+padding*2), padding);
323                 
324                 if(g_selected_item == i)
325                 {
326                         driver->draw2DRectangle(video::SColor(255,255,0,0),
327                                         core::rect<s32>(rect.UpperLeftCorner - v2s32(1,1)*padding,
328                                                         rect.LowerRightCorner + v2s32(1,1)*padding),
329                                         NULL);
330                 }
331                 else
332                 {
333                         video::SColor bgcolor2(128,0,0,0);
334                         driver->draw2DRectangle(bgcolor2, rect, NULL);
335                 }
336
337                 if(item != NULL)
338                 {
339                         drawInventoryItem(driver, font, item, rect, NULL);
340                 }
341         }
342         
343         /*
344                 Draw hearts
345         */
346         {
347                 video::ITexture *heart_texture =
348                                 driver->getTexture(porting::getDataPath("heart.png").c_str());
349                 v2s32 p = pos + v2s32(0, -20);
350                 for(s32 i=0; i<halfheartcount/2; i++)
351                 {
352                         const video::SColor color(255,255,255,255);
353                         const video::SColor colors[] = {color,color,color,color};
354                         core::rect<s32> rect(0,0,16,16);
355                         rect += p;
356                         driver->draw2DImage(heart_texture, rect,
357                                 core::rect<s32>(core::position2d<s32>(0,0),
358                                 core::dimension2di(heart_texture->getOriginalSize())),
359                                 NULL, colors, true);
360                         p += v2s32(20,0);
361                 }
362                 if(halfheartcount % 2 == 1)
363                 {
364                         const video::SColor color(255,255,255,255);
365                         const video::SColor colors[] = {color,color,color,color};
366                         core::rect<s32> rect(0,0,16/2,16);
367                         rect += p;
368                         core::dimension2di srcd(heart_texture->getOriginalSize());
369                         srcd.Width /= 2;
370                         driver->draw2DImage(heart_texture, rect,
371                                 core::rect<s32>(core::position2d<s32>(0,0), srcd),
372                                 NULL, colors, true);
373                         p += v2s32(20,0);
374                 }
375         }
376 }
377
378 /*
379         Find what the player is pointing at
380 */
381 void getPointedNode(Client *client, v3f player_position,
382                 v3f camera_direction, v3f camera_position,
383                 bool &nodefound, core::line3d<f32> shootline,
384                 v3s16 &nodepos, v3s16 &neighbourpos,
385                 core::aabbox3d<f32> &nodehilightbox,
386                 f32 d)
387 {
388         f32 mindistance = BS * 1001;
389         
390         v3s16 pos_i = floatToInt(player_position, BS);
391
392         /*std::cout<<"pos_i=("<<pos_i.X<<","<<pos_i.Y<<","<<pos_i.Z<<")"
393                         <<std::endl;*/
394
395         s16 a = d;
396         s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1);
397         s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1);
398         s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1);
399         s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1);
400         s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1);
401         s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1);
402         
403         for(s16 y = ystart; y <= yend; y++)
404         for(s16 z = zstart; z <= zend; z++)
405         for(s16 x = xstart; x <= xend; x++)
406         {
407                 MapNode n;
408                 try
409                 {
410                         n = client->getNode(v3s16(x,y,z));
411                         if(content_pointable(n.d) == false)
412                                 continue;
413                 }
414                 catch(InvalidPositionException &e)
415                 {
416                         continue;
417                 }
418
419                 v3s16 np(x,y,z);
420                 v3f npf = intToFloat(np, BS);
421                 
422                 f32 d = 0.01;
423                 
424                 v3s16 dirs[6] = {
425                         v3s16(0,0,1), // back
426                         v3s16(0,1,0), // top
427                         v3s16(1,0,0), // right
428                         v3s16(0,0,-1), // front
429                         v3s16(0,-1,0), // bottom
430                         v3s16(-1,0,0), // left
431                 };
432                 
433                 /*
434                         Meta-objects
435                 */
436                 if(n.d == CONTENT_TORCH)
437                 {
438                         v3s16 dir = unpackDir(n.dir);
439                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
440                         dir_f *= BS/2 - BS/6 - BS/20;
441                         v3f cpf = npf + dir_f;
442                         f32 distance = (cpf - camera_position).getLength();
443
444                         core::aabbox3d<f32> box;
445                         
446                         // bottom
447                         if(dir == v3s16(0,-1,0))
448                         {
449                                 box = core::aabbox3d<f32>(
450                                         npf - v3f(BS/6, BS/2, BS/6),
451                                         npf + v3f(BS/6, -BS/2+BS/3*2, BS/6)
452                                 );
453                         }
454                         // top
455                         else if(dir == v3s16(0,1,0))
456                         {
457                                 box = core::aabbox3d<f32>(
458                                         npf - v3f(BS/6, -BS/2+BS/3*2, BS/6),
459                                         npf + v3f(BS/6, BS/2, BS/6)
460                                 );
461                         }
462                         // side
463                         else
464                         {
465                                 box = core::aabbox3d<f32>(
466                                         cpf - v3f(BS/6, BS/3, BS/6),
467                                         cpf + v3f(BS/6, BS/3, BS/6)
468                                 );
469                         }
470
471                         if(distance < mindistance)
472                         {
473                                 if(box.intersectsWithLine(shootline))
474                                 {
475                                         nodefound = true;
476                                         nodepos = np;
477                                         neighbourpos = np;
478                                         mindistance = distance;
479                                         nodehilightbox = box;
480                                 }
481                         }
482                 }
483                 else if(n.d == CONTENT_SIGN_WALL)
484                 {
485                         v3s16 dir = unpackDir(n.dir);
486                         v3f dir_f = v3f(dir.X, dir.Y, dir.Z);
487                         dir_f *= BS/2 - BS/6 - BS/20;
488                         v3f cpf = npf + dir_f;
489                         f32 distance = (cpf - camera_position).getLength();
490
491                         v3f vertices[4] =
492                         {
493                                 v3f(BS*0.42,-BS*0.35,-BS*0.4),
494                                 v3f(BS*0.49, BS*0.35, BS*0.4),
495                         };
496
497                         for(s32 i=0; i<2; i++)
498                         {
499                                 if(dir == v3s16(1,0,0))
500                                         vertices[i].rotateXZBy(0);
501                                 if(dir == v3s16(-1,0,0))
502                                         vertices[i].rotateXZBy(180);
503                                 if(dir == v3s16(0,0,1))
504                                         vertices[i].rotateXZBy(90);
505                                 if(dir == v3s16(0,0,-1))
506                                         vertices[i].rotateXZBy(-90);
507                                 if(dir == v3s16(0,-1,0))
508                                         vertices[i].rotateXYBy(-90);
509                                 if(dir == v3s16(0,1,0))
510                                         vertices[i].rotateXYBy(90);
511
512                                 vertices[i] += npf;
513                         }
514
515                         core::aabbox3d<f32> box;
516
517                         box = core::aabbox3d<f32>(vertices[0]);
518                         box.addInternalPoint(vertices[1]);
519
520                         if(distance < mindistance)
521                         {
522                                 if(box.intersectsWithLine(shootline))
523                                 {
524                                         nodefound = true;
525                                         nodepos = np;
526                                         neighbourpos = np;
527                                         mindistance = distance;
528                                         nodehilightbox = box;
529                                 }
530                         }
531                 }
532                 /*
533                         Regular blocks
534                 */
535                 else
536                 {
537                         for(u16 i=0; i<6; i++)
538                         {
539                                 v3f dir_f = v3f(dirs[i].X,
540                                                 dirs[i].Y, dirs[i].Z);
541                                 v3f centerpoint = npf + dir_f * BS/2;
542                                 f32 distance =
543                                                 (centerpoint - camera_position).getLength();
544                                 
545                                 if(distance < mindistance)
546                                 {
547                                         core::CMatrix4<f32> m;
548                                         m.buildRotateFromTo(v3f(0,0,1), dir_f);
549
550                                         // This is the back face
551                                         v3f corners[2] = {
552                                                 v3f(BS/2, BS/2, BS/2),
553                                                 v3f(-BS/2, -BS/2, BS/2+d)
554                                         };
555                                         
556                                         for(u16 j=0; j<2; j++)
557                                         {
558                                                 m.rotateVect(corners[j]);
559                                                 corners[j] += npf;
560                                         }
561
562                                         core::aabbox3d<f32> facebox(corners[0]);
563                                         facebox.addInternalPoint(corners[1]);
564
565                                         if(facebox.intersectsWithLine(shootline))
566                                         {
567                                                 nodefound = true;
568                                                 nodepos = np;
569                                                 neighbourpos = np + dirs[i];
570                                                 mindistance = distance;
571
572                                                 //nodehilightbox = facebox;
573
574                                                 const float d = 0.502;
575                                                 core::aabbox3d<f32> nodebox
576                                                                 (-BS*d, -BS*d, -BS*d, BS*d, BS*d, BS*d);
577                                                 v3f nodepos_f = intToFloat(nodepos, BS);
578                                                 nodebox.MinEdge += nodepos_f;
579                                                 nodebox.MaxEdge += nodepos_f;
580                                                 nodehilightbox = nodebox;
581                                         }
582                                 } // if distance < mindistance
583                         } // for dirs
584                 } // regular block
585         } // for coords
586 }
587
588 void update_skybox(video::IVideoDriver* driver,
589                 scene::ISceneManager* smgr, scene::ISceneNode* &skybox,
590                 float brightness)
591 {
592         if(skybox)
593         {
594                 skybox->remove();
595         }
596         
597         if(brightness >= 0.5)
598         {
599                 skybox = smgr->addSkyBoxSceneNode(
600                         driver->getTexture(porting::getDataPath("skybox2.png").c_str()),
601                         driver->getTexture(porting::getDataPath("skybox3.png").c_str()),
602                         driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
603                         driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
604                         driver->getTexture(porting::getDataPath("skybox1.png").c_str()),
605                         driver->getTexture(porting::getDataPath("skybox1.png").c_str()));
606         }
607         else if(brightness >= 0.2)
608         {
609                 skybox = smgr->addSkyBoxSceneNode(
610                         driver->getTexture(porting::getDataPath("skybox2_dawn.png").c_str()),
611                         driver->getTexture(porting::getDataPath("skybox3_dawn.png").c_str()),
612                         driver->getTexture(porting::getDataPath("skybox1_dawn.png").c_str()),
613                         driver->getTexture(porting::getDataPath("skybox1_dawn.png").c_str()),
614                         driver->getTexture(porting::getDataPath("skybox1_dawn.png").c_str()),
615                         driver->getTexture(porting::getDataPath("skybox1_dawn.png").c_str()));
616         }
617         else
618         {
619                 skybox = smgr->addSkyBoxSceneNode(
620                         driver->getTexture(porting::getDataPath("skybox2_night.png").c_str()),
621                         driver->getTexture(porting::getDataPath("skybox3_night.png").c_str()),
622                         driver->getTexture(porting::getDataPath("skybox1_night.png").c_str()),
623                         driver->getTexture(porting::getDataPath("skybox1_night.png").c_str()),
624                         driver->getTexture(porting::getDataPath("skybox1_night.png").c_str()),
625                         driver->getTexture(porting::getDataPath("skybox1_night.png").c_str()));
626         }
627 }
628
629 void the_game(
630         bool &kill,
631         bool random_input,
632         InputHandler *input,
633         IrrlichtDevice *device,
634         gui::IGUIFont* font,
635         std::string map_dir,
636         std::string playername,
637         std::string address,
638         u16 port,
639         std::wstring &error_message
640 )
641 {
642         video::IVideoDriver* driver = device->getVideoDriver();
643         scene::ISceneManager* smgr = device->getSceneManager();
644
645         v2u32 screensize(0,0);
646         v2u32 last_screensize(0,0);
647         screensize = driver->getScreenSize();
648
649         const s32 hotbar_itemcount = 8;
650         const s32 hotbar_imagesize = 36;
651         
652         // The color of the sky
653
654         //video::SColor skycolor = video::SColor(255,140,186,250);
655
656         video::SColor bgcolor_bright = video::SColor(255,170,200,230);
657
658         /*
659                 Draw "Loading" screen
660         */
661         const wchar_t *loadingtext = L"Loading and connecting...";
662         u32 text_height = font->getDimension(loadingtext).Height;
663         core::vector2d<s32> center(screensize.X/2, screensize.Y/2);
664         core::vector2d<s32> textsize(300, text_height);
665         core::rect<s32> textrect(center - textsize/2, center + textsize/2);
666
667         gui::IGUIStaticText *gui_loadingtext = guienv->addStaticText(
668                         loadingtext, textrect, false, false);
669         gui_loadingtext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
670
671         driver->beginScene(true, true, video::SColor(255,0,0,0));
672         guienv->drawAll();
673         driver->endScene();
674
675         std::cout<<DTIME<<"Creating server and client"<<std::endl;
676         
677         /*
678                 Create server.
679                 SharedPtr will delete it when it goes out of scope.
680         */
681         SharedPtr<Server> server;
682         if(address == ""){
683                 server = new Server(map_dir);
684                 server->start(port);
685         }
686         
687         /*
688                 Create client
689         */
690
691         Client client(device, playername.c_str(), draw_control);
692                         
693         Address connect_address(0,0,0,0, port);
694         try{
695                 if(address == "")
696                         //connect_address.Resolve("localhost");
697                         connect_address.setAddress(127,0,0,1);
698                 else
699                         connect_address.Resolve(address.c_str());
700         }
701         catch(ResolveError &e)
702         {
703                 std::cout<<DTIME<<"Couldn't resolve address"<<std::endl;
704                 //return 0;
705                 error_message = L"Couldn't resolve address";
706                 gui_loadingtext->remove();
707                 return;
708         }
709
710         /*
711                 Attempt to connect to the server
712         */
713         
714         dstream<<DTIME<<"Connecting to server at ";
715         connect_address.print(&dstream);
716         dstream<<std::endl;
717         client.connect(connect_address);
718
719         bool could_connect = false;
720         
721         try{
722                 float time_counter = 0.0;
723                 for(;;)
724                 {
725                         if(client.connectedAndInitialized())
726                         {
727                                 could_connect = true;
728                                 break;
729                         }
730                         // Wait for 10 seconds
731                         if(time_counter >= 10.0)
732                         {
733                                 break;
734                         }
735
736                         // Update screen
737                         driver->beginScene(true, true, video::SColor(255,0,0,0));
738                         guienv->drawAll();
739                         driver->endScene();
740
741                         // Update client and server
742
743                         client.step(0.1);
744
745                         if(server != NULL)
746                                 server->step(0.1);
747                         
748                         // Delay a bit
749                         sleep_ms(100);
750                         time_counter += 0.1;
751                 }
752         }
753         catch(con::PeerNotFoundException &e)
754         {}
755
756         if(could_connect == false)
757         {
758                 std::cout<<DTIME<<"Timed out."<<std::endl;
759                 error_message = L"Connection timed out.";
760                 gui_loadingtext->remove();
761                 return;
762         }
763
764         /*
765                 Create skybox
766         */
767         float old_brightness = 1.0;
768         scene::ISceneNode* skybox = NULL;
769         update_skybox(driver, smgr, skybox, 1.0);
770         
771         /*
772                 Create the camera node
773         */
774
775         scene::ICameraSceneNode* camera = smgr->addCameraSceneNode(
776                 0, // Camera parent
777                 v3f(BS*100, BS*2, BS*100), // Look from
778                 v3f(BS*100+1, BS*2, BS*100), // Look to
779                 -1 // Camera ID
780         );
781
782         if(camera == NULL)
783         {
784                 error_message = L"Failed to create the camera node";
785                 return;
786         }
787
788         camera->setFOV(FOV_ANGLE);
789
790         // Just so big a value that everything rendered is visible
791         camera->setFarValue(100000*BS);
792         
793         f32 camera_yaw = 0; // "right/left"
794         f32 camera_pitch = 0; // "up/down"
795
796         /*
797                 Clouds
798         */
799         
800         float cloud_height = BS*100;
801         Clouds *clouds = NULL;
802         clouds = new Clouds(smgr->getRootSceneNode(), smgr, -1,
803                         cloud_height, time(0));
804
805         /*
806                 Move into game
807         */
808         
809         gui_loadingtext->remove();
810
811         /*
812                 Add some gui stuff
813         */
814
815         // First line of debug text
816         gui::IGUIStaticText *guitext = guienv->addStaticText(
817                         L"Minetest-c55",
818                         core::rect<s32>(5, 5, 795, 5+text_height),
819                         false, false);
820         // Second line of debug text
821         gui::IGUIStaticText *guitext2 = guienv->addStaticText(
822                         L"",
823                         core::rect<s32>(5, 5+(text_height+5)*1, 795, (5+text_height)*2),
824                         false, false);
825         
826         // At the middle of the screen
827         // Object infos are shown in this
828         gui::IGUIStaticText *guitext_info = guienv->addStaticText(
829                         L"",
830                         core::rect<s32>(0,0,400,text_height+5) + v2s32(100,200),
831                         false, false);
832         
833         // Chat text
834         gui::IGUIStaticText *guitext_chat = guienv->addStaticText(
835                         L"",
836                         core::rect<s32>(0,0,0,0),
837                         false, false); // Disable word wrap as of now
838                         //false, true);
839         //guitext_chat->setBackgroundColor(video::SColor(96,0,0,0));
840         core::list<ChatLine> chat_lines;
841         
842         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
843                         (guienv, NULL, v2s32(10, 70), 5, &local_inventory);*/
844         /*GUIQuickInventory *quick_inventory = new GUIQuickInventory
845                         (guienv, NULL, v2s32(0, 0), quickinv_itemcount, &local_inventory);*/
846         
847         // Test the text input system
848         /*(new GUITextInputMenu(guienv, guiroot, -1, &g_menumgr,
849                         NULL))->drop();*/
850         /*GUIMessageMenu *menu =
851                         new GUIMessageMenu(guienv, guiroot, -1, 
852                                 &g_menumgr,
853                                 L"Asd");
854         menu->drop();*/
855         
856         // Launch pause menu
857         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
858                         &g_menumgr))->drop();
859         
860         // Enable texts
861         /*guitext2->setVisible(true);
862         guitext_info->setVisible(true);
863         guitext_chat->setVisible(true);*/
864
865         //s32 guitext_chat_pad_bottom = 70;
866
867         /*
868                 Some statistics are collected in these
869         */
870         u32 drawtime = 0;
871         u32 beginscenetime = 0;
872         u32 scenetime = 0;
873         u32 endscenetime = 0;
874         
875         // A test
876         //throw con::PeerNotFoundException("lol");
877
878         core::list<float> frametime_log;
879
880         float damage_flash_timer = 0;
881
882         /*
883                 Main loop
884         */
885
886         bool first_loop_after_window_activation = true;
887
888         // Time is in milliseconds
889         // NOTE: getRealTime() causes strange problems in wine (imprecision?)
890         // NOTE: So we have to use getTime() and call run()s between them
891         u32 lasttime = device->getTimer()->getTime();
892
893         while(device->run() && kill == false)
894         {
895                 if(g_gamecallback->disconnect_requested)
896                 {
897                         g_gamecallback->disconnect_requested = false;
898                         break;
899                 }
900
901                 /*
902                         Process TextureSource's queue
903                 */
904                 ((TextureSource*)g_texturesource)->processQueue();
905
906                 /*
907                         Random calculations
908                 */
909                 last_screensize = screensize;
910                 screensize = driver->getScreenSize();
911                 v2s32 displaycenter(screensize.X/2,screensize.Y/2);
912                 //bool screensize_changed = screensize != last_screensize;
913                 
914                 // Hilight boxes collected during the loop and displayed
915                 core::list< core::aabbox3d<f32> > hilightboxes;
916                 
917                 // Info text
918                 std::wstring infotext;
919
920                 // When screen size changes, update positions and sizes of stuff
921                 /*if(screensize_changed)
922                 {
923                         v2s32 pos(displaycenter.X-((quickinv_itemcount-1)*quickinv_spacing+quickinv_size)/2, screensize.Y-quickinv_spacing);
924                         quick_inventory->updatePosition(pos);
925                 }*/
926
927                 //TimeTaker //timer1("//timer1");
928                 
929                 // Time of frame without fps limit
930                 float busytime;
931                 u32 busytime_u32;
932                 {
933                         // not using getRealTime is necessary for wine
934                         u32 time = device->getTimer()->getTime();
935                         if(time > lasttime)
936                                 busytime_u32 = time - lasttime;
937                         else
938                                 busytime_u32 = 0;
939                         busytime = busytime_u32 / 1000.0;
940                 }
941
942                 //std::cout<<"busytime_u32="<<busytime_u32<<std::endl;
943         
944                 // Necessary for device->getTimer()->getTime()
945                 device->run();
946
947                 /*
948                         Viewing range
949                 */
950                 
951                 updateViewingRange(busytime, &client);
952                 
953                 /*
954                         FPS limiter
955                 */
956
957                 {
958                         float fps_max = g_settings.getFloat("fps_max");
959                         u32 frametime_min = 1000./fps_max;
960                         
961                         if(busytime_u32 < frametime_min)
962                         {
963                                 u32 sleeptime = frametime_min - busytime_u32;
964                                 device->sleep(sleeptime);
965                         }
966                 }
967
968                 // Necessary for device->getTimer()->getTime()
969                 device->run();
970
971                 /*
972                         Time difference calculation
973                 */
974                 f32 dtime; // in seconds
975                 
976                 u32 time = device->getTimer()->getTime();
977                 if(time > lasttime)
978                         dtime = (time - lasttime) / 1000.0;
979                 else
980                         dtime = 0;
981                 lasttime = time;
982
983                 /*
984                         Log frametime for visualization
985                 */
986                 frametime_log.push_back(dtime);
987                 if(frametime_log.size() > 100)
988                 {
989                         core::list<float>::Iterator i = frametime_log.begin();
990                         frametime_log.erase(i);
991                 }
992
993                 /*
994                         Visualize frametime in terminal
995                 */
996                 /*for(u32 i=0; i<dtime*400; i++)
997                         std::cout<<"X";
998                 std::cout<<std::endl;*/
999
1000                 /*
1001                         Time average and jitter calculation
1002                 */
1003
1004                 static f32 dtime_avg1 = 0.0;
1005                 dtime_avg1 = dtime_avg1 * 0.98 + dtime * 0.02;
1006                 f32 dtime_jitter1 = dtime - dtime_avg1;
1007
1008                 static f32 dtime_jitter1_max_sample = 0.0;
1009                 static f32 dtime_jitter1_max_fraction = 0.0;
1010                 {
1011                         static f32 jitter1_max = 0.0;
1012                         static f32 counter = 0.0;
1013                         if(dtime_jitter1 > jitter1_max)
1014                                 jitter1_max = dtime_jitter1;
1015                         counter += dtime;
1016                         if(counter > 0.0)
1017                         {
1018                                 counter -= 3.0;
1019                                 dtime_jitter1_max_sample = jitter1_max;
1020                                 dtime_jitter1_max_fraction
1021                                                 = dtime_jitter1_max_sample / (dtime_avg1+0.001);
1022                                 jitter1_max = 0.0;
1023                         }
1024                 }
1025                 
1026                 /*
1027                         Busytime average and jitter calculation
1028                 */
1029
1030                 static f32 busytime_avg1 = 0.0;
1031                 busytime_avg1 = busytime_avg1 * 0.98 + busytime * 0.02;
1032                 f32 busytime_jitter1 = busytime - busytime_avg1;
1033                 
1034                 static f32 busytime_jitter1_max_sample = 0.0;
1035                 static f32 busytime_jitter1_min_sample = 0.0;
1036                 {
1037                         static f32 jitter1_max = 0.0;
1038                         static f32 jitter1_min = 0.0;
1039                         static f32 counter = 0.0;
1040                         if(busytime_jitter1 > jitter1_max)
1041                                 jitter1_max = busytime_jitter1;
1042                         if(busytime_jitter1 < jitter1_min)
1043                                 jitter1_min = busytime_jitter1;
1044                         counter += dtime;
1045                         if(counter > 0.0){
1046                                 counter -= 3.0;
1047                                 busytime_jitter1_max_sample = jitter1_max;
1048                                 busytime_jitter1_min_sample = jitter1_min;
1049                                 jitter1_max = 0.0;
1050                                 jitter1_min = 0.0;
1051                         }
1052                 }
1053                 
1054                 /*
1055                         Debug info for client
1056                 */
1057                 {
1058                         static float counter = 0.0;
1059                         counter -= dtime;
1060                         if(counter < 0)
1061                         {
1062                                 counter = 30.0;
1063                                 client.printDebugInfo(std::cout);
1064                         }
1065                 }
1066
1067                 /*
1068                         Direct handling of user input
1069                 */
1070                 
1071                 // Reset input if window not active or some menu is active
1072                 if(device->isWindowActive() == false || noMenuActive() == false)
1073                 {
1074                         input->clear();
1075                 }
1076
1077                 // Input handler step() (used by the random input generator)
1078                 input->step(dtime);
1079
1080                 /*
1081                         Launch menus according to keys
1082                 */
1083                 if(input->wasKeyDown(getKeySetting("keymap_inventory")))
1084                 {
1085                         dstream<<DTIME<<"the_game: "
1086                                         <<"Launching inventory"<<std::endl;
1087                         
1088                         GUIInventoryMenu *menu =
1089                                 new GUIInventoryMenu(guienv, guiroot, -1,
1090                                         &g_menumgr, v2s16(8,7),
1091                                         client.getInventoryContext(),
1092                                         &client);
1093
1094                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1095                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1096                                         "list", "current_player", "main",
1097                                         v2s32(0, 3), v2s32(8, 4)));
1098                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1099                                         "list", "current_player", "craft",
1100                                         v2s32(3, 0), v2s32(3, 3)));
1101                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1102                                         "list", "current_player", "craftresult",
1103                                         v2s32(7, 1), v2s32(1, 1)));
1104
1105                         menu->setDrawSpec(draw_spec);
1106
1107                         menu->drop();
1108                 }
1109                 else if(input->wasKeyDown(KEY_ESCAPE))
1110                 {
1111                         dstream<<DTIME<<"the_game: "
1112                                         <<"Launching pause menu"<<std::endl;
1113                         // It will delete itself by itself
1114                         (new GUIPauseMenu(guienv, guiroot, -1, g_gamecallback,
1115                                         &g_menumgr))->drop();
1116                 }
1117                 else if(input->wasKeyDown(getKeySetting("keymap_chat")))
1118                 {
1119                         TextDest *dest = new TextDestChat(&client);
1120
1121                         (new GUITextInputMenu(guienv, guiroot, -1,
1122                                         &g_menumgr, dest,
1123                                         L""))->drop();
1124                 }
1125
1126                 // Item selection with mouse wheel
1127                 {
1128                         s32 wheel = input->getMouseWheel();
1129                         u16 max_item = MYMIN(PLAYER_INVENTORY_SIZE-1,
1130                                         hotbar_itemcount-1);
1131
1132                         if(wheel < 0)
1133                         {
1134                                 if(g_selected_item < max_item)
1135                                         g_selected_item++;
1136                                 else
1137                                         g_selected_item = 0;
1138                         }
1139                         else if(wheel > 0)
1140                         {
1141                                 if(g_selected_item > 0)
1142                                         g_selected_item--;
1143                                 else
1144                                         g_selected_item = max_item;
1145                         }
1146                 }
1147                 
1148                 // Item selection
1149                 for(u16 i=0; i<10; i++)
1150                 {
1151                         s32 keycode = irr::KEY_KEY_1 + i;
1152                         if(i == 9)
1153                                 keycode = irr::KEY_KEY_0;
1154                         if(input->wasKeyDown((irr::EKEY_CODE)keycode))
1155                         {
1156                                 if(i < PLAYER_INVENTORY_SIZE && i < hotbar_itemcount)
1157                                 {
1158                                         g_selected_item = i;
1159
1160                                         dstream<<DTIME<<"Selected item: "
1161                                                         <<g_selected_item<<std::endl;
1162                                 }
1163                         }
1164                 }
1165
1166                 // Viewing range selection
1167                 if(input->wasKeyDown(getKeySetting("keymap_rangeselect")))
1168                 {
1169                         if(draw_control.range_all)
1170                         {
1171                                 draw_control.range_all = false;
1172                                 dstream<<DTIME<<"Disabled full viewing range"<<std::endl;
1173                         }
1174                         else
1175                         {
1176                                 draw_control.range_all = true;
1177                                 dstream<<DTIME<<"Enabled full viewing range"<<std::endl;
1178                         }
1179                 }
1180
1181                 // Print debug stacks
1182                 if(input->wasKeyDown(getKeySetting("keymap_print_debug_stacks")))
1183                 {
1184                         dstream<<"-----------------------------------------"
1185                                         <<std::endl;
1186                         dstream<<DTIME<<"Printing debug stacks:"<<std::endl;
1187                         dstream<<"-----------------------------------------"
1188                                         <<std::endl;
1189                         debug_stacks_print();
1190                 }
1191
1192                 /*
1193                         Player speed control
1194                         TODO: Cache the keycodes from getKeySetting
1195                 */
1196                 
1197                 {
1198                         /*bool a_up,
1199                         bool a_down,
1200                         bool a_left,
1201                         bool a_right,
1202                         bool a_jump,
1203                         bool a_superspeed,
1204                         bool a_sneak,
1205                         float a_pitch,
1206                         float a_yaw*/
1207                         PlayerControl control(
1208                                 input->isKeyDown(getKeySetting("keymap_forward")),
1209                                 input->isKeyDown(getKeySetting("keymap_backward")),
1210                                 input->isKeyDown(getKeySetting("keymap_left")),
1211                                 input->isKeyDown(getKeySetting("keymap_right")),
1212                                 input->isKeyDown(getKeySetting("keymap_jump")),
1213                                 input->isKeyDown(getKeySetting("keymap_special1")),
1214                                 input->isKeyDown(getKeySetting("keymap_sneak")),
1215                                 camera_pitch,
1216                                 camera_yaw
1217                         );
1218                         client.setPlayerControl(control);
1219                 }
1220                 
1221                 /*
1222                         Run server
1223                 */
1224
1225                 if(server != NULL)
1226                 {
1227                         //TimeTaker timer("server->step(dtime)");
1228                         server->step(dtime);
1229                 }
1230
1231                 /*
1232                         Process environment
1233                 */
1234                 
1235                 {
1236                         //TimeTaker timer("client.step(dtime)");
1237                         client.step(dtime);
1238                         //client.step(dtime_avg1);
1239                 }
1240
1241                 // Read client events
1242                 for(;;)
1243                 {
1244                         ClientEvent event = client.getClientEvent();
1245                         if(event.type == CE_NONE)
1246                         {
1247                                 break;
1248                         }
1249                         else if(event.type == CE_PLAYER_DAMAGE)
1250                         {
1251                                 //u16 damage = event.player_damage.amount;
1252                                 //dstream<<"Player damage: "<<damage<<std::endl;
1253                                 damage_flash_timer = 0.05;
1254                         }
1255                         else if(event.type == CE_PLAYER_FORCE_MOVE)
1256                         {
1257                                 camera_yaw = event.player_force_move.yaw;
1258                                 camera_pitch = event.player_force_move.pitch;
1259                         }
1260                 }
1261                 
1262                 // Get player position
1263                 v3f player_position = client.getPlayerPosition();
1264
1265                 //TimeTaker //timer2("//timer2");
1266
1267                 /*
1268                         Mouse and camera control
1269                 */
1270                 
1271                 if((device->isWindowActive() && noMenuActive()) || random_input)
1272                 {
1273                         if(!random_input)
1274                                 device->getCursorControl()->setVisible(false);
1275
1276                         if(first_loop_after_window_activation){
1277                                 //std::cout<<"window active, first loop"<<std::endl;
1278                                 first_loop_after_window_activation = false;
1279                         }
1280                         else{
1281                                 s32 dx = input->getMousePos().X - displaycenter.X;
1282                                 s32 dy = input->getMousePos().Y - displaycenter.Y;
1283                                 //std::cout<<"window active, pos difference "<<dx<<","<<dy<<std::endl;
1284                                 
1285                                 /*const float keyspeed = 500;
1286                                 if(input->isKeyDown(irr::KEY_UP))
1287                                         dy -= dtime * keyspeed;
1288                                 if(input->isKeyDown(irr::KEY_DOWN))
1289                                         dy += dtime * keyspeed;
1290                                 if(input->isKeyDown(irr::KEY_LEFT))
1291                                         dx -= dtime * keyspeed;
1292                                 if(input->isKeyDown(irr::KEY_RIGHT))
1293                                         dx += dtime * keyspeed;*/
1294
1295                                 camera_yaw -= dx*0.2;
1296                                 camera_pitch += dy*0.2;
1297                                 if(camera_pitch < -89.5) camera_pitch = -89.5;
1298                                 if(camera_pitch > 89.5) camera_pitch = 89.5;
1299                         }
1300                         input->setMousePos(displaycenter.X, displaycenter.Y);
1301                 }
1302                 else{
1303                         device->getCursorControl()->setVisible(true);
1304
1305                         //std::cout<<"window inactive"<<std::endl;
1306                         first_loop_after_window_activation = true;
1307                 }
1308
1309                 camera_yaw = wrapDegrees(camera_yaw);
1310                 camera_pitch = wrapDegrees(camera_pitch);
1311                 
1312                 v3f camera_direction = v3f(0,0,1);
1313                 camera_direction.rotateYZBy(camera_pitch);
1314                 camera_direction.rotateXZBy(camera_yaw);
1315                 
1316                 // This is at the height of the eyes of the current figure
1317                 //v3f camera_position = player_position + v3f(0, BS+BS/2, 0);
1318                 // This is more like in minecraft
1319                 v3f camera_position = player_position + v3f(0, BS+BS*0.625, 0);
1320
1321                 camera->setPosition(camera_position);
1322                 // *100.0 helps in large map coordinates
1323                 camera->setTarget(camera_position + camera_direction * 100.0);
1324
1325                 if(FIELD_OF_VIEW_TEST){
1326                         client.updateCamera(v3f(0,0,0), v3f(0,0,1));
1327                 }
1328                 else{
1329                         //TimeTaker timer("client.updateCamera");
1330                         client.updateCamera(camera_position, camera_direction);
1331                 }
1332                 
1333                 //timer2.stop();
1334                 //TimeTaker //timer3("//timer3");
1335
1336                 /*
1337                         Calculate what block is the crosshair pointing to
1338                 */
1339                 
1340                 //u32 t1 = device->getTimer()->getRealTime();
1341                 
1342                 //f32 d = 4; // max. distance
1343                 f32 d = 4; // max. distance
1344                 core::line3d<f32> shootline(camera_position,
1345                                 camera_position + camera_direction * BS * (d+1));
1346
1347                 MapBlockObject *selected_object = client.getSelectedObject
1348                                 (d*BS, camera_position, shootline);
1349
1350                 ClientActiveObject *selected_active_object
1351                                 = client.getSelectedActiveObject
1352                                         (d*BS, camera_position, shootline);
1353
1354                 if(selected_object != NULL)
1355                 {
1356                         //dstream<<"Client returned selected_object != NULL"<<std::endl;
1357
1358                         core::aabbox3d<f32> box_on_map
1359                                         = selected_object->getSelectionBoxOnMap();
1360
1361                         hilightboxes.push_back(box_on_map);
1362
1363                         infotext = narrow_to_wide(selected_object->infoText());
1364
1365                         if(input->getLeftClicked())
1366                         {
1367                                 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1368                                 client.clickObject(0, selected_object->getBlock()->getPos(),
1369                                                 selected_object->getId(), g_selected_item);
1370                         }
1371                         else if(input->getRightClicked())
1372                         {
1373                                 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1374                                 /*
1375                                         Check if we want to modify the object ourselves
1376                                 */
1377                                 if(selected_object->getTypeId() == MAPBLOCKOBJECT_TYPE_SIGN)
1378                                 {
1379                                         dstream<<"Sign object right-clicked"<<std::endl;
1380                                         
1381                                         if(random_input == false)
1382                                         {
1383                                                 // Get a new text for it
1384
1385                                                 TextDest *dest = new TextDestSign(
1386                                                                 selected_object->getBlock()->getPos(),
1387                                                                 selected_object->getId(),
1388                                                                 &client);
1389
1390                                                 SignObject *sign_object = (SignObject*)selected_object;
1391
1392                                                 std::wstring wtext =
1393                                                                 narrow_to_wide(sign_object->getText());
1394
1395                                                 (new GUITextInputMenu(guienv, guiroot, -1,
1396                                                                 &g_menumgr, dest,
1397                                                                 wtext))->drop();
1398                                         }
1399                                 }
1400                                 /*
1401                                         Otherwise pass the event to the server as-is
1402                                 */
1403                                 else
1404                                 {
1405                                         client.clickObject(1, selected_object->getBlock()->getPos(),
1406                                                         selected_object->getId(), g_selected_item);
1407                                 }
1408                         }
1409                 }
1410                 else if(selected_active_object != NULL)
1411                 {
1412                         //dstream<<"Client returned selected_active_object != NULL"<<std::endl;
1413                         
1414                         core::aabbox3d<f32> *selection_box
1415                                         = selected_active_object->getSelectionBox();
1416                         // Box should exist because object was returned in the
1417                         // first place
1418                         assert(selection_box);
1419
1420                         v3f pos = selected_active_object->getPosition();
1421
1422                         core::aabbox3d<f32> box_on_map(
1423                                         selection_box->MinEdge + pos,
1424                                         selection_box->MaxEdge + pos
1425                         );
1426
1427                         hilightboxes.push_back(box_on_map);
1428
1429                         //infotext = narrow_to_wide("A ClientActiveObject");
1430                         infotext = narrow_to_wide(selected_active_object->infoText());
1431
1432                         if(input->getLeftClicked())
1433                         {
1434                                 std::cout<<DTIME<<"Left-clicked object"<<std::endl;
1435                                 client.clickActiveObject(0,
1436                                                 selected_active_object->getId(), g_selected_item);
1437                         }
1438                         else if(input->getRightClicked())
1439                         {
1440                                 std::cout<<DTIME<<"Right-clicked object"<<std::endl;
1441                         }
1442                 }
1443                 else // selected_object == NULL
1444                 {
1445
1446                 /*
1447                         Find out which node we are pointing at
1448                 */
1449                 
1450                 bool nodefound = false;
1451                 v3s16 nodepos;
1452                 v3s16 neighbourpos;
1453                 core::aabbox3d<f32> nodehilightbox;
1454
1455                 getPointedNode(&client, player_position,
1456                                 camera_direction, camera_position,
1457                                 nodefound, shootline,
1458                                 nodepos, neighbourpos,
1459                                 nodehilightbox, d);
1460         
1461                 static float nodig_delay_counter = 0.0;
1462
1463                 if(nodefound)
1464                 {
1465                         static v3s16 nodepos_old(-32768,-32768,-32768);
1466
1467                         static float dig_time = 0.0;
1468                         static u16 dig_index = 0;
1469                         
1470                         /*
1471                                 Visualize selection
1472                         */
1473
1474                         hilightboxes.push_back(nodehilightbox);
1475
1476                         /*
1477                                 Check information text of node
1478                         */
1479
1480                         NodeMetadata *meta = client.getNodeMetadata(nodepos);
1481                         if(meta)
1482                         {
1483                                 infotext = narrow_to_wide(meta->infoText());
1484                         }
1485                         
1486                         //MapNode node = client.getNode(nodepos);
1487
1488                         /*
1489                                 Handle digging
1490                         */
1491                         
1492                         if(input->getLeftReleased())
1493                         {
1494                                 client.clearTempMod(nodepos);
1495                                 dig_time = 0.0;
1496                         }
1497                         
1498                         if(nodig_delay_counter > 0.0)
1499                         {
1500                                 nodig_delay_counter -= dtime;
1501                         }
1502                         else
1503                         {
1504                                 if(nodepos != nodepos_old)
1505                                 {
1506                                         std::cout<<DTIME<<"Pointing at ("<<nodepos.X<<","
1507                                                         <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl;
1508
1509                                         if(nodepos_old != v3s16(-32768,-32768,-32768))
1510                                         {
1511                                                 client.clearTempMod(nodepos_old);
1512                                                 dig_time = 0.0;
1513                                         }
1514                                 }
1515
1516                                 if(input->getLeftClicked() ||
1517                                                 (input->getLeftState() && nodepos != nodepos_old))
1518                                 {
1519                                         dstream<<DTIME<<"Started digging"<<std::endl;
1520                                         client.groundAction(0, nodepos, neighbourpos, g_selected_item);
1521                                 }
1522                                 if(input->getLeftClicked())
1523                                 {
1524                                         client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, 0));
1525                                 }
1526                                 if(input->getLeftState())
1527                                 {
1528                                         MapNode n = client.getNode(nodepos);
1529                                 
1530                                         // Get tool name. Default is "" = bare hands
1531                                         std::string toolname = "";
1532                                         InventoryList *mlist = local_inventory.getList("main");
1533                                         if(mlist != NULL)
1534                                         {
1535                                                 InventoryItem *item = mlist->getItem(g_selected_item);
1536                                                 if(item && (std::string)item->getName() == "ToolItem")
1537                                                 {
1538                                                         ToolItem *titem = (ToolItem*)item;
1539                                                         toolname = titem->getToolName();
1540                                                 }
1541                                         }
1542
1543                                         // Get digging properties for material and tool
1544                                         u8 material = n.d;
1545                                         DiggingProperties prop =
1546                                                         getDiggingProperties(material, toolname);
1547                                         
1548                                         float dig_time_complete = 0.0;
1549
1550                                         if(prop.diggable == false)
1551                                         {
1552                                                 /*dstream<<"Material "<<(int)material
1553                                                                 <<" not diggable with \""
1554                                                                 <<toolname<<"\""<<std::endl;*/
1555                                                 // I guess nobody will wait for this long
1556                                                 dig_time_complete = 10000000.0;
1557                                         }
1558                                         else
1559                                         {
1560                                                 dig_time_complete = prop.time;
1561                                         }
1562                                         
1563                                         if(dig_time_complete >= 0.001)
1564                                         {
1565                                                 dig_index = (u16)((float)CRACK_ANIMATION_LENGTH
1566                                                                 * dig_time/dig_time_complete);
1567                                         }
1568                                         // This is for torches
1569                                         else
1570                                         {
1571                                                 dig_index = CRACK_ANIMATION_LENGTH;
1572                                         }
1573
1574                                         if(dig_index < CRACK_ANIMATION_LENGTH)
1575                                         {
1576                                                 //TimeTaker timer("client.setTempMod");
1577                                                 //dstream<<"dig_index="<<dig_index<<std::endl;
1578                                                 client.setTempMod(nodepos, NodeMod(NODEMOD_CRACK, dig_index));
1579                                         }
1580                                         else
1581                                         {
1582                                                 dstream<<DTIME<<"Digging completed"<<std::endl;
1583                                                 client.groundAction(3, nodepos, neighbourpos, g_selected_item);
1584                                                 client.clearTempMod(nodepos);
1585                                                 client.removeNode(nodepos);
1586
1587                                                 dig_time = 0;
1588
1589                                                 nodig_delay_counter = dig_time_complete
1590                                                                 / (float)CRACK_ANIMATION_LENGTH;
1591
1592                                                 // We don't want a corresponding delay to
1593                                                 // very time consuming nodes
1594                                                 if(nodig_delay_counter > 0.5)
1595                                                 {
1596                                                         nodig_delay_counter = 0.5;
1597                                                 }
1598                                                 // We want a slight delay to very little
1599                                                 // time consuming nodes
1600                                                 float mindelay = 0.15;
1601                                                 if(nodig_delay_counter < mindelay)
1602                                                 {
1603                                                         nodig_delay_counter = mindelay;
1604                                                 }
1605                                         }
1606
1607                                         dig_time += dtime;
1608                                 }
1609                         }
1610                         
1611                         if(input->getRightClicked())
1612                         {
1613                                 std::cout<<DTIME<<"Ground right-clicked"<<std::endl;
1614                                 
1615                                 if(meta && meta->typeId() == CONTENT_SIGN_WALL && !random_input)
1616                                 {
1617                                         dstream<<"Sign node right-clicked"<<std::endl;
1618                                         
1619                                         SignNodeMetadata *signmeta = (SignNodeMetadata*)meta;
1620                                         
1621                                         // Get a new text for it
1622
1623                                         TextDest *dest = new TextDestSignNode(nodepos, &client);
1624
1625                                         std::wstring wtext =
1626                                                         narrow_to_wide(signmeta->getText());
1627
1628                                         (new GUITextInputMenu(guienv, guiroot, -1,
1629                                                         &g_menumgr, dest,
1630                                                         wtext))->drop();
1631                                 }
1632                                 else if(meta && meta->typeId() == CONTENT_CHEST && !random_input)
1633                                 {
1634                                         dstream<<"Chest node right-clicked"<<std::endl;
1635                                         
1636                                         //ChestNodeMetadata *chestmeta = (ChestNodeMetadata*)meta;
1637
1638                                         std::string chest_inv_id;
1639                                         chest_inv_id += "nodemeta:";
1640                                         chest_inv_id += itos(nodepos.X);
1641                                         chest_inv_id += ",";
1642                                         chest_inv_id += itos(nodepos.Y);
1643                                         chest_inv_id += ",";
1644                                         chest_inv_id += itos(nodepos.Z);
1645                                         
1646                                         GUIInventoryMenu *menu =
1647                                                 new GUIInventoryMenu(guienv, guiroot, -1,
1648                                                         &g_menumgr, v2s16(8,9),
1649                                                         client.getInventoryContext(),
1650                                                         &client);
1651
1652                                         core::array<GUIInventoryMenu::DrawSpec> draw_spec;
1653                                         
1654                                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1655                                                         "list", chest_inv_id, "0",
1656                                                         v2s32(0, 0), v2s32(8, 4)));
1657                                         draw_spec.push_back(GUIInventoryMenu::DrawSpec(
1658                                                         "list", "current_player", "main",
1659                                                         v2s32(0, 5), v2s32(8, 4)));
1660
1661                                         menu->setDrawSpec(draw_spec);
1662
1663                                         menu->drop();
1664
1665                                 }
1666                                 else if(meta && meta->typeId() == CONTENT_FURNACE && !random_input)
1667                                 {
1668                                         dstream<<"Furnace node right-clicked"<<std::endl;
1669                                         
1670                                         GUIFurnaceMenu *menu =
1671                                                 new GUIFurnaceMenu(guienv, guiroot, -1,
1672                                                         &g_menumgr, nodepos, &client);
1673
1674                                         menu->drop();
1675
1676                                 }
1677                                 else
1678                                 {
1679                                         client.groundAction(1, nodepos, neighbourpos, g_selected_item);
1680                                 }
1681                         }
1682                         
1683                         nodepos_old = nodepos;
1684                 }
1685                 else{
1686                 }
1687
1688                 } // selected_object == NULL
1689                 
1690                 input->resetLeftClicked();
1691                 input->resetRightClicked();
1692                 
1693                 if(input->getLeftReleased())
1694                 {
1695                         std::cout<<DTIME<<"Left button released (stopped digging)"
1696                                         <<std::endl;
1697                         client.groundAction(2, v3s16(0,0,0), v3s16(0,0,0), 0);
1698                 }
1699                 if(input->getRightReleased())
1700                 {
1701                         //std::cout<<DTIME<<"Right released"<<std::endl;
1702                         // Nothing here
1703                 }
1704                 
1705                 input->resetLeftReleased();
1706                 input->resetRightReleased();
1707                 
1708                 /*
1709                         Calculate stuff for drawing
1710                 */
1711
1712                 camera->setAspectRatio((f32)screensize.X / (f32)screensize.Y);
1713                 
1714                 u32 daynight_ratio = client.getDayNightRatio();
1715                 u8 l = decode_light((daynight_ratio * LIGHT_SUN) / 1000);
1716                 video::SColor bgcolor = video::SColor(
1717                                 255,
1718                                 bgcolor_bright.getRed() * l / 255,
1719                                 bgcolor_bright.getGreen() * l / 255,
1720                                 bgcolor_bright.getBlue() * l / 255);
1721                                 /*skycolor.getRed() * l / 255,
1722                                 skycolor.getGreen() * l / 255,
1723                                 skycolor.getBlue() * l / 255);*/
1724
1725                 float brightness = (float)l/255.0;
1726
1727                 /*
1728                         Update skybox
1729                 */
1730                 if(fabs(brightness - old_brightness) > 0.01)
1731                         update_skybox(driver, smgr, skybox, brightness);
1732
1733                 /*
1734                         Update coulds
1735                 */
1736                 if(clouds)
1737                 {
1738                         clouds->step(dtime);
1739                         clouds->update(v2f(player_position.X, player_position.Z),
1740                                         0.05+brightness*0.95);
1741                 }
1742                 
1743                 // Store brightness value
1744                 old_brightness = brightness;
1745
1746                 /*
1747                         Fog
1748                 */
1749                 
1750                 if(g_settings.getBool("enable_fog") == true)
1751                 {
1752                         f32 range = draw_control.wanted_range*BS + MAP_BLOCKSIZE*BS*1.5;
1753                         if(draw_control.range_all)
1754                                 range = 100000*BS;
1755                         if(range < 50*BS)
1756                                 range = range * 0.5 + 25*BS;
1757
1758                         driver->setFog(
1759                                 bgcolor,
1760                                 video::EFT_FOG_LINEAR,
1761                                 range*0.4,
1762                                 range*1.0,
1763                                 0.01,
1764                                 false, // pixel fog
1765                                 false // range fog
1766                         );
1767                 }
1768                 else
1769                 {
1770                         driver->setFog(
1771                                 bgcolor,
1772                                 video::EFT_FOG_LINEAR,
1773                                 100000*BS,
1774                                 110000*BS,
1775                                 0.01,
1776                                 false, // pixel fog
1777                                 false // range fog
1778                         );
1779                 }
1780
1781
1782                 /*
1783                         Update gui stuff (0ms)
1784                 */
1785
1786                 //TimeTaker guiupdatetimer("Gui updating");
1787                 
1788                 {
1789                         static float drawtime_avg = 0;
1790                         drawtime_avg = drawtime_avg * 0.95 + (float)drawtime*0.05;
1791                         static float beginscenetime_avg = 0;
1792                         beginscenetime_avg = beginscenetime_avg * 0.95 + (float)beginscenetime*0.05;
1793                         static float scenetime_avg = 0;
1794                         scenetime_avg = scenetime_avg * 0.95 + (float)scenetime*0.05;
1795                         static float endscenetime_avg = 0;
1796                         endscenetime_avg = endscenetime_avg * 0.95 + (float)endscenetime*0.05;
1797                         
1798                         char temptext[300];
1799                         snprintf(temptext, 300, "Minetest-c55 %s ("
1800                                         "R: range_all=%i"
1801                                         ")"
1802                                         " drawtime=%.0f, beginscenetime=%.0f"
1803                                         ", scenetime=%.0f, endscenetime=%.0f",
1804                                         VERSION_STRING,
1805                                         draw_control.range_all,
1806                                         drawtime_avg,
1807                                         beginscenetime_avg,
1808                                         scenetime_avg,
1809                                         endscenetime_avg
1810                                         );
1811                         
1812                         guitext->setText(narrow_to_wide(temptext).c_str());
1813                 }
1814                 
1815                 {
1816                         char temptext[300];
1817                         snprintf(temptext, 300,
1818                                         "(% .1f, % .1f, % .1f)"
1819                                         " (% .3f < btime_jitter < % .3f"
1820                                         ", dtime_jitter = % .1f %%"
1821                                         ", v_range = %.1f)",
1822                                         player_position.X/BS,
1823                                         player_position.Y/BS,
1824                                         player_position.Z/BS,
1825                                         busytime_jitter1_min_sample,
1826                                         busytime_jitter1_max_sample,
1827                                         dtime_jitter1_max_fraction * 100.0,
1828                                         draw_control.wanted_range
1829                                         );
1830
1831                         guitext2->setText(narrow_to_wide(temptext).c_str());
1832                 }
1833                 
1834                 {
1835                         guitext_info->setText(infotext.c_str());
1836                 }
1837                 
1838                 /*
1839                         Get chat messages from client
1840                 */
1841                 {
1842                         // Get new messages
1843                         std::wstring message;
1844                         while(client.getChatMessage(message))
1845                         {
1846                                 chat_lines.push_back(ChatLine(message));
1847                                 /*if(chat_lines.size() > 6)
1848                                 {
1849                                         core::list<ChatLine>::Iterator
1850                                                         i = chat_lines.begin();
1851                                         chat_lines.erase(i);
1852                                 }*/
1853                         }
1854                         // Append them to form the whole static text and throw
1855                         // it to the gui element
1856                         std::wstring whole;
1857                         // This will correspond to the line number counted from
1858                         // top to bottom, from size-1 to 0
1859                         s16 line_number = chat_lines.size();
1860                         // Count of messages to be removed from the top
1861                         u16 to_be_removed_count = 0;
1862                         for(core::list<ChatLine>::Iterator
1863                                         i = chat_lines.begin();
1864                                         i != chat_lines.end(); i++)
1865                         {
1866                                 // After this, line number is valid for this loop
1867                                 line_number--;
1868                                 // Increment age
1869                                 (*i).age += dtime;
1870                                 /*
1871                                         This results in a maximum age of 60*6 to the
1872                                         lowermost line and a maximum of 6 lines
1873                                 */
1874                                 float allowed_age = (6-line_number) * 60.0;
1875
1876                                 if((*i).age > allowed_age)
1877                                 {
1878                                         to_be_removed_count++;
1879                                         continue;
1880                                 }
1881                                 whole += (*i).text + L'\n';
1882                         }
1883                         for(u16 i=0; i<to_be_removed_count; i++)
1884                         {
1885                                 core::list<ChatLine>::Iterator
1886                                                 it = chat_lines.begin();
1887                                 chat_lines.erase(it);
1888                         }
1889                         guitext_chat->setText(whole.c_str());
1890
1891                         // Update gui element size and position
1892
1893                         /*core::rect<s32> rect(
1894                                         10,
1895                                         screensize.Y - guitext_chat_pad_bottom
1896                                                         - text_height*chat_lines.size(),
1897                                         screensize.X - 10,
1898                                         screensize.Y - guitext_chat_pad_bottom
1899                         );*/
1900                         core::rect<s32> rect(
1901                                         10,
1902                                         50,
1903                                         screensize.X - 10,
1904                                         50 + text_height*chat_lines.size()
1905                         );
1906
1907                         guitext_chat->setRelativePosition(rect);
1908
1909                         if(chat_lines.size() == 0)
1910                                 guitext_chat->setVisible(false);
1911                         else
1912                                 guitext_chat->setVisible(true);
1913                 }
1914
1915                 /*
1916                         Inventory
1917                 */
1918                 
1919                 static u16 old_selected_item = 65535;
1920                 if(client.getLocalInventoryUpdated()
1921                                 || g_selected_item != old_selected_item)
1922                 {
1923                         old_selected_item = g_selected_item;
1924                         //std::cout<<"Updating local inventory"<<std::endl;
1925                         client.getLocalInventory(local_inventory);
1926                 }
1927                 
1928                 /*
1929                         Send actions returned by the inventory menu
1930                 */
1931                 while(inventory_action_queue.size() != 0)
1932                 {
1933                         InventoryAction *a = inventory_action_queue.pop_front();
1934
1935                         client.sendInventoryAction(a);
1936                         // Eat it
1937                         delete a;
1938                 }
1939
1940                 /*
1941                         Drawing begins
1942                 */
1943
1944                 TimeTaker drawtimer("Drawing");
1945
1946                 
1947                 {
1948                         TimeTaker timer("beginScene");
1949                         driver->beginScene(true, true, bgcolor);
1950                         //driver->beginScene(false, true, bgcolor);
1951                         beginscenetime = timer.stop(true);
1952                 }
1953
1954                 //timer3.stop();
1955                 
1956                 //std::cout<<DTIME<<"smgr->drawAll()"<<std::endl;
1957                 
1958                 {
1959                         TimeTaker timer("smgr");
1960                         smgr->drawAll();
1961                         scenetime = timer.stop(true);
1962                 }
1963                 
1964                 {
1965                 //TimeTaker timer9("auxiliary drawings");
1966                 // 0ms
1967                 
1968                 //timer9.stop();
1969                 //TimeTaker //timer10("//timer10");
1970                 
1971                 video::SMaterial m;
1972                 //m.Thickness = 10;
1973                 m.Thickness = 3;
1974                 m.Lighting = false;
1975                 driver->setMaterial(m);
1976
1977                 driver->setTransform(video::ETS_WORLD, core::IdentityMatrix);
1978
1979                 for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin();
1980                                 i != hilightboxes.end(); i++)
1981                 {
1982                         /*std::cout<<"hilightbox min="
1983                                         <<"("<<i->MinEdge.X<<","<<i->MinEdge.Y<<","<<i->MinEdge.Z<<")"
1984                                         <<" max="
1985                                         <<"("<<i->MaxEdge.X<<","<<i->MaxEdge.Y<<","<<i->MaxEdge.Z<<")"
1986                                         <<std::endl;*/
1987                         driver->draw3DBox(*i, video::SColor(255,0,0,0));
1988                 }
1989
1990                 /*
1991                         Frametime log
1992                 */
1993                 if(g_settings.getBool("frametime_graph") == true)
1994                 {
1995                         s32 x = 10;
1996                         for(core::list<float>::Iterator
1997                                         i = frametime_log.begin();
1998                                         i != frametime_log.end();
1999                                         i++)
2000                         {
2001                                 driver->draw2DLine(v2s32(x,50),
2002                                                 v2s32(x,50+(*i)*1000),
2003                                                 video::SColor(255,255,255,255));
2004                                 x++;
2005                         }
2006                 }
2007
2008                 /*
2009                         Draw crosshair
2010                 */
2011                 driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0),
2012                                 displaycenter + core::vector2d<s32>(10,0),
2013                                 video::SColor(255,255,255,255));
2014                 driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10),
2015                                 displaycenter + core::vector2d<s32>(0,10),
2016                                 video::SColor(255,255,255,255));
2017
2018                 } // timer
2019
2020                 //timer10.stop();
2021                 //TimeTaker //timer11("//timer11");
2022
2023                 /*
2024                         Draw gui
2025                 */
2026                 // 0-1ms
2027                 guienv->drawAll();
2028
2029                 /*
2030                         Draw hotbar
2031                 */
2032                 {
2033                         draw_hotbar(driver, font, v2s32(displaycenter.X, screensize.Y),
2034                                         hotbar_imagesize, hotbar_itemcount, &local_inventory,
2035                                         client.getHP());
2036                 }
2037
2038                 /*
2039                         Damage flash
2040                 */
2041                 if(damage_flash_timer > 0.0)
2042                 {
2043                         damage_flash_timer -= dtime;
2044                         
2045                         video::SColor color(128,255,0,0);
2046                         driver->draw2DRectangle(color,
2047                                         core::rect<s32>(0,0,screensize.X,screensize.Y),
2048                                         NULL);
2049                 }
2050                 
2051                 /*
2052                         End scene
2053                 */
2054                 {
2055                         TimeTaker timer("endScene");
2056                         endSceneX(driver);
2057                         endscenetime = timer.stop(true);
2058                 }
2059
2060                 drawtime = drawtimer.stop(true);
2061
2062                 /*
2063                         End of drawing
2064                 */
2065
2066                 static s16 lastFPS = 0;
2067                 //u16 fps = driver->getFPS();
2068                 u16 fps = (1.0/dtime_avg1);
2069
2070                 if (lastFPS != fps)
2071                 {
2072                         core::stringw str = L"Minetest [";
2073                         str += driver->getName();
2074                         str += "] FPS=";
2075                         str += fps;
2076
2077                         device->setWindowCaption(str.c_str());
2078                         lastFPS = fps;
2079                 }
2080         }
2081         
2082         /*
2083                 Draw a "shutting down" screen, which will be shown while the map
2084                 generator and other stuff quits
2085         */
2086         {
2087                 const wchar_t *shuttingdowntext = L"Shutting down stuff...";
2088                 gui::IGUIStaticText *gui_shuttingdowntext = guienv->addStaticText(
2089                                 shuttingdowntext, textrect, false, false);
2090                 gui_shuttingdowntext->setTextAlignment(gui::EGUIA_CENTER,
2091                                 gui::EGUIA_UPPERLEFT);
2092                 driver->beginScene(true, true, video::SColor(255,0,0,0));
2093                 guienv->drawAll();
2094                 driver->endScene();
2095                 gui_shuttingdowntext->remove();
2096         }
2097 }
2098
2099