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