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