]> git.lizzy.rs Git - minetest.git/blob - src/client/clientmap.cpp
Fix rounding errors when slicing the shadow draw list (#13226)
[minetest.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 "client/renderingengine.h"
32
33 #include <queue>
34
35 // struct MeshBufListList
36 void MeshBufListList::clear()
37 {
38         for (auto &list : lists)
39                 list.clear();
40 }
41
42 void MeshBufListList::add(scene::IMeshBuffer *buf, v3s16 position, u8 layer)
43 {
44         // Append to the correct layer
45         std::vector<MeshBufList> &list = lists[layer];
46         const video::SMaterial &m = buf->getMaterial();
47         for (MeshBufList &l : list) {
48                 // comparing a full material is quite expensive so we don't do it if
49                 // not even first texture is equal
50                 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
51                         continue;
52
53                 if (l.m == m) {
54                         l.bufs.emplace_back(position, buf);
55                         return;
56                 }
57         }
58         MeshBufList l;
59         l.m = m;
60         l.bufs.emplace_back(position, buf);
61         list.emplace_back(l);
62 }
63
64 static void on_settings_changed(const std::string &name, void *data)
65 {
66         static_cast<ClientMap*>(data)->onSettingChanged(name);
67 }
68 // ClientMap
69
70 ClientMap::ClientMap(
71                 Client *client,
72                 RenderingEngine *rendering_engine,
73                 MapDrawControl &control,
74                 s32 id
75 ):
76         Map(client),
77         scene::ISceneNode(rendering_engine->get_scene_manager()->getRootSceneNode(),
78                 rendering_engine->get_scene_manager(), id),
79         m_client(client),
80         m_rendering_engine(rendering_engine),
81         m_control(control),
82         m_drawlist(MapBlockComparer(v3s16(0,0,0)))
83 {
84
85         /*
86          * @Liso: Sadly C++ doesn't have introspection, so the only way we have to know
87          * the class is whith a name ;) Name property cames from ISceneNode base class.
88          */
89         Name = "ClientMap";
90         m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
91                         BS*1000000,BS*1000000,BS*1000000);
92
93         /* TODO: Add a callback function so these can be updated when a setting
94          *       changes.  At this point in time it doesn't matter (e.g. /set
95          *       is documented to change server settings only)
96          *
97          * TODO: Local caching of settings is not optimal and should at some stage
98          *       be updated to use a global settings object for getting thse values
99          *       (as opposed to the this local caching). This can be addressed in
100          *       a later release.
101          */
102         m_cache_trilinear_filter  = g_settings->getBool("trilinear_filter");
103         m_cache_bilinear_filter   = g_settings->getBool("bilinear_filter");
104         m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
105         m_cache_transparency_sorting_distance = g_settings->getU16("transparency_sorting_distance");
106         m_enable_raytraced_culling = g_settings->getBool("enable_raytraced_culling");
107         g_settings->registerChangedCallback("enable_raytraced_culling", on_settings_changed, this);
108 }
109
110 void ClientMap::onSettingChanged(const std::string &name)
111 {
112         if (name == "enable_raytraced_culling")
113                 m_enable_raytraced_culling = g_settings->getBool("enable_raytraced_culling");
114 }
115
116 ClientMap::~ClientMap()
117 {
118         g_settings->deregisterChangedCallback("enable_raytraced_culling", on_settings_changed, this);
119 }
120
121 void ClientMap::updateCamera(v3f pos, v3f dir, f32 fov, v3s16 offset)
122 {
123         v3s16 previous_node = floatToInt(m_camera_position, BS) + m_camera_offset;
124         v3s16 previous_block = getContainerPos(previous_node, MAP_BLOCKSIZE);
125
126         m_camera_position = pos;
127         m_camera_direction = dir;
128         m_camera_fov = fov;
129         m_camera_offset = offset;
130
131         v3s16 current_node = floatToInt(m_camera_position, BS) + m_camera_offset;
132         v3s16 current_block = getContainerPos(current_node, MAP_BLOCKSIZE);
133
134         // reorder the blocks when camera crosses block boundary
135         if (previous_block != current_block)
136                 m_needs_update_drawlist = true;
137
138         // reorder transparent meshes when camera crosses node boundary
139         if (previous_node != current_node)
140                 m_needs_update_transparent_meshes = true;
141 }
142
143 MapSector * ClientMap::emergeSector(v2s16 p2d)
144 {
145         // Check that it doesn't exist already
146         MapSector *sector = getSectorNoGenerate(p2d);
147
148         // Create it if it does not exist yet
149         if (!sector) {
150                 sector = new MapSector(this, p2d, m_gamedef);
151                 m_sectors[p2d] = sector;
152         }
153
154         return sector;
155 }
156
157 void ClientMap::OnRegisterSceneNode()
158 {
159         if(IsVisible)
160         {
161                 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
162                 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
163         }
164
165         ISceneNode::OnRegisterSceneNode();
166         // It's not needed to register this node to the shadow renderer
167         // we have other way to find it
168 }
169
170 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
171                 v3s16 *p_blocks_min, v3s16 *p_blocks_max, float range)
172 {
173         if (range <= 0.0f)
174                 range = m_control.wanted_range;
175
176         v3s16 box_nodes_d = range * v3s16(1, 1, 1);
177         // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
178         // can exceed the range of v3s16 when a large view range is used near the
179         // world edges.
180         v3s32 p_nodes_min(
181                 cam_pos_nodes.X - box_nodes_d.X,
182                 cam_pos_nodes.Y - box_nodes_d.Y,
183                 cam_pos_nodes.Z - box_nodes_d.Z);
184         v3s32 p_nodes_max(
185                 cam_pos_nodes.X + box_nodes_d.X,
186                 cam_pos_nodes.Y + box_nodes_d.Y,
187                 cam_pos_nodes.Z + box_nodes_d.Z);
188         // Take a fair amount as we will be dropping more out later
189         // Umm... these additions are a bit strange but they are needed.
190         *p_blocks_min = v3s16(
191                         p_nodes_min.X / MAP_BLOCKSIZE - 3,
192                         p_nodes_min.Y / MAP_BLOCKSIZE - 3,
193                         p_nodes_min.Z / MAP_BLOCKSIZE - 3);
194         *p_blocks_max = v3s16(
195                         p_nodes_max.X / MAP_BLOCKSIZE + 1,
196                         p_nodes_max.Y / MAP_BLOCKSIZE + 1,
197                         p_nodes_max.Z / MAP_BLOCKSIZE + 1);
198 }
199
200 class MapBlockFlags
201 {
202 public:
203         static constexpr u16 CHUNK_EDGE = 8;
204         static constexpr u16 CHUNK_MASK = CHUNK_EDGE - 1;
205         static constexpr std::size_t CHUNK_VOLUME = CHUNK_EDGE * CHUNK_EDGE * CHUNK_EDGE; // volume of a chunk
206
207         MapBlockFlags(v3s16 min_pos, v3s16 max_pos)
208                         : min_pos(min_pos), volume((max_pos - min_pos) / CHUNK_EDGE + 1)
209         {
210                 chunks.resize(volume.X * volume.Y * volume.Z);
211         }
212
213         class Chunk
214         {
215         public:
216                 inline u8 &getBits(v3s16 pos)
217                 {
218                         std::size_t address = getAddress(pos);
219                         return bits[address];
220                 }
221
222         private:
223                 inline std::size_t getAddress(v3s16 pos) {
224                         std::size_t address = (pos.X & CHUNK_MASK) + (pos.Y & CHUNK_MASK) * CHUNK_EDGE + (pos.Z & CHUNK_MASK) * (CHUNK_EDGE * CHUNK_EDGE);
225                         return address;
226                 }
227
228                 std::array<u8, CHUNK_VOLUME> bits;
229         };
230
231         Chunk &getChunk(v3s16 pos)
232         {
233                 v3s16 delta = (pos - min_pos) / CHUNK_EDGE;
234                 std::size_t address = delta.X + delta.Y * volume.X + delta.Z * volume.X * volume.Y;
235                 Chunk *chunk = chunks[address].get();
236                 if (!chunk) {
237                         chunk = new Chunk();
238                         chunks[address].reset(chunk);
239                 }
240                 return *chunk;
241         }
242 private:
243         std::vector<std::unique_ptr<Chunk>> chunks;
244         v3s16 min_pos;
245         v3s16 volume;
246 };
247
248 void ClientMap::updateDrawList()
249 {
250         ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
251
252         m_needs_update_drawlist = false;
253
254         for (auto &i : m_drawlist) {
255                 MapBlock *block = i.second;
256                 block->refDrop();
257         }
258         m_drawlist.clear();
259
260         for (auto &block : m_keeplist) {
261                 block->refDrop();
262         }
263         m_keeplist.clear();
264
265         v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
266
267         v3s16 p_blocks_min;
268         v3s16 p_blocks_max;
269         getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
270
271         // Number of blocks occlusion culled
272         u32 blocks_occlusion_culled = 0;
273         // Blocks visited by the algorithm
274         u32 blocks_visited = 0;
275         // Block sides that were not traversed
276         u32 sides_skipped = 0;
277
278         // No occlusion culling when free_move is on and camera is inside ground
279         bool occlusion_culling_enabled = true;
280         if (m_control.allow_noclip) {
281                 MapNode n = getNode(cam_pos_nodes);
282                 if (n.getContent() == CONTENT_IGNORE || m_nodedef->get(n).solidness == 2)
283                         occlusion_culling_enabled = false;
284         }
285
286         v3s16 camera_block = getContainerPos(cam_pos_nodes, MAP_BLOCKSIZE);
287         m_drawlist = std::map<v3s16, MapBlock*, MapBlockComparer>(MapBlockComparer(camera_block));
288
289         auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
290
291         // Uncomment to debug occluded blocks in the wireframe mode
292         // TODO: Include this as a flag for an extended debugging setting
293         // if (occlusion_culling_enabled && m_control.show_wireframe)
294         //      occlusion_culling_enabled = porting::getTimeS() & 1;
295
296         std::queue<v3s16> blocks_to_consider;
297
298         // Bits per block:
299         // [ visited | 0 | 0 | 0 | 0 | Z visible | Y visible | X visible ]
300         MapBlockFlags blocks_seen(p_blocks_min, p_blocks_max);
301
302         // Start breadth-first search with the block the camera is in
303         blocks_to_consider.push(camera_block);
304         blocks_seen.getChunk(camera_block).getBits(camera_block) = 0x07; // mark all sides as visible
305
306         std::set<v3s16> shortlist;
307         MeshGrid mesh_grid = m_client->getMeshGrid();
308
309         // Recursively walk the space and pick mapblocks for drawing
310         while (blocks_to_consider.size() > 0) {
311
312                 v3s16 block_coord = blocks_to_consider.front();
313                 blocks_to_consider.pop();
314
315                 auto &flags = blocks_seen.getChunk(block_coord).getBits(block_coord);
316
317                 // Only visit each block once (it may have been queued up to three times)
318                 if ((flags & 0x80) == 0x80)
319                         continue;
320                 flags |= 0x80;
321
322                 blocks_visited++;
323
324                 // Get the sector, block and mesh
325                 MapSector *sector = this->getSectorNoGenerate(v2s16(block_coord.X, block_coord.Z));
326
327                 if (!sector)
328                         continue;
329
330                 MapBlock *block = sector->getBlockNoCreateNoEx(block_coord.Y);
331
332                 MapBlockMesh *mesh = block ? block->mesh : nullptr;
333
334                 // Calculate the coordinates for range and frutum culling
335                 v3f mesh_sphere_center;
336                 f32 mesh_sphere_radius;
337
338                 v3s16 block_pos_nodes = block_coord * MAP_BLOCKSIZE;
339
340                 if (mesh) {
341                         mesh_sphere_center = intToFloat(block_pos_nodes, BS)
342                                         + mesh->getBoundingSphereCenter();
343                         mesh_sphere_radius = mesh->getBoundingRadius();
344                 }
345                 else {
346                         mesh_sphere_center = intToFloat(block_pos_nodes, BS) + v3f((MAP_BLOCKSIZE * 0.5f - 0.5f) * BS);
347                         mesh_sphere_radius = 0.0f;
348                 }
349
350                 // First, perform a simple distance check.
351                 if (!m_control.range_all &&
352                         mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
353                                 m_control.wanted_range * BS + mesh_sphere_radius)
354                         continue; // Out of range, skip.
355
356                 // Frustum culling
357                 // Only do coarse culling here, to account for fast camera movement.
358                 // This is needed because this function is not called every frame.
359                 float frustum_cull_extra_radius = 300.0f;
360                 if (is_frustum_culled(mesh_sphere_center,
361                                 mesh_sphere_radius + frustum_cull_extra_radius))
362                         continue;
363
364                 // Calculate the vector from the camera block to the current block
365                 // We use it to determine through which sides of the current block we can continue the search
366                 v3s16 look = block_coord - camera_block;
367
368                 // Occluded near sides will further occlude the far sides
369                 u8 visible_outer_sides = flags & 0x07;
370
371                 // Raytraced occlusion culling - send rays from the camera to the block's corners
372                 if (occlusion_culling_enabled && m_enable_raytraced_culling &&
373                                 block && mesh &&
374                                 visible_outer_sides != 0x07 && isBlockOccluded(block, cam_pos_nodes)) {
375                         blocks_occlusion_culled++;
376                         continue;
377                 }
378
379                 if (mesh_grid.cell_size > 1) {
380                         // Block meshes are stored in the corner block of a chunk
381                         // (where all coordinate are divisible by the chunk size)
382                         // Add them to the de-dup set.
383                         shortlist.emplace(mesh_grid.getMeshPos(block_coord.X), mesh_grid.getMeshPos(block_coord.Y), mesh_grid.getMeshPos(block_coord.Z));
384                         // All other blocks we can grab and add to the keeplist right away.
385                         if (block) {
386                                 m_keeplist.push_back(block);
387                                 block->refGrab();
388                         }
389                 }
390                 else if (mesh) {
391                         // without mesh chunking we can add the block to the drawlist
392                         block->refGrab();
393                         m_drawlist.emplace(block_coord, block);
394                 }
395
396                 // Decide which sides to traverse next or to block away
397
398                 // First, find the near sides that would occlude the far sides
399                 // * A near side can itself be occluded by a nearby block (the test above ^^)
400                 // * A near side can be visible but fully opaque by itself (e.g. ground at the 0 level)
401
402                 // mesh solid sides are +Z-Z+Y-Y+X-X
403                 // if we are inside the block's coordinates on an axis, 
404                 // treat these sides as opaque, as they should not allow to reach the far sides
405                 u8 block_inner_sides = (look.X == 0 ? 3 : 0) |
406                         (look.Y == 0 ? 12 : 0) |
407                         (look.Z == 0 ? 48 : 0);
408
409                 // get the mask for the sides that are relevant based on the direction
410                 u8 near_inner_sides = (look.X > 0 ? 1 : 2) |
411                                 (look.Y > 0 ? 4 : 8) |
412                                 (look.Z > 0 ? 16 : 32);
413                 
414                 // This bitset is +Z-Z+Y-Y+X-X (See MapBlockMesh), and axis is XYZ.
415                 // Get he block's transparent sides
416                 u8 transparent_sides = (occlusion_culling_enabled && block) ? ~block->solid_sides : 0x3F;
417
418                 // compress block transparent sides to ZYX mask of see-through axes
419                 u8 near_transparency =  (block_inner_sides == 0x3F) ? near_inner_sides : (transparent_sides & near_inner_sides);
420
421                 // when we are inside the camera block, do not block any sides
422                 if (block_inner_sides == 0x3F)
423                         block_inner_sides = 0;
424
425                 near_transparency &= ~block_inner_sides & 0x3F;
426
427                 near_transparency |= (near_transparency >> 1);
428                 near_transparency = (near_transparency & 1) |
429                                 ((near_transparency >> 1) & 2) |
430                                 ((near_transparency >> 2) & 4);
431
432                 // combine with known visible sides that matter
433                 near_transparency &= visible_outer_sides;
434
435                 // The rule for any far side to be visible:
436                 // * Any of the adjacent near sides is transparent (different axes)
437                 // * The opposite near side (same axis) is transparent, if it is the dominant axis of the look vector
438
439                 // Calculate vector from camera to mapblock center. Because we only need relation between
440                 // coordinates we scale by 2 to avoid precision loss.
441                 v3s16 precise_look = 2 * (block_pos_nodes - cam_pos_nodes) + MAP_BLOCKSIZE - 1;
442
443                 // dominant axis flag
444                 u8 dominant_axis = (abs(precise_look.X) > abs(precise_look.Y) && abs(precise_look.X) > abs(precise_look.Z)) |
445                                         ((abs(precise_look.Y) > abs(precise_look.Z) && abs(precise_look.Y) > abs(precise_look.X)) << 1) |
446                                         ((abs(precise_look.Z) > abs(precise_look.X) && abs(precise_look.Z) > abs(precise_look.Y)) << 2);
447
448                 // Queue next blocks for processing:
449                 // - Examine "far" sides of the current blocks, i.e. never move towards the camera
450                 // - Only traverse the sides that are not occluded
451                 // - Only traverse the sides that are not opaque
452                 // When queueing, mark the relevant side on the next block as 'visible'
453                 for (s16 axis = 0; axis < 3; axis++) {
454
455                         // Select a bit from transparent_sides for the side
456                         u8 far_side_mask = 1 << (2 * axis);
457
458                         // axis flag
459                         u8 my_side = 1 << axis;
460                         u8 adjacent_sides = my_side ^ 0x07;
461
462                         auto traverse_far_side = [&](s8 next_pos_offset) {
463                                 // far side is visible if adjacent near sides are transparent, or if opposite side on dominant axis is transparent
464                                 bool side_visible = ((near_transparency & adjacent_sides) | (near_transparency & my_side & dominant_axis)) != 0;
465                                 side_visible = side_visible && ((far_side_mask & transparent_sides) != 0);
466
467                                 v3s16 next_pos = block_coord;
468                                 next_pos[axis] += next_pos_offset;
469
470                                 // If a side is a see-through, mark the next block's side as visible, and queue
471                                 if (side_visible) {
472                                         auto &next_flags = blocks_seen.getChunk(next_pos).getBits(next_pos);
473                                         next_flags |= my_side;
474                                         blocks_to_consider.push(next_pos);
475                                 }
476                                 else {
477                                         sides_skipped++;
478                                 }
479                         };
480
481
482                         // Test the '-' direction of the axis
483                         if (look[axis] <= 0 && block_coord[axis] > p_blocks_min[axis])
484                                 traverse_far_side(-1);
485
486                         // Test the '+' direction of the axis
487                         far_side_mask <<= 1;
488
489                         if (look[axis] >= 0 && block_coord[axis] < p_blocks_max[axis])
490                                 traverse_far_side(+1);
491                 }
492         }
493
494         g_profiler->avg("MapBlocks shortlist [#]", shortlist.size());
495
496         assert(m_drawlist.empty() || shortlist.empty());
497         for (auto pos : shortlist) {
498                 MapBlock * block = getBlockNoCreateNoEx(pos);
499                 if (block) {
500                         block->refGrab();
501                         m_drawlist.emplace(pos, block);
502                 }
503         }
504
505         g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
506         g_profiler->avg("MapBlocks sides skipped [#]", sides_skipped);
507         g_profiler->avg("MapBlocks examined [#]", blocks_visited);
508         g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
509 }
510
511 void ClientMap::touchMapBlocks()
512 {
513         v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
514
515         v3s16 p_blocks_min;
516         v3s16 p_blocks_max;
517         getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
518
519         // Number of blocks currently loaded by the client
520         u32 blocks_loaded = 0;
521         // Number of blocks with mesh in rendering range
522         u32 blocks_in_range_with_mesh = 0;
523
524         for (const auto &sector_it : m_sectors) {
525                 MapSector *sector = sector_it.second;
526                 v2s16 sp = sector->getPos();
527
528                 blocks_loaded += sector->size();
529                 if (!m_control.range_all) {
530                         if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
531                                         sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
532                                 continue;
533                 }
534
535                 MapBlockVect sectorblocks;
536                 sector->getBlocks(sectorblocks);
537
538                 /*
539                         Loop through blocks in sector
540                 */
541
542                 for (MapBlock *block : sectorblocks) {
543                         /*
544                                 Compare block position to camera position, skip
545                                 if not seen on display
546                         */
547
548                         if (!block->mesh) {
549                                 // Ignore if mesh doesn't exist
550                                 continue;
551                         }
552
553                         v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
554                                         + block->mesh->getBoundingSphereCenter();
555                         f32 mesh_sphere_radius = block->mesh->getBoundingRadius();
556                         // First, perform a simple distance check.
557                         if (!m_control.range_all &&
558                                 mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
559                                         m_control.wanted_range * BS + mesh_sphere_radius)
560                                 continue; // Out of range, skip.
561
562                         // Keep the block alive as long as it is in range.
563                         block->resetUsageTimer();
564                         blocks_in_range_with_mesh++;
565                 }
566         }
567         g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
568         g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
569 }
570
571 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
572 {
573         bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
574
575         std::string prefix;
576         if (pass == scene::ESNRP_SOLID)
577                 prefix = "renderMap(SOLID): ";
578         else
579                 prefix = "renderMap(TRANSPARENT): ";
580
581         /*
582                 This is called two times per frame, reset on the non-transparent one
583         */
584         if (pass == scene::ESNRP_SOLID)
585                 m_last_drawn_sectors.clear();
586
587         /*
588                 Get animation parameters
589         */
590         const float animation_time = m_client->getAnimationTime();
591         const int crack = m_client->getCrackLevel();
592         const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
593
594         const v3f camera_position = m_camera_position;
595
596         /*
597                 Get all blocks and draw all visible ones
598         */
599
600         u32 vertex_count = 0;
601         u32 drawcall_count = 0;
602
603         // For limiting number of mesh animations per frame
604         u32 mesh_animate_count = 0;
605         //u32 mesh_animate_count_far = 0;
606
607         /*
608                 Update transparent meshes
609         */
610         if (is_transparent_pass)
611                 updateTransparentMeshBuffers();
612
613         /*
614                 Draw the selected MapBlocks
615         */
616
617         MeshBufListList grouped_buffers;
618         std::vector<DrawDescriptor> draw_order;
619         video::SMaterial previous_material;
620
621         auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
622
623         const MeshGrid mesh_grid = m_client->getMeshGrid();
624         for (auto &i : m_drawlist) {
625                 v3s16 block_pos = i.first;
626                 MapBlock *block = i.second;
627                 MapBlockMesh *block_mesh = block->mesh;
628
629                 // If the mesh of the block happened to get deleted, ignore it
630                 if (!block_mesh)
631                         continue;
632
633                 // Do exact frustum culling
634                 // (The one in updateDrawList is only coarse.)
635                 v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
636                                 + block_mesh->getBoundingSphereCenter();
637                 f32 mesh_sphere_radius = block_mesh->getBoundingRadius();
638                 if (is_frustum_culled(mesh_sphere_center, mesh_sphere_radius))
639                         continue;
640
641                 v3f block_pos_r = intToFloat(block->getPosRelative() + MAP_BLOCKSIZE / 2, BS);
642
643                 float d = camera_position.getDistanceFrom(block_pos_r);
644                 d = MYMAX(0,d - BLOCK_MAX_RADIUS);
645
646                 // Mesh animation
647                 if (pass == scene::ESNRP_SOLID) {
648                         // Pretty random but this should work somewhat nicely
649                         bool faraway = d >= BS * 50;
650                         if (block_mesh->isAnimationForced() || !faraway ||
651                                         mesh_animate_count < (m_control.range_all ? 200 : 50)) {
652
653                                 bool animated = block_mesh->animate(faraway, animation_time,
654                                         crack, daynight_ratio);
655                                 if (animated)
656                                         mesh_animate_count++;
657                         } else {
658                                 block_mesh->decreaseAnimationForceTimer();
659                         }
660                 }
661
662                 /*
663                         Get the meshbuffers of the block
664                 */
665                 if (is_transparent_pass) {
666                         // In transparent pass, the mesh will give us
667                         // the partial buffers in the correct order
668                         for (auto &buffer : block_mesh->getTransparentBuffers())
669                                 draw_order.emplace_back(block_pos, &buffer);
670                 }
671                 else {
672                         // otherwise, group buffers across meshes
673                         // using MeshBufListList
674                         for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
675                                 scene::IMesh *mesh = block_mesh->getMesh(layer);
676                                 assert(mesh);
677
678                                 u32 c = mesh->getMeshBufferCount();
679                                 for (u32 i = 0; i < c; i++) {
680                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
681
682                                         video::SMaterial& material = buf->getMaterial();
683                                         video::IMaterialRenderer* rnd =
684                                                         driver->getMaterialRenderer(material.MaterialType);
685                                         bool transparent = (rnd && rnd->isTransparent());
686                                         if (!transparent) {
687                                                 if (buf->getVertexCount() == 0)
688                                                         errorstream << "Block [" << analyze_block(block)
689                                                                         << "] contains an empty meshbuf" << std::endl;
690
691                                                 grouped_buffers.add(buf, block_pos, layer);
692                                         }
693                                 }
694                         }
695                 }
696         }
697
698         // Capture draw order for all solid meshes
699         for (auto &lists : grouped_buffers.lists) {
700                 for (MeshBufList &list : lists) {
701                         // iterate in reverse to draw closest blocks first
702                         for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it) {
703                                 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
704                         }
705                 }
706         }
707
708         TimeTaker draw("Drawing mesh buffers");
709
710         core::matrix4 m; // Model matrix
711         v3f offset = intToFloat(m_camera_offset, BS);
712         u32 material_swaps = 0;
713
714         // Render all mesh buffers in order
715         drawcall_count += draw_order.size();
716
717         for (auto &descriptor : draw_order) {
718                 scene::IMeshBuffer *buf = descriptor.getBuffer();
719
720                 if (!descriptor.m_reuse_material) {
721                         auto &material = buf->getMaterial();
722
723                         // Apply filter settings
724                         material.setFlag(video::EMF_TRILINEAR_FILTER,
725                                 m_cache_trilinear_filter);
726                         material.setFlag(video::EMF_BILINEAR_FILTER,
727                                 m_cache_bilinear_filter);
728                         material.setFlag(video::EMF_ANISOTROPIC_FILTER,
729                                 m_cache_anistropic_filter);
730                         material.setFlag(video::EMF_WIREFRAME,
731                                 m_control.show_wireframe);
732
733                         // pass the shadow map texture to the buffer texture
734                         ShadowRenderer *shadow = m_rendering_engine->get_shadow_renderer();
735                         if (shadow && shadow->is_active()) {
736                                 auto &layer = material.TextureLayer[ShadowRenderer::TEXTURE_LAYER_SHADOW];
737                                 layer.Texture = shadow->get_texture();
738                                 layer.TextureWrapU = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
739                                 layer.TextureWrapV = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
740                                 // Do not enable filter on shadow texture to avoid visual artifacts
741                                 // with colored shadows.
742                                 // Filtering is done in shader code anyway
743                                 layer.BilinearFilter = false;
744                                 layer.AnisotropicFilter = false;
745                                 layer.TrilinearFilter = false;
746                         }
747                         driver->setMaterial(material);
748                         ++material_swaps;
749                         material.TextureLayer[ShadowRenderer::TEXTURE_LAYER_SHADOW].Texture = nullptr;
750                 }
751
752                 v3f block_wpos = intToFloat(mesh_grid.getMeshPos(descriptor.m_pos) * MAP_BLOCKSIZE, BS);
753                 m.setTranslation(block_wpos - offset);
754
755                 driver->setTransform(video::ETS_WORLD, m);
756                 descriptor.draw(driver);
757                 vertex_count += buf->getIndexCount();
758         }
759
760         g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
761
762         // Log only on solid pass because values are the same
763         if (pass == scene::ESNRP_SOLID) {
764                 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
765         }
766
767         if (pass == scene::ESNRP_TRANSPARENT) {
768                 g_profiler->avg("renderMap(): transparent buffers [#]", draw_order.size());
769         }
770
771         g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
772         g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
773         g_profiler->avg(prefix + "material swaps [#]", material_swaps);
774 }
775
776 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
777         float step_multiplier, float start_distance, float end_distance,
778         const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
779         int *result, bool *sunlight_seen)
780 {
781         int brightness_sum = 0;
782         int brightness_count = 0;
783         float distance = start_distance;
784         dir.normalize();
785         v3f pf = p0;
786         pf += dir * distance;
787         int noncount = 0;
788         bool nonlight_seen = false;
789         bool allow_allowing_non_sunlight_propagates = false;
790         bool allow_non_sunlight_propagates = false;
791         // Check content nearly at camera position
792         {
793                 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
794                 MapNode n = map->getNode(p);
795                 if(ndef->getLightingFlags(n).has_light &&
796                                 !ndef->getLightingFlags(n).sunlight_propagates)
797                         allow_allowing_non_sunlight_propagates = true;
798         }
799         // If would start at CONTENT_IGNORE, start closer
800         {
801                 v3s16 p = floatToInt(pf, BS);
802                 MapNode n = map->getNode(p);
803                 if(n.getContent() == CONTENT_IGNORE){
804                         float newd = 2*BS;
805                         pf = p0 + dir * 2*newd;
806                         distance = newd;
807                         sunlight_min_d = 0;
808                 }
809         }
810         for (int i=0; distance < end_distance; i++) {
811                 pf += dir * step;
812                 distance += step;
813                 step *= step_multiplier;
814
815                 v3s16 p = floatToInt(pf, BS);
816                 MapNode n = map->getNode(p);
817                 ContentLightingFlags f = ndef->getLightingFlags(n);
818                 if (allow_allowing_non_sunlight_propagates && i == 0 &&
819                                 f.has_light && !f.sunlight_propagates) {
820                         allow_non_sunlight_propagates = true;
821                 }
822
823                 if (!f.has_light || (!f.sunlight_propagates && !allow_non_sunlight_propagates)){
824                         nonlight_seen = true;
825                         noncount++;
826                         if(noncount >= 4)
827                                 break;
828                         continue;
829                 }
830
831                 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
832                         if (n.getLight(LIGHTBANK_DAY, f) == LIGHT_SUN)
833                                 *sunlight_seen = true;
834                 noncount = 0;
835                 brightness_sum += decode_light(n.getLightBlend(daylight_factor, f));
836                 brightness_count++;
837         }
838         *result = 0;
839         if(brightness_count == 0)
840                 return false;
841         *result = brightness_sum / brightness_count;
842         /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
843                         <<(*result)<<std::endl;*/
844         return true;
845 }
846
847 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
848                 int oldvalue, bool *sunlight_seen_result)
849 {
850         ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
851         static v3f z_directions[50] = {
852                 v3f(-100, 0, 0)
853         };
854         static f32 z_offsets[50] = {
855                 -1000,
856         };
857
858         if (z_directions[0].X < -99) {
859                 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
860                         // Assumes FOV of 72 and 16/9 aspect ratio
861                         z_directions[i] = v3f(
862                                 0.02 * myrand_range(-100, 100),
863                                 1.0,
864                                 0.01 * myrand_range(-100, 100)
865                         ).normalize();
866                         z_offsets[i] = 0.01 * myrand_range(0,100);
867                 }
868         }
869
870         int sunlight_seen_count = 0;
871         float sunlight_min_d = max_d*0.8;
872         if(sunlight_min_d > 35*BS)
873                 sunlight_min_d = 35*BS;
874         std::vector<int> values;
875         values.reserve(ARRLEN(z_directions));
876         for (u32 i = 0; i < ARRLEN(z_directions); i++) {
877                 v3f z_dir = z_directions[i];
878                 core::CMatrix4<f32> a;
879                 a.buildRotateFromTo(v3f(0,1,0), z_dir);
880                 v3f dir = m_camera_direction;
881                 a.rotateVect(dir);
882                 int br = 0;
883                 float step = BS*1.5;
884                 if(max_d > 35*BS)
885                         step = max_d / 35 * 1.5;
886                 float off = step * z_offsets[i];
887                 bool sunlight_seen_now = false;
888                 bool ok = getVisibleBrightness(this, m_camera_position, dir,
889                                 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
890                                 sunlight_min_d,
891                                 &br, &sunlight_seen_now);
892                 if(sunlight_seen_now)
893                         sunlight_seen_count++;
894                 if(!ok)
895                         continue;
896                 values.push_back(br);
897                 // Don't try too much if being in the sun is clear
898                 if(sunlight_seen_count >= 20)
899                         break;
900         }
901         int brightness_sum = 0;
902         int brightness_count = 0;
903         std::sort(values.begin(), values.end());
904         u32 num_values_to_use = values.size();
905         if(num_values_to_use >= 10)
906                 num_values_to_use -= num_values_to_use/2;
907         else if(num_values_to_use >= 7)
908                 num_values_to_use -= num_values_to_use/3;
909         u32 first_value_i = (values.size() - num_values_to_use) / 2;
910
911         for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
912                 brightness_sum += values[i];
913                 brightness_count++;
914         }
915
916         int ret = 0;
917         if(brightness_count == 0){
918                 MapNode n = getNode(floatToInt(m_camera_position, BS));
919                 ContentLightingFlags f = m_nodedef->getLightingFlags(n);
920                 if(f.has_light){
921                         ret = decode_light(n.getLightBlend(daylight_factor, f));
922                 } else {
923                         ret = oldvalue;
924                 }
925         } else {
926                 ret = brightness_sum / brightness_count;
927         }
928
929         *sunlight_seen_result = (sunlight_seen_count > 0);
930         return ret;
931 }
932
933 void ClientMap::renderPostFx(CameraMode cam_mode)
934 {
935         // Sadly ISceneManager has no "post effects" render pass, in that case we
936         // could just register for that and handle it in renderMap().
937
938         MapNode n = getNode(floatToInt(m_camera_position, BS));
939
940         const ContentFeatures& features = m_nodedef->get(n);
941         video::SColor post_effect_color = features.post_effect_color;
942
943         // If the camera is in a solid node, make everything black.
944         // (first person mode only)
945         if (features.solidness == 2 && cam_mode == CAMERA_MODE_FIRST &&
946                 !m_control.allow_noclip) {
947                 post_effect_color = video::SColor(255, 0, 0, 0);
948         }
949
950         if (post_effect_color.getAlpha() != 0) {
951                 // Draw a full-screen rectangle
952                 video::IVideoDriver* driver = SceneManager->getVideoDriver();
953                 v2u32 ss = driver->getScreenSize();
954                 core::rect<s32> rect(0,0, ss.X, ss.Y);
955                 driver->draw2DRectangle(post_effect_color, rect);
956         }
957 }
958
959 void ClientMap::PrintInfo(std::ostream &out)
960 {
961         out<<"ClientMap: ";
962 }
963
964 void ClientMap::renderMapShadows(video::IVideoDriver *driver,
965                 const video::SMaterial &material, s32 pass, int frame, int total_frames)
966 {
967         bool is_transparent_pass = pass != scene::ESNRP_SOLID;
968         std::string prefix;
969         if (is_transparent_pass)
970                 prefix = "renderMap(SHADOW TRANS): ";
971         else
972                 prefix = "renderMap(SHADOW SOLID): ";
973
974         u32 drawcall_count = 0;
975         u32 vertex_count = 0;
976
977         MeshBufListList grouped_buffers;
978         std::vector<DrawDescriptor> draw_order;
979
980
981         std::size_t count = 0;
982         std::size_t meshes_per_frame = m_drawlist_shadow.size() / total_frames + 1;
983         std::size_t low_bound = is_transparent_pass ? 0 : meshes_per_frame * frame;
984         std::size_t high_bound = is_transparent_pass ? m_drawlist_shadow.size() : meshes_per_frame * (frame + 1);
985
986         // transparent pass should be rendered in one go
987         if (is_transparent_pass && frame != total_frames - 1) {
988                 return;
989         }
990
991         const MeshGrid mesh_grid = m_client->getMeshGrid();
992         for (const auto &i : m_drawlist_shadow) {
993                 // only process specific part of the list & break early
994                 ++count;
995                 if (count <= low_bound)
996                         continue;
997                 if (count > high_bound)
998                         break;
999
1000                 v3s16 block_pos = i.first;
1001                 MapBlock *block = i.second;
1002
1003                 // If the mesh of the block happened to get deleted, ignore it
1004                 if (!block->mesh)
1005                         continue;
1006
1007                 /*
1008                         Get the meshbuffers of the block
1009                 */
1010                 if (is_transparent_pass) {
1011                         // In transparent pass, the mesh will give us
1012                         // the partial buffers in the correct order
1013                         for (auto &buffer : block->mesh->getTransparentBuffers())
1014                                 draw_order.emplace_back(block_pos, &buffer);
1015                 }
1016                 else {
1017                         // otherwise, group buffers across meshes
1018                         // using MeshBufListList
1019                         MapBlockMesh *mapBlockMesh = block->mesh;
1020                         assert(mapBlockMesh);
1021
1022                         for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
1023                                 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
1024                                 assert(mesh);
1025
1026                                 u32 c = mesh->getMeshBufferCount();
1027                                 for (u32 i = 0; i < c; i++) {
1028                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
1029
1030                                         video::SMaterial &mat = buf->getMaterial();
1031                                         auto rnd = driver->getMaterialRenderer(mat.MaterialType);
1032                                         bool transparent = rnd && rnd->isTransparent();
1033                                         if (!transparent)
1034                                                 grouped_buffers.add(buf, block_pos, layer);
1035                                 }
1036                         }
1037                 }
1038         }
1039
1040         u32 buffer_count = 0;
1041         for (auto &lists : grouped_buffers.lists)
1042                 for (MeshBufList &list : lists)
1043                         buffer_count += list.bufs.size();
1044
1045         draw_order.reserve(draw_order.size() + buffer_count);
1046
1047         // Capture draw order for all solid meshes
1048         for (auto &lists : grouped_buffers.lists) {
1049                 for (MeshBufList &list : lists) {
1050                         // iterate in reverse to draw closest blocks first
1051                         for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it)
1052                                 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
1053                 }
1054         }
1055
1056         TimeTaker draw("Drawing shadow mesh buffers");
1057
1058         core::matrix4 m; // Model matrix
1059         v3f offset = intToFloat(m_camera_offset, BS);
1060         u32 material_swaps = 0;
1061
1062         // Render all mesh buffers in order
1063         drawcall_count += draw_order.size();
1064
1065         for (auto &descriptor : draw_order) {
1066                 scene::IMeshBuffer *buf = descriptor.getBuffer();
1067
1068                 if (!descriptor.m_reuse_material) {
1069                         // override some material properties
1070                         video::SMaterial local_material = buf->getMaterial();
1071                         local_material.MaterialType = material.MaterialType;
1072                         local_material.BackfaceCulling = material.BackfaceCulling;
1073                         local_material.FrontfaceCulling = material.FrontfaceCulling;
1074                         local_material.BlendOperation = material.BlendOperation;
1075                         local_material.Lighting = false;
1076                         driver->setMaterial(local_material);
1077                         ++material_swaps;
1078                 }
1079
1080                 v3f block_wpos = intToFloat(mesh_grid.getMeshPos(descriptor.m_pos) * MAP_BLOCKSIZE, BS);
1081                 m.setTranslation(block_wpos - offset);
1082
1083                 driver->setTransform(video::ETS_WORLD, m);
1084                 descriptor.draw(driver);
1085                 vertex_count += buf->getIndexCount();
1086         }
1087
1088         // restore the driver material state
1089         video::SMaterial clean;
1090         clean.BlendOperation = video::EBO_ADD;
1091         driver->setMaterial(clean); // reset material to defaults
1092         driver->draw3DLine(v3f(), v3f(), video::SColor(0));
1093
1094         g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
1095         g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
1096         g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
1097         g_profiler->avg(prefix + "material swaps [#]", material_swaps);
1098 }
1099
1100 /*
1101         Custom update draw list for the pov of shadow light.
1102 */
1103 void ClientMap::updateDrawListShadow(v3f shadow_light_pos, v3f shadow_light_dir, float radius, float length)
1104 {
1105         ScopeProfiler sp(g_profiler, "CM::updateDrawListShadow()", SPT_AVG);
1106
1107         v3s16 cam_pos_nodes = floatToInt(shadow_light_pos, BS);
1108         v3s16 p_blocks_min;
1109         v3s16 p_blocks_max;
1110         getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max, radius + length);
1111
1112         for (auto &i : m_drawlist_shadow) {
1113                 MapBlock *block = i.second;
1114                 block->refDrop();
1115         }
1116         m_drawlist_shadow.clear();
1117
1118         // Number of blocks currently loaded by the client
1119         u32 blocks_loaded = 0;
1120         // Number of blocks with mesh in rendering range
1121         u32 blocks_in_range_with_mesh = 0;
1122         // Number of blocks occlusion culled
1123         u32 blocks_occlusion_culled = 0;
1124
1125         std::set<v3s16> shortlist;
1126         MeshGrid mesh_grid = m_client->getMeshGrid();
1127
1128         for (auto &sector_it : m_sectors) {
1129                 MapSector *sector = sector_it.second;
1130                 if (!sector)
1131                         continue;
1132                 blocks_loaded += sector->size();
1133
1134                 MapBlockVect sectorblocks;
1135                 sector->getBlocks(sectorblocks);
1136
1137                 /*
1138                         Loop through blocks in sector
1139                 */
1140                 for (MapBlock *block : sectorblocks) {
1141                         if (mesh_grid.cell_size == 1 && !block->mesh) {
1142                                 // fast out in the case of no mesh chunking
1143                                 continue;
1144                         }
1145
1146                         v3f block_pos = intToFloat(block->getPos() * MAP_BLOCKSIZE, BS);
1147                         v3f projection = shadow_light_pos + shadow_light_dir * shadow_light_dir.dotProduct(block_pos - shadow_light_pos);
1148                         if (projection.getDistanceFrom(block_pos) > radius)
1149                                 continue;
1150
1151                         if (mesh_grid.cell_size > 1) {
1152                                 // Block meshes are stored in the corner block of a chunk
1153                                 // (where all coordinate are divisible by the chunk size)
1154                                 // Add them to the de-dup set.
1155                                 shortlist.emplace(mesh_grid.getMeshPos(block->getPos()));
1156                         }
1157                         if (!block->mesh) {
1158                                 // Ignore if mesh doesn't exist
1159                                 continue;
1160                         }
1161
1162                         blocks_in_range_with_mesh++;
1163
1164                         // This block is in range. Reset usage timer.
1165                         block->resetUsageTimer();
1166
1167                         // Add to set
1168                         if (m_drawlist_shadow.emplace(block->getPos(), block).second) {
1169                                 block->refGrab();
1170                         }
1171                 }
1172         }
1173         for (auto pos : shortlist) {
1174                 MapBlock * block = getBlockNoCreateNoEx(pos);
1175                 if (block && block->mesh && m_drawlist_shadow.emplace(pos, block).second) {
1176                         block->refGrab();
1177                 }
1178         }
1179
1180         g_profiler->avg("SHADOW MapBlock meshes in range [#]", blocks_in_range_with_mesh);
1181         g_profiler->avg("SHADOW MapBlocks occlusion culled [#]", blocks_occlusion_culled);
1182         g_profiler->avg("SHADOW MapBlocks drawn [#]", m_drawlist_shadow.size());
1183         g_profiler->avg("SHADOW MapBlocks loaded [#]", blocks_loaded);
1184 }
1185
1186 void ClientMap::reportMetrics(u64 save_time_us, u32 saved_blocks, u32 all_blocks)
1187 {
1188         g_profiler->avg("CM::reportMetrics loaded blocks [#]", all_blocks);
1189 }
1190
1191 void ClientMap::updateTransparentMeshBuffers()
1192 {
1193         ScopeProfiler sp(g_profiler, "CM::updateTransparentMeshBuffers", SPT_AVG);
1194         u32 sorted_blocks = 0;
1195         u32 unsorted_blocks = 0;
1196         f32 sorting_distance_sq = pow(m_cache_transparency_sorting_distance * BS, 2.0f);
1197
1198
1199         // Update the order of transparent mesh buffers in each mesh
1200         for (auto it = m_drawlist.begin(); it != m_drawlist.end(); it++) {
1201                 MapBlock* block = it->second;
1202                 if (!block->mesh)
1203                         continue;
1204
1205                 if (m_needs_update_transparent_meshes ||
1206                                 block->mesh->getTransparentBuffers().size() == 0) {
1207
1208                         v3s16 block_pos = block->getPos();
1209                         v3f block_pos_f = intToFloat(block_pos * MAP_BLOCKSIZE + MAP_BLOCKSIZE / 2, BS);
1210                         f32 distance = m_camera_position.getDistanceFromSQ(block_pos_f);
1211                         if (distance <= sorting_distance_sq) {
1212                                 block->mesh->updateTransparentBuffers(m_camera_position, block_pos);
1213                                 ++sorted_blocks;
1214                         }
1215                         else {
1216                                 block->mesh->consolidateTransparentBuffers();
1217                                 ++unsorted_blocks;
1218                         }
1219                 }
1220         }
1221
1222         g_profiler->avg("CM::Transparent Buffers - Sorted", sorted_blocks);
1223         g_profiler->avg("CM::Transparent Buffers - Unsorted", unsorted_blocks);
1224         m_needs_update_transparent_meshes = false;
1225 }
1226
1227 scene::IMeshBuffer* ClientMap::DrawDescriptor::getBuffer()
1228 {
1229         return m_use_partial_buffer ? m_partial_buffer->getBuffer() : m_buffer;
1230 }
1231
1232 void ClientMap::DrawDescriptor::draw(video::IVideoDriver* driver)
1233 {
1234         if (m_use_partial_buffer) {
1235                 m_partial_buffer->beforeDraw();
1236                 driver->drawMeshBuffer(m_partial_buffer->getBuffer());
1237                 m_partial_buffer->afterDraw();
1238         } else {
1239                 driver->drawMeshBuffer(m_buffer);
1240         }
1241 }