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