]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/clientmap.cpp
Keep mapblocks in memory if they're in range (#10714)
[dragonfireclient.git] / src / client / 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 "mapsector.h"
26 #include "mapblock.h"
27 #include "profiler.h"
28 #include "settings.h"
29 #include "camera.h"               // CameraModes
30 #include "util/basic_macros.h"
31 #include <algorithm>
32 #include "client/renderingengine.h"
33
34 // struct MeshBufListList
35 void MeshBufListList::clear()
36 {
37         for (auto &list : lists)
38                 list.clear();
39 }
40
41 void MeshBufListList::add(scene::IMeshBuffer *buf, v3s16 position, u8 layer)
42 {
43         // Append to the correct layer
44         std::vector<MeshBufList> &list = lists[layer];
45         const video::SMaterial &m = buf->getMaterial();
46         for (MeshBufList &l : list) {
47                 // comparing a full material is quite expensive so we don't do it if
48                 // not even first texture is equal
49                 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
50                         continue;
51
52                 if (l.m == m) {
53                         l.bufs.emplace_back(position, buf);
54                         return;
55                 }
56         }
57         MeshBufList l;
58         l.m = m;
59         l.bufs.emplace_back(position, buf);
60         list.emplace_back(l);
61 }
62
63 // ClientMap
64
65 ClientMap::ClientMap(
66                 Client *client,
67                 MapDrawControl &control,
68                 s32 id
69 ):
70         Map(client),
71         scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
72                 RenderingEngine::get_scene_manager(), id),
73         m_client(client),
74         m_control(control)
75 {
76         m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
77                         BS*1000000,BS*1000000,BS*1000000);
78
79         /* TODO: Add a callback function so these can be updated when a setting
80          *       changes.  At this point in time it doesn't matter (e.g. /set
81          *       is documented to change server settings only)
82          *
83          * TODO: Local caching of settings is not optimal and should at some stage
84          *       be updated to use a global settings object for getting thse values
85          *       (as opposed to the this local caching). This can be addressed in
86          *       a later release.
87          */
88         m_cache_trilinear_filter  = g_settings->getBool("trilinear_filter");
89         m_cache_bilinear_filter   = g_settings->getBool("bilinear_filter");
90         m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
91
92 }
93
94 MapSector * ClientMap::emergeSector(v2s16 p2d)
95 {
96         // Check that it doesn't exist already
97         MapSector *sector = getSectorNoGenerate(p2d);
98
99         // Create it if it does not exist yet
100         if (!sector) {
101                 sector = new MapSector(this, p2d, m_gamedef);
102                 m_sectors[p2d] = sector;
103         }
104
105         return sector;
106 }
107
108 void ClientMap::OnRegisterSceneNode()
109 {
110         if(IsVisible)
111         {
112                 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
113                 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
114         }
115
116         ISceneNode::OnRegisterSceneNode();
117 }
118
119 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
120                 v3s16 *p_blocks_min, v3s16 *p_blocks_max)
121 {
122         v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
123         // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
124         // can exceed the range of v3s16 when a large view range is used near the
125         // world edges.
126         v3s32 p_nodes_min(
127                 cam_pos_nodes.X - box_nodes_d.X,
128                 cam_pos_nodes.Y - box_nodes_d.Y,
129                 cam_pos_nodes.Z - box_nodes_d.Z);
130         v3s32 p_nodes_max(
131                 cam_pos_nodes.X + box_nodes_d.X,
132                 cam_pos_nodes.Y + box_nodes_d.Y,
133                 cam_pos_nodes.Z + box_nodes_d.Z);
134         // Take a fair amount as we will be dropping more out later
135         // Umm... these additions are a bit strange but they are needed.
136         *p_blocks_min = v3s16(
137                         p_nodes_min.X / MAP_BLOCKSIZE - 3,
138                         p_nodes_min.Y / MAP_BLOCKSIZE - 3,
139                         p_nodes_min.Z / MAP_BLOCKSIZE - 3);
140         *p_blocks_max = v3s16(
141                         p_nodes_max.X / MAP_BLOCKSIZE + 1,
142                         p_nodes_max.Y / MAP_BLOCKSIZE + 1,
143                         p_nodes_max.Z / MAP_BLOCKSIZE + 1);
144 }
145
146 void ClientMap::updateDrawList()
147 {
148         ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
149
150         for (auto &i : m_drawlist) {
151                 MapBlock *block = i.second;
152                 block->refDrop();
153         }
154         m_drawlist.clear();
155
156         const v3f camera_position = m_camera_position;
157         const v3f camera_direction = m_camera_direction;
158
159         // Use a higher fov to accomodate faster camera movements.
160         // Blocks are cropped better when they are drawn.
161         const f32 camera_fov = m_camera_fov * 1.1f;
162
163         v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
164         v3s16 p_blocks_min;
165         v3s16 p_blocks_max;
166         getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
167
168         // Read the vision range, unless unlimited range is enabled.
169         float range = m_control.range_all ? 1e7 : m_control.wanted_range;
170
171         // Number of blocks currently loaded by the client
172         u32 blocks_loaded = 0;
173         // Number of blocks with mesh in rendering range
174         u32 blocks_in_range_with_mesh = 0;
175         // Number of blocks occlusion culled
176         u32 blocks_occlusion_culled = 0;
177
178         // No occlusion culling when free_move is on and camera is
179         // inside ground
180         bool occlusion_culling_enabled = true;
181         if (g_settings->getBool("free_move") && g_settings->getBool("noclip")) {
182                 MapNode n = getNode(cam_pos_nodes);
183                 if (n.getContent() == CONTENT_IGNORE ||
184                                 m_nodedef->get(n).solidness == 2)
185                         occlusion_culling_enabled = false;
186         }
187
188
189         // Uncomment to debug occluded blocks in the wireframe mode
190         // TODO: Include this as a flag for an extended debugging setting
191         //if (occlusion_culling_enabled && m_control.show_wireframe)
192         //    occlusion_culling_enabled = porting::getTimeS() & 1;
193
194         for (const auto &sector_it : m_sectors) {
195                 MapSector *sector = sector_it.second;
196                 v2s16 sp = sector->getPos();
197
198                 blocks_loaded += sector->size();
199                 if (!m_control.range_all) {
200                         if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
201                                         sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
202                                 continue;
203                 }
204
205                 MapBlockVect sectorblocks;
206                 sector->getBlocks(sectorblocks);
207
208                 /*
209                         Loop through blocks in sector
210                 */
211
212                 u32 sector_blocks_drawn = 0;
213
214                 for (MapBlock *block : sectorblocks) {
215                         /*
216                                 Compare block position to camera position, skip
217                                 if not seen on display
218                         */
219
220                         if (!block->mesh) {
221                                 // Ignore if mesh doesn't exist
222                                 continue;
223                         }
224
225                         v3s16 block_coord = block->getPos();
226                         v3s16 block_position = block->getPosRelative() + MAP_BLOCKSIZE / 2;
227
228                         // First, perform a simple distance check, with a padding of one extra block.
229                         if (!m_control.range_all &&
230                                         block_position.getDistanceFrom(cam_pos_nodes) > range + MAP_BLOCKSIZE)
231                                 continue; // Out of range, skip.
232
233                         // Keep the block alive as long as it is in range.
234                         block->resetUsageTimer();
235                         blocks_in_range_with_mesh++;
236
237                         // Frustum culling
238                         float d = 0.0;
239                         if (!isBlockInSight(block_coord, camera_position,
240                                         camera_direction, camera_fov, range * BS, &d))
241                                 continue;
242
243                         // Occlusion culling
244                         if ((!m_control.range_all && d > m_control.wanted_range * BS) ||
245                                         (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) {
246                                 blocks_occlusion_culled++;
247                                 continue;
248                         }
249
250                         // Add to set
251                         block->refGrab();
252                         m_drawlist[block_coord] = block;
253
254                         sector_blocks_drawn++;
255                 } // foreach sectorblocks
256
257                 if (sector_blocks_drawn != 0)
258                         m_last_drawn_sectors.insert(sp);
259         }
260
261         g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
262         g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
263         g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
264         g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
265 }
266
267 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
268 {
269         bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
270
271         std::string prefix;
272         if (pass == scene::ESNRP_SOLID)
273                 prefix = "renderMap(SOLID): ";
274         else
275                 prefix = "renderMap(TRANSPARENT): ";
276
277         /*
278                 This is called two times per frame, reset on the non-transparent one
279         */
280         if (pass == scene::ESNRP_SOLID)
281                 m_last_drawn_sectors.clear();
282
283         /*
284                 Get animation parameters
285         */
286         const float animation_time = m_client->getAnimationTime();
287         const int crack = m_client->getCrackLevel();
288         const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
289
290         const v3f camera_position = m_camera_position;
291
292         /*
293                 Get all blocks and draw all visible ones
294         */
295
296         u32 vertex_count = 0;
297         u32 drawcall_count = 0;
298
299         // For limiting number of mesh animations per frame
300         u32 mesh_animate_count = 0;
301         //u32 mesh_animate_count_far = 0;
302
303         /*
304                 Draw the selected MapBlocks
305         */
306
307         MeshBufListList drawbufs;
308
309         for (auto &i : m_drawlist) {
310                 v3s16 block_pos = i.first;
311                 MapBlock *block = i.second;
312
313                 // If the mesh of the block happened to get deleted, ignore it
314                 if (!block->mesh)
315                         continue;
316
317                 v3f block_pos_r = intToFloat(block->getPosRelative() + MAP_BLOCKSIZE / 2, BS);
318                 float d = camera_position.getDistanceFrom(block_pos_r);
319                 d = MYMAX(0,d - BLOCK_MAX_RADIUS);
320                 
321                 // Mesh animation
322                 if (pass == scene::ESNRP_SOLID) {
323                         //MutexAutoLock lock(block->mesh_mutex);
324                         MapBlockMesh *mapBlockMesh = block->mesh;
325                         assert(mapBlockMesh);
326                         // Pretty random but this should work somewhat nicely
327                         bool faraway = d >= BS * 50;
328                         if (mapBlockMesh->isAnimationForced() || !faraway ||
329                                         mesh_animate_count < (m_control.range_all ? 200 : 50)) {
330
331                                 bool animated = mapBlockMesh->animate(faraway, animation_time,
332                                         crack, daynight_ratio);
333                                 if (animated)
334                                         mesh_animate_count++;
335                         } else {
336                                 mapBlockMesh->decreaseAnimationForceTimer();
337                         }
338                 }
339
340                 /*
341                         Get the meshbuffers of the block
342                 */
343                 {
344                         //MutexAutoLock lock(block->mesh_mutex);
345
346                         MapBlockMesh *mapBlockMesh = block->mesh;
347                         assert(mapBlockMesh);
348
349                         for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
350                                 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
351                                 assert(mesh);
352
353                                 u32 c = mesh->getMeshBufferCount();
354                                 for (u32 i = 0; i < c; i++) {
355                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
356
357                                         video::SMaterial& material = buf->getMaterial();
358                                         video::IMaterialRenderer* rnd =
359                                                 driver->getMaterialRenderer(material.MaterialType);
360                                         bool transparent = (rnd && rnd->isTransparent());
361                                         if (transparent == is_transparent_pass) {
362                                                 if (buf->getVertexCount() == 0)
363                                                         errorstream << "Block [" << analyze_block(block)
364                                                                 << "] contains an empty meshbuf" << std::endl;
365
366                                                 material.setFlag(video::EMF_TRILINEAR_FILTER,
367                                                         m_cache_trilinear_filter);
368                                                 material.setFlag(video::EMF_BILINEAR_FILTER,
369                                                         m_cache_bilinear_filter);
370                                                 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
371                                                         m_cache_anistropic_filter);
372                                                 material.setFlag(video::EMF_WIREFRAME,
373                                                         m_control.show_wireframe);
374
375                                                 drawbufs.add(buf, block_pos, layer);
376                                         }
377                                 }
378                         }
379                 }
380         }
381
382         TimeTaker draw("Drawing mesh buffers");
383
384         core::matrix4 m; // Model matrix
385         v3f offset = intToFloat(m_camera_offset, BS);
386
387         // Render all layers in order
388         for (auto &lists : drawbufs.lists) {
389                 for (MeshBufList &list : lists) {
390                         // Check and abort if the machine is swapping a lot
391                         if (draw.getTimerTime() > 2000) {
392                                 infostream << "ClientMap::renderMap(): Rendering took >2s, " <<
393                                                 "returning." << std::endl;
394                                 return;
395                         }
396                         driver->setMaterial(list.m);
397
398                         drawcall_count += list.bufs.size();
399                         for (auto &pair : list.bufs) {
400                                 scene::IMeshBuffer *buf = pair.second;
401
402                                 v3f block_wpos = intToFloat(pair.first * MAP_BLOCKSIZE, BS);
403                                 m.setTranslation(block_wpos - offset);
404
405                                 driver->setTransform(video::ETS_WORLD, m);
406                                 driver->drawMeshBuffer(buf);
407                                 vertex_count += buf->getVertexCount();
408                         }
409                 }
410         }
411         g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
412
413         // Log only on solid pass because values are the same
414         if (pass == scene::ESNRP_SOLID) {
415                 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
416         }
417
418         g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
419         g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
420 }
421
422 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
423         float step_multiplier, float start_distance, float end_distance,
424         const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
425         int *result, bool *sunlight_seen)
426 {
427         int brightness_sum = 0;
428         int brightness_count = 0;
429         float distance = start_distance;
430         dir.normalize();
431         v3f pf = p0;
432         pf += dir * distance;
433         int noncount = 0;
434         bool nonlight_seen = false;
435         bool allow_allowing_non_sunlight_propagates = false;
436         bool allow_non_sunlight_propagates = false;
437         // Check content nearly at camera position
438         {
439                 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
440                 MapNode n = map->getNode(p);
441                 if(ndef->get(n).param_type == CPT_LIGHT &&
442                                 !ndef->get(n).sunlight_propagates)
443                         allow_allowing_non_sunlight_propagates = true;
444         }
445         // If would start at CONTENT_IGNORE, start closer
446         {
447                 v3s16 p = floatToInt(pf, BS);
448                 MapNode n = map->getNode(p);
449                 if(n.getContent() == CONTENT_IGNORE){
450                         float newd = 2*BS;
451                         pf = p0 + dir * 2*newd;
452                         distance = newd;
453                         sunlight_min_d = 0;
454                 }
455         }
456         for (int i=0; distance < end_distance; i++) {
457                 pf += dir * step;
458                 distance += step;
459                 step *= step_multiplier;
460
461                 v3s16 p = floatToInt(pf, BS);
462                 MapNode n = map->getNode(p);
463                 if (allow_allowing_non_sunlight_propagates && i == 0 &&
464                                 ndef->get(n).param_type == CPT_LIGHT &&
465                                 !ndef->get(n).sunlight_propagates) {
466                         allow_non_sunlight_propagates = true;
467                 }
468
469                 if (ndef->get(n).param_type != CPT_LIGHT ||
470                                 (!ndef->get(n).sunlight_propagates &&
471                                         !allow_non_sunlight_propagates)){
472                         nonlight_seen = true;
473                         noncount++;
474                         if(noncount >= 4)
475                                 break;
476                         continue;
477                 }
478
479                 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
480                         if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
481                                 *sunlight_seen = true;
482                 noncount = 0;
483                 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
484                 brightness_count++;
485         }
486         *result = 0;
487         if(brightness_count == 0)
488                 return false;
489         *result = brightness_sum / brightness_count;
490         /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
491                         <<(*result)<<std::endl;*/
492         return true;
493 }
494
495 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
496                 int oldvalue, bool *sunlight_seen_result)
497 {
498         ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
499         static v3f z_directions[50] = {
500                 v3f(-100, 0, 0)
501         };
502         static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
503                 -1000,
504         };
505
506         if(z_directions[0].X < -99){
507                 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
508                         // Assumes FOV of 72 and 16/9 aspect ratio
509                         z_directions[i] = v3f(
510                                 0.02 * myrand_range(-100, 100),
511                                 1.0,
512                                 0.01 * myrand_range(-100, 100)
513                         ).normalize();
514                         z_offsets[i] = 0.01 * myrand_range(0,100);
515                 }
516         }
517
518         int sunlight_seen_count = 0;
519         float sunlight_min_d = max_d*0.8;
520         if(sunlight_min_d > 35*BS)
521                 sunlight_min_d = 35*BS;
522         std::vector<int> values;
523         for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
524                 v3f z_dir = z_directions[i];
525                 core::CMatrix4<f32> a;
526                 a.buildRotateFromTo(v3f(0,1,0), z_dir);
527                 v3f dir = m_camera_direction;
528                 a.rotateVect(dir);
529                 int br = 0;
530                 float step = BS*1.5;
531                 if(max_d > 35*BS)
532                         step = max_d / 35 * 1.5;
533                 float off = step * z_offsets[i];
534                 bool sunlight_seen_now = false;
535                 bool ok = getVisibleBrightness(this, m_camera_position, dir,
536                                 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
537                                 sunlight_min_d,
538                                 &br, &sunlight_seen_now);
539                 if(sunlight_seen_now)
540                         sunlight_seen_count++;
541                 if(!ok)
542                         continue;
543                 values.push_back(br);
544                 // Don't try too much if being in the sun is clear
545                 if(sunlight_seen_count >= 20)
546                         break;
547         }
548         int brightness_sum = 0;
549         int brightness_count = 0;
550         std::sort(values.begin(), values.end());
551         u32 num_values_to_use = values.size();
552         if(num_values_to_use >= 10)
553                 num_values_to_use -= num_values_to_use/2;
554         else if(num_values_to_use >= 7)
555                 num_values_to_use -= num_values_to_use/3;
556         u32 first_value_i = (values.size() - num_values_to_use) / 2;
557
558         for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
559                 brightness_sum += values[i];
560                 brightness_count++;
561         }
562
563         int ret = 0;
564         if(brightness_count == 0){
565                 MapNode n = getNode(floatToInt(m_camera_position, BS));
566                 if(m_nodedef->get(n).param_type == CPT_LIGHT){
567                         ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
568                 } else {
569                         ret = oldvalue;
570                 }
571         } else {
572                 ret = brightness_sum / brightness_count;
573         }
574
575         *sunlight_seen_result = (sunlight_seen_count > 0);
576         return ret;
577 }
578
579 void ClientMap::renderPostFx(CameraMode cam_mode)
580 {
581         // Sadly ISceneManager has no "post effects" render pass, in that case we
582         // could just register for that and handle it in renderMap().
583
584         MapNode n = getNode(floatToInt(m_camera_position, BS));
585
586         // - If the player is in a solid node, make everything black.
587         // - If the player is in liquid, draw a semi-transparent overlay.
588         // - Do not if player is in third person mode
589         const ContentFeatures& features = m_nodedef->get(n);
590         video::SColor post_effect_color = features.post_effect_color;
591         if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
592                         m_client->checkLocalPrivilege("noclip")) &&
593                         cam_mode == CAMERA_MODE_FIRST)
594         {
595                 post_effect_color = video::SColor(255, 0, 0, 0);
596         }
597         if (post_effect_color.getAlpha() != 0)
598         {
599                 // Draw a full-screen rectangle
600                 video::IVideoDriver* driver = SceneManager->getVideoDriver();
601                 v2u32 ss = driver->getScreenSize();
602                 core::rect<s32> rect(0,0, ss.X, ss.Y);
603                 driver->draw2DRectangle(post_effect_color, rect);
604         }
605 }
606
607 void ClientMap::PrintInfo(std::ostream &out)
608 {
609         out<<"ClientMap: ";
610 }