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