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