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