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