]> git.lizzy.rs Git - minetest.git/blob - src/clientmap.cpp
Fix crash when a error occurs in a globalstep callback
[minetest.git] / src / clientmap.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser 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 "clientmap.h"
21 #include "client.h"
22 #include "mapblock_mesh.h"
23 #include <IMaterialRenderer.h>
24 #include <matrix4.h>
25 #include "log.h"
26 #include "mapsector.h"
27 #include "main.h" // dout_client, g_settings
28 #include "nodedef.h"
29 #include "mapblock.h"
30 #include "profiler.h"
31 #include "settings.h"
32 #include "util/mathconstants.h"
33 #include <algorithm>
34
35 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
36
37 ClientMap::ClientMap(
38                 Client *client,
39                 IGameDef *gamedef,
40                 MapDrawControl &control,
41                 scene::ISceneNode* parent,
42                 scene::ISceneManager* mgr,
43                 s32 id
44 ):
45         Map(dout_client, gamedef),
46         scene::ISceneNode(parent, mgr, id),
47         m_client(client),
48         m_control(control),
49         m_camera_position(0,0,0),
50         m_camera_direction(0,0,1),
51         m_camera_fov(M_PI)
52 {
53         m_box = core::aabbox3d<f32>(-BS*1000000,-BS*1000000,-BS*1000000,
54                         BS*1000000,BS*1000000,BS*1000000);
55 }
56
57 ClientMap::~ClientMap()
58 {
59         /*JMutexAutoLock lock(mesh_mutex);
60         
61         if(mesh != NULL)
62         {
63                 mesh->drop();
64                 mesh = NULL;
65         }*/
66 }
67
68 MapSector * ClientMap::emergeSector(v2s16 p2d)
69 {
70         DSTACK(__FUNCTION_NAME);
71         // Check that it doesn't exist already
72         try{
73                 return getSectorNoGenerate(p2d);
74         }
75         catch(InvalidPositionException &e)
76         {
77         }
78         
79         // Create a sector
80         ClientMapSector *sector = new ClientMapSector(this, p2d, m_gamedef);
81         
82         {
83                 //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
84                 m_sectors[p2d] = sector;
85         }
86         
87         return sector;
88 }
89
90 #if 0
91 void ClientMap::deSerializeSector(v2s16 p2d, std::istream &is)
92 {
93         DSTACK(__FUNCTION_NAME);
94         ClientMapSector *sector = NULL;
95
96         //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
97         
98         core::map<v2s16, MapSector*>::Node *n = m_sectors.find(p2d);
99
100         if(n != NULL)
101         {
102                 sector = (ClientMapSector*)n->getValue();
103                 assert(sector->getId() == MAPSECTOR_CLIENT);
104         }
105         else
106         {
107                 sector = new ClientMapSector(this, p2d);
108                 {
109                         //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
110                         m_sectors.insert(p2d, sector);
111                 }
112         }
113
114         sector->deSerialize(is);
115 }
116 #endif
117
118 void ClientMap::OnRegisterSceneNode()
119 {
120         if(IsVisible)
121         {
122                 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
123                 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
124         }
125
126         ISceneNode::OnRegisterSceneNode();
127 }
128
129 static bool isOccluded(Map *map, v3s16 p0, v3s16 p1, float step, float stepfac,
130                 float start_off, float end_off, u32 needed_count, INodeDefManager *nodemgr)
131 {
132         float d0 = (float)BS * p0.getDistanceFrom(p1);
133         v3s16 u0 = p1 - p0;
134         v3f uf = v3f(u0.X, u0.Y, u0.Z) * BS;
135         uf.normalize();
136         v3f p0f = v3f(p0.X, p0.Y, p0.Z) * BS;
137         u32 count = 0;
138         for(float s=start_off; s<d0+end_off; s+=step){
139                 v3f pf = p0f + uf * s;
140                 v3s16 p = floatToInt(pf, BS);
141                 MapNode n = map->getNodeNoEx(p);
142                 bool is_transparent = false;
143                 const ContentFeatures &f = nodemgr->get(n);
144                 if(f.solidness == 0)
145                         is_transparent = (f.visual_solidness != 2);
146                 else
147                         is_transparent = (f.solidness != 2);
148                 if(!is_transparent){
149                         count++;
150                         if(count >= needed_count)
151                                 return true;
152                 }
153                 step *= stepfac;
154         }
155         return false;
156 }
157
158 void ClientMap::updateDrawList(video::IVideoDriver* driver)
159 {
160         ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
161         g_profiler->add("CM::updateDrawList() count", 1);
162
163         INodeDefManager *nodemgr = m_gamedef->ndef();
164
165         for(std::map<v3s16, MapBlock*>::iterator
166                         i = m_drawlist.begin();
167                         i != m_drawlist.end(); ++i)
168         {
169                 MapBlock *block = i->second;
170                 block->refDrop();
171         }
172         m_drawlist.clear();
173
174         m_camera_mutex.Lock();
175         v3f camera_position = m_camera_position;
176         v3f camera_direction = m_camera_direction;
177         f32 camera_fov = m_camera_fov;
178         m_camera_mutex.Unlock();
179
180         // Use a higher fov to accomodate faster camera movements.
181         // Blocks are cropped better when they are drawn.
182         // Or maybe they aren't? Well whatever.
183         camera_fov *= 1.2;
184
185         v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
186         v3s16 box_nodes_d = m_control.wanted_range * v3s16(1,1,1);
187         v3s16 p_nodes_min = cam_pos_nodes - box_nodes_d;
188         v3s16 p_nodes_max = cam_pos_nodes + box_nodes_d;
189         // Take a fair amount as we will be dropping more out later
190         // Umm... these additions are a bit strange but they are needed.
191         v3s16 p_blocks_min(
192                         p_nodes_min.X / MAP_BLOCKSIZE - 3,
193                         p_nodes_min.Y / MAP_BLOCKSIZE - 3,
194                         p_nodes_min.Z / MAP_BLOCKSIZE - 3);
195         v3s16 p_blocks_max(
196                         p_nodes_max.X / MAP_BLOCKSIZE + 1,
197                         p_nodes_max.Y / MAP_BLOCKSIZE + 1,
198                         p_nodes_max.Z / MAP_BLOCKSIZE + 1);
199         
200         // Number of blocks in rendering range
201         u32 blocks_in_range = 0;
202         // Number of blocks occlusion culled
203         u32 blocks_occlusion_culled = 0;
204         // Number of blocks in rendering range but don't have a mesh
205         u32 blocks_in_range_without_mesh = 0;
206         // Blocks that had mesh that would have been drawn according to
207         // rendering range (if max blocks limit didn't kick in)
208         u32 blocks_would_have_drawn = 0;
209         // Blocks that were drawn and had a mesh
210         u32 blocks_drawn = 0;
211         // Blocks which had a corresponding meshbuffer for this pass
212         //u32 blocks_had_pass_meshbuf = 0;
213         // Blocks from which stuff was actually drawn
214         //u32 blocks_without_stuff = 0;
215         // Distance to farthest drawn block
216         float farthest_drawn = 0;
217
218         for(std::map<v2s16, MapSector*>::iterator
219                         si = m_sectors.begin();
220                         si != m_sectors.end(); ++si)
221         {
222                 MapSector *sector = si->second;
223                 v2s16 sp = sector->getPos();
224                 
225                 if(m_control.range_all == false)
226                 {
227                         if(sp.X < p_blocks_min.X
228                         || sp.X > p_blocks_max.X
229                         || sp.Y < p_blocks_min.Z
230                         || sp.Y > p_blocks_max.Z)
231                                 continue;
232                 }
233
234                 std::list< MapBlock * > sectorblocks;
235                 sector->getBlocks(sectorblocks);
236                 
237                 /*
238                         Loop through blocks in sector
239                 */
240
241                 u32 sector_blocks_drawn = 0;
242                 
243                 std::list< MapBlock * >::iterator i;
244                 for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++)
245                 {
246                         MapBlock *block = *i;
247
248                         /*
249                                 Compare block position to camera position, skip
250                                 if not seen on display
251                         */
252                         
253                         float range = 100000 * BS;
254                         if(m_control.range_all == false)
255                                 range = m_control.wanted_range * BS;
256
257                         float d = 0.0;
258                         if(isBlockInSight(block->getPos(), camera_position,
259                                         camera_direction, camera_fov,
260                                         range, &d) == false)
261                         {
262                                 continue;
263                         }
264
265                         // This is ugly (spherical distance limit?)
266                         /*if(m_control.range_all == false &&
267                                         d - 0.5*BS*MAP_BLOCKSIZE > range)
268                                 continue;*/
269
270                         blocks_in_range++;
271                         
272                         /*
273                                 Ignore if mesh doesn't exist
274                         */
275                         {
276                                 //JMutexAutoLock lock(block->mesh_mutex);
277
278                                 if(block->mesh == NULL){
279                                         blocks_in_range_without_mesh++;
280                                         continue;
281                                 }
282                         }
283
284                         /*
285                                 Occlusion culling
286                         */
287
288                         // No occlusion culling when free_move is on and camera is
289                         // inside ground
290                         bool occlusion_culling_enabled = true;
291                         if(g_settings->getBool("free_move")){
292                                 MapNode n = getNodeNoEx(cam_pos_nodes);
293                                 if(n.getContent() == CONTENT_IGNORE ||
294                                                 nodemgr->get(n).solidness == 2)
295                                         occlusion_culling_enabled = false;
296                         }
297
298                         v3s16 cpn = block->getPos() * MAP_BLOCKSIZE;
299                         cpn += v3s16(MAP_BLOCKSIZE/2, MAP_BLOCKSIZE/2, MAP_BLOCKSIZE/2);
300                         float step = BS*1;
301                         float stepfac = 1.1;
302                         float startoff = BS*1;
303                         float endoff = -BS*MAP_BLOCKSIZE*1.42*1.42;
304                         v3s16 spn = cam_pos_nodes + v3s16(0,0,0);
305                         s16 bs2 = MAP_BLOCKSIZE/2 + 1;
306                         u32 needed_count = 1;
307                         if(
308                                 occlusion_culling_enabled &&
309                                 isOccluded(this, spn, cpn + v3s16(0,0,0),
310                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
311                                 isOccluded(this, spn, cpn + v3s16(bs2,bs2,bs2),
312                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
313                                 isOccluded(this, spn, cpn + v3s16(bs2,bs2,-bs2),
314                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
315                                 isOccluded(this, spn, cpn + v3s16(bs2,-bs2,bs2),
316                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
317                                 isOccluded(this, spn, cpn + v3s16(bs2,-bs2,-bs2),
318                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
319                                 isOccluded(this, spn, cpn + v3s16(-bs2,bs2,bs2),
320                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
321                                 isOccluded(this, spn, cpn + v3s16(-bs2,bs2,-bs2),
322                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
323                                 isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,bs2),
324                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
325                                 isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,-bs2),
326                                         step, stepfac, startoff, endoff, needed_count, nodemgr)
327                         )
328                         {
329                                 blocks_occlusion_culled++;
330                                 continue;
331                         }
332                         
333                         // This block is in range. Reset usage timer.
334                         block->resetUsageTimer();
335
336                         // Limit block count in case of a sudden increase
337                         blocks_would_have_drawn++;
338                         if(blocks_drawn >= m_control.wanted_max_blocks
339                                         && m_control.range_all == false
340                                         && d > m_control.wanted_min_range * BS)
341                                 continue;
342
343                         // Add to set
344                         block->refGrab();
345                         m_drawlist[block->getPos()] = block;
346
347                         sector_blocks_drawn++;
348                         blocks_drawn++;
349                         if(d/BS > farthest_drawn)
350                                 farthest_drawn = d/BS;
351
352                 } // foreach sectorblocks
353
354                 if(sector_blocks_drawn != 0)
355                         m_last_drawn_sectors.insert(sp);
356         }
357
358         m_control.blocks_would_have_drawn = blocks_would_have_drawn;
359         m_control.blocks_drawn = blocks_drawn;
360         m_control.farthest_drawn = farthest_drawn;
361
362         g_profiler->avg("CM: blocks in range", blocks_in_range);
363         g_profiler->avg("CM: blocks occlusion culled", blocks_occlusion_culled);
364         if(blocks_in_range != 0)
365                 g_profiler->avg("CM: blocks in range without mesh (frac)",
366                                 (float)blocks_in_range_without_mesh/blocks_in_range);
367         g_profiler->avg("CM: blocks drawn", blocks_drawn);
368         g_profiler->avg("CM: farthest drawn", farthest_drawn);
369         g_profiler->avg("CM: wanted max blocks", m_control.wanted_max_blocks);
370 }
371
372 struct MeshBufList
373 {
374         video::SMaterial m;
375         std::list<scene::IMeshBuffer*> bufs;
376 };
377
378 struct MeshBufListList
379 {
380         std::list<MeshBufList> lists;
381         
382         void clear()
383         {
384                 lists.clear();
385         }
386         
387         void add(scene::IMeshBuffer *buf)
388         {
389                 for(std::list<MeshBufList>::iterator i = lists.begin();
390                                 i != lists.end(); ++i){
391                         MeshBufList &l = *i;
392                         if(l.m == buf->getMaterial()){
393                                 l.bufs.push_back(buf);
394                                 return;
395                         }
396                 }
397                 MeshBufList l;
398                 l.m = buf->getMaterial();
399                 l.bufs.push_back(buf);
400                 lists.push_back(l);
401         }
402 };
403
404 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
405 {
406         DSTACK(__FUNCTION_NAME);
407
408         bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
409         
410         std::string prefix;
411         if(pass == scene::ESNRP_SOLID)
412                 prefix = "CM: solid: ";
413         else
414                 prefix = "CM: transparent: ";
415
416         /*
417                 This is called two times per frame, reset on the non-transparent one
418         */
419         if(pass == scene::ESNRP_SOLID)
420         {
421                 m_last_drawn_sectors.clear();
422         }
423
424         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
425         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
426         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
427
428         /*
429                 Get time for measuring timeout.
430                 
431                 Measuring time is very useful for long delays when the
432                 machine is swapping a lot.
433         */
434         int time1 = time(0);
435
436         /*
437                 Get animation parameters
438         */
439         float animation_time = m_client->getAnimationTime();
440         int crack = m_client->getCrackLevel();
441         u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
442
443         m_camera_mutex.Lock();
444         v3f camera_position = m_camera_position;
445         v3f camera_direction = m_camera_direction;
446         f32 camera_fov = m_camera_fov;
447         m_camera_mutex.Unlock();
448
449         /*
450                 Get all blocks and draw all visible ones
451         */
452
453         v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
454         
455         v3s16 box_nodes_d = m_control.wanted_range * v3s16(1,1,1);
456
457         v3s16 p_nodes_min = cam_pos_nodes - box_nodes_d;
458         v3s16 p_nodes_max = cam_pos_nodes + box_nodes_d;
459
460         // Take a fair amount as we will be dropping more out later
461         // Umm... these additions are a bit strange but they are needed.
462         v3s16 p_blocks_min(
463                         p_nodes_min.X / MAP_BLOCKSIZE - 3,
464                         p_nodes_min.Y / MAP_BLOCKSIZE - 3,
465                         p_nodes_min.Z / MAP_BLOCKSIZE - 3);
466         v3s16 p_blocks_max(
467                         p_nodes_max.X / MAP_BLOCKSIZE + 1,
468                         p_nodes_max.Y / MAP_BLOCKSIZE + 1,
469                         p_nodes_max.Z / MAP_BLOCKSIZE + 1);
470         
471         u32 vertex_count = 0;
472         u32 meshbuffer_count = 0;
473         
474         // For limiting number of mesh animations per frame
475         u32 mesh_animate_count = 0;
476         u32 mesh_animate_count_far = 0;
477         
478         // Blocks that were drawn and had a mesh
479         u32 blocks_drawn = 0;
480         // Blocks which had a corresponding meshbuffer for this pass
481         u32 blocks_had_pass_meshbuf = 0;
482         // Blocks from which stuff was actually drawn
483         u32 blocks_without_stuff = 0;
484
485         /*
486                 Draw the selected MapBlocks
487         */
488
489         {
490         ScopeProfiler sp(g_profiler, prefix+"drawing blocks", SPT_AVG);
491
492         MeshBufListList drawbufs;
493
494         for(std::map<v3s16, MapBlock*>::iterator
495                         i = m_drawlist.begin();
496                         i != m_drawlist.end(); ++i)
497         {
498                 MapBlock *block = i->second;
499
500                 // If the mesh of the block happened to get deleted, ignore it
501                 if(block->mesh == NULL)
502                         continue;
503                 
504                 float d = 0.0;
505                 if(isBlockInSight(block->getPos(), camera_position,
506                                 camera_direction, camera_fov,
507                                 100000*BS, &d) == false)
508                 {
509                         continue;
510                 }
511
512                 // Mesh animation
513                 {
514                         //JMutexAutoLock lock(block->mesh_mutex);
515                         MapBlockMesh *mapBlockMesh = block->mesh;
516                         assert(mapBlockMesh);
517                         // Pretty random but this should work somewhat nicely
518                         bool faraway = d >= BS*50;
519                         //bool faraway = d >= m_control.wanted_range * BS;
520                         if(mapBlockMesh->isAnimationForced() ||
521                                         !faraway ||
522                                         mesh_animate_count_far < (m_control.range_all ? 200 : 50))
523                         {
524                                 bool animated = mapBlockMesh->animate(
525                                                 faraway,
526                                                 animation_time,
527                                                 crack,
528                                                 daynight_ratio);
529                                 if(animated)
530                                         mesh_animate_count++;
531                                 if(animated && faraway)
532                                         mesh_animate_count_far++;
533                         }
534                         else
535                         {
536                                 mapBlockMesh->decreaseAnimationForceTimer();
537                         }
538                 }
539
540                 /*
541                         Get the meshbuffers of the block
542                 */
543                 {
544                         //JMutexAutoLock lock(block->mesh_mutex);
545
546                         MapBlockMesh *mapBlockMesh = block->mesh;
547                         assert(mapBlockMesh);
548
549                         scene::SMesh *mesh = mapBlockMesh->getMesh();
550                         assert(mesh);
551
552                         u32 c = mesh->getMeshBufferCount();
553                         for(u32 i=0; i<c; i++)
554                         {
555                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
556
557                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
558                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
559                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
560
561                                 const video::SMaterial& material = buf->getMaterial();
562                                 video::IMaterialRenderer* rnd =
563                                                 driver->getMaterialRenderer(material.MaterialType);
564                                 bool transparent = (rnd && rnd->isTransparent());
565                                 if(transparent == is_transparent_pass)
566                                 {
567                                         if(buf->getVertexCount() == 0)
568                                                 errorstream<<"Block ["<<analyze_block(block)
569                                                                 <<"] contains an empty meshbuf"<<std::endl;
570                                         drawbufs.add(buf);
571                                 }
572                         }
573                 }
574         }
575         
576         std::list<MeshBufList> &lists = drawbufs.lists;
577         
578         int timecheck_counter = 0;
579         for(std::list<MeshBufList>::iterator i = lists.begin();
580                         i != lists.end(); ++i)
581         {
582                 {
583                         timecheck_counter++;
584                         if(timecheck_counter > 50)
585                         {
586                                 timecheck_counter = 0;
587                                 int time2 = time(0);
588                                 if(time2 > time1 + 4)
589                                 {
590                                         infostream<<"ClientMap::renderMap(): "
591                                                 "Rendering takes ages, returning."
592                                                 <<std::endl;
593                                         return;
594                                 }
595                         }
596                 }
597
598                 MeshBufList &list = *i;
599                 
600                 driver->setMaterial(list.m);
601                 
602                 for(std::list<scene::IMeshBuffer*>::iterator j = list.bufs.begin();
603                                 j != list.bufs.end(); ++j)
604                 {
605                         scene::IMeshBuffer *buf = *j;
606                         driver->drawMeshBuffer(buf);
607                         vertex_count += buf->getVertexCount();
608                         meshbuffer_count++;
609                 }
610 #if 0
611                 /*
612                         Draw the faces of the block
613                 */
614                 {
615                         //JMutexAutoLock lock(block->mesh_mutex);
616
617                         MapBlockMesh *mapBlockMesh = block->mesh;
618                         assert(mapBlockMesh);
619
620                         scene::SMesh *mesh = mapBlockMesh->getMesh();
621                         assert(mesh);
622
623                         u32 c = mesh->getMeshBufferCount();
624                         bool stuff_actually_drawn = false;
625                         for(u32 i=0; i<c; i++)
626                         {
627                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
628                                 const video::SMaterial& material = buf->getMaterial();
629                                 video::IMaterialRenderer* rnd =
630                                                 driver->getMaterialRenderer(material.MaterialType);
631                                 bool transparent = (rnd && rnd->isTransparent());
632                                 // Render transparent on transparent pass and likewise.
633                                 if(transparent == is_transparent_pass)
634                                 {
635                                         if(buf->getVertexCount() == 0)
636                                                 errorstream<<"Block ["<<analyze_block(block)
637                                                                 <<"] contains an empty meshbuf"<<std::endl;
638                                         /*
639                                                 This *shouldn't* hurt too much because Irrlicht
640                                                 doesn't change opengl textures if the old
641                                                 material has the same texture.
642                                         */
643                                         driver->setMaterial(buf->getMaterial());
644                                         driver->drawMeshBuffer(buf);
645                                         vertex_count += buf->getVertexCount();
646                                         meshbuffer_count++;
647                                         stuff_actually_drawn = true;
648                                 }
649                         }
650                         if(stuff_actually_drawn)
651                                 blocks_had_pass_meshbuf++;
652                         else
653                                 blocks_without_stuff++;
654                 }
655 #endif
656         }
657         } // ScopeProfiler
658         
659         // Log only on solid pass because values are the same
660         if(pass == scene::ESNRP_SOLID){
661                 g_profiler->avg("CM: animated meshes", mesh_animate_count);
662                 g_profiler->avg("CM: animated meshes (far)", mesh_animate_count_far);
663         }
664         
665         g_profiler->avg(prefix+"vertices drawn", vertex_count);
666         if(blocks_had_pass_meshbuf != 0)
667                 g_profiler->avg(prefix+"meshbuffers per block",
668                                 (float)meshbuffer_count / (float)blocks_had_pass_meshbuf);
669         if(blocks_drawn != 0)
670                 g_profiler->avg(prefix+"empty blocks (frac)",
671                                 (float)blocks_without_stuff / blocks_drawn);
672
673         /*infostream<<"renderMap(): is_transparent_pass="<<is_transparent_pass
674                         <<", rendered "<<vertex_count<<" vertices."<<std::endl;*/
675 }
676
677 static bool getVisibleBrightness(Map *map, v3f p0, v3f dir, float step,
678                 float step_multiplier, float start_distance, float end_distance,
679                 INodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
680                 int *result, bool *sunlight_seen)
681 {
682         int brightness_sum = 0;
683         int brightness_count = 0;
684         float distance = start_distance;
685         dir.normalize();
686         v3f pf = p0;
687         pf += dir * distance;
688         int noncount = 0;
689         bool nonlight_seen = false;
690         bool allow_allowing_non_sunlight_propagates = false;
691         bool allow_non_sunlight_propagates = false;
692         // Check content nearly at camera position
693         {
694                 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
695                 MapNode n = map->getNodeNoEx(p);
696                 if(ndef->get(n).param_type == CPT_LIGHT &&
697                                 !ndef->get(n).sunlight_propagates)
698                         allow_allowing_non_sunlight_propagates = true;
699         }
700         // If would start at CONTENT_IGNORE, start closer
701         {
702                 v3s16 p = floatToInt(pf, BS);
703                 MapNode n = map->getNodeNoEx(p);
704                 if(n.getContent() == CONTENT_IGNORE){
705                         float newd = 2*BS;
706                         pf = p0 + dir * 2*newd;
707                         distance = newd;
708                         sunlight_min_d = 0;
709                 }
710         }
711         for(int i=0; distance < end_distance; i++){
712                 pf += dir * step;
713                 distance += step;
714                 step *= step_multiplier;
715                 
716                 v3s16 p = floatToInt(pf, BS);
717                 MapNode n = map->getNodeNoEx(p);
718                 if(allow_allowing_non_sunlight_propagates && i == 0 &&
719                                 ndef->get(n).param_type == CPT_LIGHT &&
720                                 !ndef->get(n).sunlight_propagates){
721                         allow_non_sunlight_propagates = true;
722                 }
723                 if(ndef->get(n).param_type != CPT_LIGHT ||
724                                 (!ndef->get(n).sunlight_propagates &&
725                                         !allow_non_sunlight_propagates)){
726                         nonlight_seen = true;
727                         noncount++;
728                         if(noncount >= 4)
729                                 break;
730                         continue;
731                 }
732                 if(distance >= sunlight_min_d && *sunlight_seen == false
733                                 && nonlight_seen == false)
734                         if(n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
735                                 *sunlight_seen = true;
736                 noncount = 0;
737                 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
738                 brightness_count++;
739         }
740         *result = 0;
741         if(brightness_count == 0)
742                 return false;
743         *result = brightness_sum / brightness_count;
744         /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
745                         <<(*result)<<std::endl;*/
746         return true;
747 }
748
749 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
750                 int oldvalue, bool *sunlight_seen_result)
751 {
752         const bool debugprint = false;
753         INodeDefManager *ndef = m_gamedef->ndef();
754         static v3f z_directions[50] = {
755                 v3f(-100, 0, 0)
756         };
757         static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
758                 -1000,
759         };
760         if(z_directions[0].X < -99){
761                 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
762                         z_directions[i] = v3f(
763                                 0.01 * myrand_range(-100, 100),
764                                 1.0,
765                                 0.01 * myrand_range(-100, 100)
766                         );
767                         z_offsets[i] = 0.01 * myrand_range(0,100);
768                 }
769         }
770         if(debugprint)
771                 std::cerr<<"In goes "<<PP(m_camera_direction)<<", out comes ";
772         int sunlight_seen_count = 0;
773         float sunlight_min_d = max_d*0.8;
774         if(sunlight_min_d > 35*BS)
775                 sunlight_min_d = 35*BS;
776         std::vector<int> values;
777         for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
778                 v3f z_dir = z_directions[i];
779                 z_dir.normalize();
780                 core::CMatrix4<f32> a;
781                 a.buildRotateFromTo(v3f(0,1,0), z_dir);
782                 v3f dir = m_camera_direction;
783                 a.rotateVect(dir);
784                 int br = 0;
785                 float step = BS*1.5;
786                 if(max_d > 35*BS)
787                         step = max_d / 35 * 1.5;
788                 float off = step * z_offsets[i];
789                 bool sunlight_seen_now = false;
790                 bool ok = getVisibleBrightness(this, m_camera_position, dir,
791                                 step, 1.0, max_d*0.6+off, max_d, ndef, daylight_factor,
792                                 sunlight_min_d,
793                                 &br, &sunlight_seen_now);
794                 if(sunlight_seen_now)
795                         sunlight_seen_count++;
796                 if(!ok)
797                         continue;
798                 values.push_back(br);
799                 // Don't try too much if being in the sun is clear
800                 if(sunlight_seen_count >= 20)
801                         break;
802         }
803         int brightness_sum = 0;
804         int brightness_count = 0;
805         std::sort(values.begin(), values.end());
806         u32 num_values_to_use = values.size();
807         if(num_values_to_use >= 10)
808                 num_values_to_use -= num_values_to_use/2;
809         else if(num_values_to_use >= 7)
810                 num_values_to_use -= num_values_to_use/3;
811         u32 first_value_i = (values.size() - num_values_to_use) / 2;
812         if(debugprint){
813                 for(u32 i=0; i < first_value_i; i++)
814                         std::cerr<<values[i]<<" ";
815                 std::cerr<<"[";
816         }
817         for(u32 i=first_value_i; i < first_value_i+num_values_to_use; i++){
818                 if(debugprint)
819                         std::cerr<<values[i]<<" ";
820                 brightness_sum += values[i];
821                 brightness_count++;
822         }
823         if(debugprint){
824                 std::cerr<<"]";
825                 for(u32 i=first_value_i+num_values_to_use; i < values.size(); i++)
826                         std::cerr<<values[i]<<" ";
827         }
828         int ret = 0;
829         if(brightness_count == 0){
830                 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
831                 if(ndef->get(n).param_type == CPT_LIGHT){
832                         ret = decode_light(n.getLightBlend(daylight_factor, ndef));
833                 } else {
834                         ret = oldvalue;
835                         //ret = blend_light(255, 0, daylight_factor);
836                 }
837         } else {
838                 /*float pre = (float)brightness_sum / (float)brightness_count;
839                 float tmp = pre;
840                 const float d = 0.2;
841                 pre *= 1.0 + d*2;
842                 pre -= tmp * d;
843                 int preint = pre;
844                 ret = MYMAX(0, MYMIN(255, preint));*/
845                 ret = brightness_sum / brightness_count;
846         }
847         if(debugprint)
848                 std::cerr<<"Result: "<<ret<<" sunlight_seen_count="
849                                 <<sunlight_seen_count<<std::endl;
850         *sunlight_seen_result = (sunlight_seen_count > 0);
851         return ret;
852 }
853
854 void ClientMap::renderPostFx()
855 {
856         INodeDefManager *nodemgr = m_gamedef->ndef();
857
858         // Sadly ISceneManager has no "post effects" render pass, in that case we
859         // could just register for that and handle it in renderMap().
860
861         m_camera_mutex.Lock();
862         v3f camera_position = m_camera_position;
863         m_camera_mutex.Unlock();
864
865         MapNode n = getNodeNoEx(floatToInt(camera_position, BS));
866
867         // - If the player is in a solid node, make everything black.
868         // - If the player is in liquid, draw a semi-transparent overlay.
869         const ContentFeatures& features = nodemgr->get(n);
870         video::SColor post_effect_color = features.post_effect_color;
871         if(features.solidness == 2 && !(g_settings->getBool("noclip") && m_gamedef->checkLocalPrivilege("noclip")))
872         {
873                 post_effect_color = video::SColor(255, 0, 0, 0);
874         }
875         if (post_effect_color.getAlpha() != 0)
876         {
877                 // Draw a full-screen rectangle
878                 video::IVideoDriver* driver = SceneManager->getVideoDriver();
879                 v2u32 ss = driver->getScreenSize();
880                 core::rect<s32> rect(0,0, ss.X, ss.Y);
881                 driver->draw2DRectangle(post_effect_color, rect);
882         }
883 }
884
885 void ClientMap::PrintInfo(std::ostream &out)
886 {
887         out<<"ClientMap: ";
888 }
889
890