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