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