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