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