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