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