]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/clientmap.cpp
Merge branch 'master' of https://github.com/minetest/minetest
[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         // Number of blocks currently loaded by the client
169         u32 blocks_loaded = 0;
170         // Number of blocks with mesh in rendering range
171         u32 blocks_in_range_with_mesh = 0;
172         // Number of blocks occlusion culled
173         u32 blocks_occlusion_culled = 0;
174
175         // No occlusion culling when free_move is on and camera is
176         // inside ground
177         bool occlusion_culling_enabled = true;
178         if ((g_settings->getBool("free_move") && g_settings->getBool("noclip")) || g_settings->getBool("freecam")) {
179                 MapNode n = getNode(cam_pos_nodes);
180                 if (n.getContent() == CONTENT_IGNORE ||
181                                 m_nodedef->get(n).solidness == 2)
182                         occlusion_culling_enabled = false;
183         }
184
185         // Uncomment to debug occluded blocks in the wireframe mode
186         // TODO: Include this as a flag for an extended debugging setting
187         //if (occlusion_culling_enabled && m_control.show_wireframe)
188         //    occlusion_culling_enabled = porting::getTimeS() & 1;
189
190         for (const auto &sector_it : m_sectors) {
191                 MapSector *sector = sector_it.second;
192                 v2s16 sp = sector->getPos();
193
194                 blocks_loaded += sector->size();
195                 if (!m_control.range_all) {
196                         if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
197                                         sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
198                                 continue;
199                 }
200
201                 MapBlockVect sectorblocks;
202                 sector->getBlocks(sectorblocks);
203
204                 /*
205                         Loop through blocks in sector
206                 */
207
208                 u32 sector_blocks_drawn = 0;
209
210                 for (MapBlock *block : sectorblocks) {
211                         /*
212                                 Compare block position to camera position, skip
213                                 if not seen on display
214                         */
215
216                         if (!block->mesh) {
217                                 // Ignore if mesh doesn't exist
218                                 continue;
219                         }
220
221                         float range = 100000 * BS;
222                         if (!m_control.range_all)
223                                 range = m_control.wanted_range * BS;
224
225                         float d = 0.0;
226                         if (!isBlockInSight(block->getPos(), camera_position,
227                                         camera_direction, camera_fov, range, &d))
228                                 continue;
229
230                         blocks_in_range_with_mesh++;
231
232                         /*
233                                 Occlusion culling
234                         */
235                         if ((!m_control.range_all && d > m_control.wanted_range * BS) ||
236                                         (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) {
237                                 blocks_occlusion_culled++;
238                                 continue;
239                         }
240
241                         // This block is in range. Reset usage timer.
242                         block->resetUsageTimer();
243
244                         // Add to set
245                         block->refGrab();
246                         m_drawlist[block->getPos()] = block;
247
248                         sector_blocks_drawn++;
249                 } // foreach sectorblocks
250
251                 if (sector_blocks_drawn != 0)
252                         m_last_drawn_sectors.insert(sp);
253         }
254
255         g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
256         g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
257         g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
258         g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
259 }
260
261 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
262 {
263         bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
264
265         std::string prefix;
266         if (pass == scene::ESNRP_SOLID)
267                 prefix = "renderMap(SOLID): ";
268         else
269                 prefix = "renderMap(TRANSPARENT): ";
270
271         /*
272                 This is called two times per frame, reset on the non-transparent one
273         */
274         if (pass == scene::ESNRP_SOLID)
275                 m_last_drawn_sectors.clear();
276
277         /*
278                 Get animation parameters
279         */
280         const float animation_time = m_client->getAnimationTime();
281         const int crack = m_client->getCrackLevel();
282         const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
283
284         const v3f camera_position = m_camera_position;
285         const v3f camera_direction = m_camera_direction;
286         const f32 camera_fov = m_camera_fov;
287
288         /*
289                 Get all blocks and draw all visible ones
290         */
291
292         u32 vertex_count = 0;
293         u32 drawcall_count = 0;
294
295         // For limiting number of mesh animations per frame
296         u32 mesh_animate_count = 0;
297         //u32 mesh_animate_count_far = 0;
298
299         /*
300                 Draw the selected MapBlocks
301         */
302
303         MeshBufListList drawbufs;
304
305         for (auto &i : m_drawlist) {
306                 v3s16 block_pos = i.first;
307                 MapBlock *block = i.second;
308
309                 // If the mesh of the block happened to get deleted, ignore it
310                 if (!block->mesh)
311                         continue;
312
313                 float d = 0.0;
314                 if (!isBlockInSight(block->getPos(), camera_position,
315                                 camera_direction, camera_fov, 100000 * BS, &d))
316                         continue;
317
318                 // Mesh animation
319                 if (pass == scene::ESNRP_SOLID) {
320                         //MutexAutoLock lock(block->mesh_mutex);
321                         MapBlockMesh *mapBlockMesh = block->mesh;
322                         assert(mapBlockMesh);
323                         // Pretty random but this should work somewhat nicely
324                         bool faraway = d >= BS * 50;
325                         if (mapBlockMesh->isAnimationForced() || !faraway ||
326                                         mesh_animate_count < (m_control.range_all ? 200 : 50)) {
327
328                                 bool animated = mapBlockMesh->animate(faraway, animation_time,
329                                         crack, daynight_ratio);
330                                 if (animated)
331                                         mesh_animate_count++;
332                         } else {
333                                 mapBlockMesh->decreaseAnimationForceTimer();
334                         }
335                 }
336
337                 /*
338                         Get the meshbuffers of the block
339                 */
340                 {
341                         //MutexAutoLock lock(block->mesh_mutex);
342
343                         MapBlockMesh *mapBlockMesh = block->mesh;
344                         assert(mapBlockMesh);
345
346                         for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
347                                 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
348                                 assert(mesh);
349
350                                 u32 c = mesh->getMeshBufferCount();
351                                 for (u32 i = 0; i < c; i++) {
352                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
353
354                                         video::SMaterial& material = buf->getMaterial();
355                                         video::IMaterialRenderer* rnd =
356                                                 driver->getMaterialRenderer(material.MaterialType);
357                                         bool transparent = (rnd && rnd->isTransparent());
358                                         if (transparent == is_transparent_pass) {
359                                                 if (buf->getVertexCount() == 0)
360                                                         errorstream << "Block [" << analyze_block(block)
361                                                                 << "] contains an empty meshbuf" << std::endl;
362
363                                                 material.setFlag(video::EMF_TRILINEAR_FILTER,
364                                                         m_cache_trilinear_filter);
365                                                 material.setFlag(video::EMF_BILINEAR_FILTER,
366                                                         m_cache_bilinear_filter);
367                                                 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
368                                                         m_cache_anistropic_filter);
369                                                 material.setFlag(video::EMF_WIREFRAME,
370                                                         m_control.show_wireframe);
371
372                                                 drawbufs.add(buf, block_pos, layer);
373                                         }
374                                 }
375                         }
376                 }
377         }
378
379         TimeTaker draw("Drawing mesh buffers");
380
381         core::matrix4 m; // Model matrix
382         v3f offset = intToFloat(m_camera_offset, BS);
383
384         // Render all layers in order
385         for (auto &lists : drawbufs.lists) {
386                 for (MeshBufList &list : lists) {
387                         // Check and abort if the machine is swapping a lot
388                         if (draw.getTimerTime() > 2000) {
389                                 infostream << "ClientMap::renderMap(): Rendering took >2s, " <<
390                                                 "returning." << std::endl;
391                                 return;
392                         }
393                         driver->setMaterial(list.m);
394
395                         drawcall_count += list.bufs.size();
396                         for (auto &pair : list.bufs) {
397                                 scene::IMeshBuffer *buf = pair.second;
398
399                                 v3f block_wpos = intToFloat(pair.first * MAP_BLOCKSIZE, BS);
400                                 m.setTranslation(block_wpos - offset);
401
402                                 driver->setTransform(video::ETS_WORLD, m);
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         g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
417 }
418
419 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
420         float step_multiplier, float start_distance, float end_distance,
421         const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
422         int *result, bool *sunlight_seen)
423 {
424         int brightness_sum = 0;
425         int brightness_count = 0;
426         float distance = start_distance;
427         dir.normalize();
428         v3f pf = p0;
429         pf += dir * distance;
430         int noncount = 0;
431         bool nonlight_seen = false;
432         bool allow_allowing_non_sunlight_propagates = false;
433         bool allow_non_sunlight_propagates = false;
434         // Check content nearly at camera position
435         {
436                 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
437                 MapNode n = map->getNode(p);
438                 if(ndef->get(n).param_type == CPT_LIGHT &&
439                                 !ndef->get(n).sunlight_propagates)
440                         allow_allowing_non_sunlight_propagates = true;
441         }
442         // If would start at CONTENT_IGNORE, start closer
443         {
444                 v3s16 p = floatToInt(pf, BS);
445                 MapNode n = map->getNode(p);
446                 if(n.getContent() == CONTENT_IGNORE){
447                         float newd = 2*BS;
448                         pf = p0 + dir * 2*newd;
449                         distance = newd;
450                         sunlight_min_d = 0;
451                 }
452         }
453         for (int i=0; distance < end_distance; i++) {
454                 pf += dir * step;
455                 distance += step;
456                 step *= step_multiplier;
457
458                 v3s16 p = floatToInt(pf, BS);
459                 MapNode n = map->getNode(p);
460                 if (allow_allowing_non_sunlight_propagates && i == 0 &&
461                                 ndef->get(n).param_type == CPT_LIGHT &&
462                                 !ndef->get(n).sunlight_propagates) {
463                         allow_non_sunlight_propagates = true;
464                 }
465
466                 if (ndef->get(n).param_type != CPT_LIGHT ||
467                                 (!ndef->get(n).sunlight_propagates &&
468                                         !allow_non_sunlight_propagates)){
469                         nonlight_seen = true;
470                         noncount++;
471                         if(noncount >= 4)
472                                 break;
473                         continue;
474                 }
475
476                 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
477                         if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
478                                 *sunlight_seen = true;
479                 noncount = 0;
480                 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
481                 brightness_count++;
482         }
483         *result = 0;
484         if(brightness_count == 0)
485                 return false;
486         *result = brightness_sum / brightness_count;
487         /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
488                         <<(*result)<<std::endl;*/
489         return true;
490 }
491
492 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
493                 int oldvalue, bool *sunlight_seen_result)
494 {
495         ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
496         static v3f z_directions[50] = {
497                 v3f(-100, 0, 0)
498         };
499         static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
500                 -1000,
501         };
502
503         if(z_directions[0].X < -99){
504                 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
505                         // Assumes FOV of 72 and 16/9 aspect ratio
506                         z_directions[i] = v3f(
507                                 0.02 * myrand_range(-100, 100),
508                                 1.0,
509                                 0.01 * myrand_range(-100, 100)
510                         ).normalize();
511                         z_offsets[i] = 0.01 * myrand_range(0,100);
512                 }
513         }
514
515         int sunlight_seen_count = 0;
516         float sunlight_min_d = max_d*0.8;
517         if(sunlight_min_d > 35*BS)
518                 sunlight_min_d = 35*BS;
519         std::vector<int> values;
520         for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
521                 v3f z_dir = z_directions[i];
522                 core::CMatrix4<f32> a;
523                 a.buildRotateFromTo(v3f(0,1,0), z_dir);
524                 v3f dir = m_camera_direction;
525                 a.rotateVect(dir);
526                 int br = 0;
527                 float step = BS*1.5;
528                 if(max_d > 35*BS)
529                         step = max_d / 35 * 1.5;
530                 float off = step * z_offsets[i];
531                 bool sunlight_seen_now = false;
532                 bool ok = getVisibleBrightness(this, m_camera_position, dir,
533                                 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
534                                 sunlight_min_d,
535                                 &br, &sunlight_seen_now);
536                 if(sunlight_seen_now)
537                         sunlight_seen_count++;
538                 if(!ok)
539                         continue;
540                 values.push_back(br);
541                 // Don't try too much if being in the sun is clear
542                 if(sunlight_seen_count >= 20)
543                         break;
544         }
545         int brightness_sum = 0;
546         int brightness_count = 0;
547         std::sort(values.begin(), values.end());
548         u32 num_values_to_use = values.size();
549         if(num_values_to_use >= 10)
550                 num_values_to_use -= num_values_to_use/2;
551         else if(num_values_to_use >= 7)
552                 num_values_to_use -= num_values_to_use/3;
553         u32 first_value_i = (values.size() - num_values_to_use) / 2;
554
555         for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
556                 brightness_sum += values[i];
557                 brightness_count++;
558         }
559
560         int ret = 0;
561         if(brightness_count == 0){
562                 MapNode n = getNode(floatToInt(m_camera_position, BS));
563                 if(m_nodedef->get(n).param_type == CPT_LIGHT){
564                         ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
565                 } else {
566                         ret = oldvalue;
567                 }
568         } else {
569                 ret = brightness_sum / brightness_count;
570         }
571
572         *sunlight_seen_result = (sunlight_seen_count > 0);
573         return ret;
574 }
575
576 void ClientMap::renderPostFx(CameraMode cam_mode)
577 {
578         // Sadly ISceneManager has no "post effects" render pass, in that case we
579         // could just register for that and handle it in renderMap().
580
581         MapNode n = getNode(floatToInt(m_camera_position, BS));
582
583         // - If the player is in a solid node, make everything black.
584         // - If the player is in liquid, draw a semi-transparent overlay.
585         // - Do not if player is in third person mode
586         const ContentFeatures& features = m_nodedef->get(n);
587         video::SColor post_effect_color = features.post_effect_color;
588         if(features.solidness == 2 && !((g_settings->getBool("noclip") || g_settings->getBool("freecam")) &&
589                         (m_client->checkLocalPrivilege("noclip") || g_settings->getBool("freecam"))) &&
590                         cam_mode == CAMERA_MODE_FIRST)
591         {
592                 post_effect_color = video::SColor(255, 0, 0, 0);
593         }
594         if (post_effect_color.getAlpha() != 0)
595         {
596                 // Draw a full-screen rectangle
597                 video::IVideoDriver* driver = SceneManager->getVideoDriver();
598                 v2u32 ss = driver->getScreenSize();
599                 core::rect<s32> rect(0,0, ss.X, ss.Y);
600                 driver->draw2DRectangle(post_effect_color, rect);
601         }
602 }
603
604 void ClientMap::PrintInfo(std::ostream &out)
605 {
606         out<<"ClientMap: ";
607 }