3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
20 #include "clientmap.h"
22 #include "mapblock_mesh.h"
23 #include <IMaterialRenderer.h>
25 #include "mapsector.h"
29 #include "camera.h" // CameraModes
30 #include "util/basic_macros.h"
31 #include "client/renderingengine.h"
35 // struct MeshBufListList
36 void MeshBufListList::clear()
38 for (auto &list : lists)
42 void MeshBufListList::add(scene::IMeshBuffer *buf, v3s16 position, u8 layer)
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)
54 l.bufs.emplace_back(position, buf);
60 l.bufs.emplace_back(position, buf);
64 static void on_settings_changed(const std::string &name, void *data)
66 static_cast<ClientMap*>(data)->onSettingChanged(name);
72 RenderingEngine *rendering_engine,
73 MapDrawControl &control,
77 scene::ISceneNode(rendering_engine->get_scene_manager()->getRootSceneNode(),
78 rendering_engine->get_scene_manager(), id),
80 m_rendering_engine(rendering_engine),
82 m_drawlist(MapBlockComparer(v3s16(0,0,0)))
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.
90 m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
91 BS*1000000,BS*1000000,BS*1000000);
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)
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
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);
110 void ClientMap::onSettingChanged(const std::string &name)
112 if (name == "enable_raytraced_culling")
113 m_enable_raytraced_culling = g_settings->getBool("enable_raytraced_culling");
116 ClientMap::~ClientMap()
118 g_settings->deregisterChangedCallback("enable_raytraced_culling", on_settings_changed, this);
121 void ClientMap::updateCamera(v3f pos, v3f dir, f32 fov, v3s16 offset)
123 v3s16 previous_node = floatToInt(m_camera_position, BS) + m_camera_offset;
124 v3s16 previous_block = getContainerPos(previous_node, MAP_BLOCKSIZE);
126 m_camera_position = pos;
127 m_camera_direction = dir;
129 m_camera_offset = offset;
131 v3s16 current_node = floatToInt(m_camera_position, BS) + m_camera_offset;
132 v3s16 current_block = getContainerPos(current_node, MAP_BLOCKSIZE);
134 // reorder the blocks when camera crosses block boundary
135 if (previous_block != current_block)
136 m_needs_update_drawlist = true;
138 // reorder transparent meshes when camera crosses node boundary
139 if (previous_node != current_node)
140 m_needs_update_transparent_meshes = true;
143 MapSector * ClientMap::emergeSector(v2s16 p2d)
145 // Check that it doesn't exist already
146 MapSector *sector = getSectorNoGenerate(p2d);
148 // Create it if it does not exist yet
150 sector = new MapSector(this, p2d, m_gamedef);
151 m_sectors[p2d] = sector;
157 void ClientMap::OnRegisterSceneNode()
161 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
162 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
165 ISceneNode::OnRegisterSceneNode();
166 // It's not needed to register this node to the shadow renderer
167 // we have other way to find it
170 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
171 v3s16 *p_blocks_min, v3s16 *p_blocks_max, float range)
174 range = m_control.wanted_range;
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
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);
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);
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
207 MapBlockFlags(v3s16 min_pos, v3s16 max_pos)
208 : min_pos(min_pos), volume((max_pos - min_pos) / CHUNK_EDGE + 1)
210 chunks.resize(volume.X * volume.Y * volume.Z);
216 inline u8 &getBits(v3s16 pos)
218 std::size_t address = getAddress(pos);
219 return bits[address];
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);
228 std::array<u8, CHUNK_VOLUME> bits;
231 Chunk &getChunk(v3s16 pos)
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();
238 chunks[address].reset(chunk);
243 std::vector<std::unique_ptr<Chunk>> chunks;
248 void ClientMap::updateDrawList()
250 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
252 m_needs_update_drawlist = false;
254 for (auto &i : m_drawlist) {
255 MapBlock *block = i.second;
260 for (auto &block : m_keeplist) {
265 v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
269 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
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;
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;
286 v3s16 camera_block = getContainerPos(cam_pos_nodes, MAP_BLOCKSIZE);
287 m_drawlist = std::map<v3s16, MapBlock*, MapBlockComparer>(MapBlockComparer(camera_block));
289 auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
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;
296 std::queue<v3s16> blocks_to_consider;
299 // [ visited | 0 | 0 | 0 | 0 | Z visible | Y visible | X visible ]
300 MapBlockFlags blocks_seen(p_blocks_min, p_blocks_max);
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
306 std::set<v3s16> shortlist;
308 // Recursively walk the space and pick mapblocks for drawing
309 while (blocks_to_consider.size() > 0) {
311 v3s16 block_coord = blocks_to_consider.front();
312 blocks_to_consider.pop();
314 auto &flags = blocks_seen.getChunk(block_coord).getBits(block_coord);
316 // Only visit each block once (it may have been queued up to three times)
317 if ((flags & 0x80) == 0x80)
323 // Get the sector, block and mesh
324 MapSector *sector = this->getSectorNoGenerate(v2s16(block_coord.X, block_coord.Z));
329 MapBlock *block = sector->getBlockNoCreateNoEx(block_coord.Y);
331 MapBlockMesh *mesh = block ? block->mesh : nullptr;
334 // Calculate the coordinates for range and frutum culling
335 v3f mesh_sphere_center;
336 f32 mesh_sphere_radius;
338 v3s16 block_pos_nodes = block_coord * MAP_BLOCKSIZE;
341 mesh_sphere_center = intToFloat(block_pos_nodes, BS)
342 + mesh->getBoundingSphereCenter();
343 mesh_sphere_radius = mesh->getBoundingRadius();
346 mesh_sphere_center = intToFloat(block_pos_nodes, BS) + v3f((MAP_BLOCKSIZE * 0.5f - 0.5f) * BS);
347 mesh_sphere_radius = 0.0f;
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.
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))
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;
368 // Occluded near sides will further occlude the far sides
369 u8 visible_outer_sides = flags & 0x07;
371 // Raytraced occlusion culling - send rays from the camera to the block's corners
372 if (occlusion_culling_enabled && m_enable_raytraced_culling &&
374 visible_outer_sides != 0x07 && isBlockOccluded(block, cam_pos_nodes)) {
375 blocks_occlusion_culled++;
379 // Block meshes are stored in blocks where all coordinates are even (lowest bit set to 0)
380 // Add them to the de-dup set.
381 shortlist.emplace(block_coord.X & ~1, block_coord.Y & ~1, block_coord.Z & ~1);
382 // All other blocks we can grab and add to the keeplist right away.
384 m_keeplist.push_back(block);
388 // Decide which sides to traverse next or to block away
390 // First, find the near sides that would occlude the far sides
391 // * A near side can itself be occluded by a nearby block (the test above ^^)
392 // * A near side can be visible but fully opaque by itself (e.g. ground at the 0 level)
394 // mesh solid sides are +Z-Z+Y-Y+X-X
395 // if we are inside the block's coordinates on an axis,
396 // treat these sides as opaque, as they should not allow to reach the far sides
397 u8 block_inner_sides = (look.X == 0 ? 3 : 0) |
398 (look.Y == 0 ? 12 : 0) |
399 (look.Z == 0 ? 48 : 0);
401 // get the mask for the sides that are relevant based on the direction
402 u8 near_inner_sides = (look.X > 0 ? 1 : 2) |
403 (look.Y > 0 ? 4 : 8) |
404 (look.Z > 0 ? 16 : 32);
406 // This bitset is +Z-Z+Y-Y+X-X (See MapBlockMesh), and axis is XYZ.
407 // Get he block's transparent sides
408 u8 transparent_sides = (occlusion_culling_enabled && block) ? ~block->solid_sides : 0x3F;
410 // compress block transparent sides to ZYX mask of see-through axes
411 u8 near_transparency = (block_inner_sides == 0x3F) ? near_inner_sides : (transparent_sides & near_inner_sides);
413 // when we are inside the camera block, do not block any sides
414 if (block_inner_sides == 0x3F)
415 block_inner_sides = 0;
417 near_transparency &= ~block_inner_sides & 0x3F;
419 near_transparency |= (near_transparency >> 1);
420 near_transparency = (near_transparency & 1) |
421 ((near_transparency >> 1) & 2) |
422 ((near_transparency >> 2) & 4);
424 // combine with known visible sides that matter
425 near_transparency &= visible_outer_sides;
427 // The rule for any far side to be visible:
428 // * Any of the adjacent near sides is transparent (different axes)
429 // * The opposite near side (same axis) is transparent, if it is the dominant axis of the look vector
431 // Calculate vector from camera to mapblock center. Because we only need relation between
432 // coordinates we scale by 2 to avoid precision loss.
433 v3s16 precise_look = 2 * (block_pos_nodes - cam_pos_nodes) + MAP_BLOCKSIZE - 1;
435 // dominant axis flag
436 u8 dominant_axis = (abs(precise_look.X) > abs(precise_look.Y) && abs(precise_look.X) > abs(precise_look.Z)) |
437 ((abs(precise_look.Y) > abs(precise_look.Z) && abs(precise_look.Y) > abs(precise_look.X)) << 1) |
438 ((abs(precise_look.Z) > abs(precise_look.X) && abs(precise_look.Z) > abs(precise_look.Y)) << 2);
440 // Queue next blocks for processing:
441 // - Examine "far" sides of the current blocks, i.e. never move towards the camera
442 // - Only traverse the sides that are not occluded
443 // - Only traverse the sides that are not opaque
444 // When queueing, mark the relevant side on the next block as 'visible'
445 for (s16 axis = 0; axis < 3; axis++) {
447 // Select a bit from transparent_sides for the side
448 u8 far_side_mask = 1 << (2 * axis);
451 u8 my_side = 1 << axis;
452 u8 adjacent_sides = my_side ^ 0x07;
454 auto traverse_far_side = [&](s8 next_pos_offset) {
455 // far side is visible if adjacent near sides are transparent, or if opposite side on dominant axis is transparent
456 bool side_visible = ((near_transparency & adjacent_sides) | (near_transparency & my_side & dominant_axis)) != 0;
457 side_visible = side_visible && ((far_side_mask & transparent_sides) != 0);
459 v3s16 next_pos = block_coord;
460 next_pos[axis] += next_pos_offset;
462 // If a side is a see-through, mark the next block's side as visible, and queue
464 auto &next_flags = blocks_seen.getChunk(next_pos).getBits(next_pos);
465 next_flags |= my_side;
466 blocks_to_consider.push(next_pos);
474 // Test the '-' direction of the axis
475 if (look[axis] <= 0 && block_coord[axis] > p_blocks_min[axis])
476 traverse_far_side(-1);
478 // Test the '+' direction of the axis
481 if (look[axis] >= 0 && block_coord[axis] < p_blocks_max[axis])
482 traverse_far_side(+1);
486 g_profiler->avg("MapBlocks shortlist [#]", shortlist.size());
488 assert(m_drawlist.empty());
489 for (auto pos : shortlist) {
490 MapBlock * block = getBlockNoCreateNoEx(pos);
493 m_drawlist.emplace(pos, block);
497 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
498 g_profiler->avg("MapBlocks sides skipped [#]", sides_skipped);
499 g_profiler->avg("MapBlocks examined [#]", blocks_visited);
500 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
503 void ClientMap::touchMapBlocks()
505 v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
509 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
511 // Number of blocks currently loaded by the client
512 u32 blocks_loaded = 0;
513 // Number of blocks with mesh in rendering range
514 u32 blocks_in_range_with_mesh = 0;
516 for (const auto §or_it : m_sectors) {
517 MapSector *sector = sector_it.second;
518 v2s16 sp = sector->getPos();
520 blocks_loaded += sector->size();
521 if (!m_control.range_all) {
522 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
523 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
527 MapBlockVect sectorblocks;
528 sector->getBlocks(sectorblocks);
531 Loop through blocks in sector
534 for (MapBlock *block : sectorblocks) {
536 Compare block position to camera position, skip
537 if not seen on display
541 // Ignore if mesh doesn't exist
545 v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
546 + block->mesh->getBoundingSphereCenter();
547 f32 mesh_sphere_radius = block->mesh->getBoundingRadius();
548 // First, perform a simple distance check.
549 if (!m_control.range_all &&
550 mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
551 m_control.wanted_range * BS + mesh_sphere_radius)
552 continue; // Out of range, skip.
554 // Keep the block alive as long as it is in range.
555 block->resetUsageTimer();
556 blocks_in_range_with_mesh++;
559 g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
560 g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
563 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
565 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
568 if (pass == scene::ESNRP_SOLID)
569 prefix = "renderMap(SOLID): ";
571 prefix = "renderMap(TRANSPARENT): ";
574 This is called two times per frame, reset on the non-transparent one
576 if (pass == scene::ESNRP_SOLID)
577 m_last_drawn_sectors.clear();
580 Get animation parameters
582 const float animation_time = m_client->getAnimationTime();
583 const int crack = m_client->getCrackLevel();
584 const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
586 const v3f camera_position = m_camera_position;
589 Get all blocks and draw all visible ones
592 u32 vertex_count = 0;
593 u32 drawcall_count = 0;
595 // For limiting number of mesh animations per frame
596 u32 mesh_animate_count = 0;
597 //u32 mesh_animate_count_far = 0;
600 Update transparent meshes
602 if (is_transparent_pass)
603 updateTransparentMeshBuffers();
606 Draw the selected MapBlocks
609 MeshBufListList grouped_buffers;
610 std::vector<DrawDescriptor> draw_order;
611 video::SMaterial previous_material;
613 auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
615 for (auto &i : m_drawlist) {
616 v3s16 block_pos = i.first;
617 MapBlock *block = i.second;
618 MapBlockMesh *block_mesh = block->mesh;
620 // If the mesh of the block happened to get deleted, ignore it
624 // Do exact frustum culling
625 // (The one in updateDrawList is only coarse.)
626 v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
627 + block_mesh->getBoundingSphereCenter();
628 f32 mesh_sphere_radius = block_mesh->getBoundingRadius();
629 if (is_frustum_culled(mesh_sphere_center, mesh_sphere_radius))
632 v3f block_pos_r = intToFloat(block->getPosRelative() + MAP_BLOCKSIZE / 2, BS);
634 float d = camera_position.getDistanceFrom(block_pos_r);
635 d = MYMAX(0,d - BLOCK_MAX_RADIUS);
638 if (pass == scene::ESNRP_SOLID) {
639 // Pretty random but this should work somewhat nicely
640 bool faraway = d >= BS * 50;
641 if (block_mesh->isAnimationForced() || !faraway ||
642 mesh_animate_count < (m_control.range_all ? 200 : 50)) {
644 bool animated = block_mesh->animate(faraway, animation_time,
645 crack, daynight_ratio);
647 mesh_animate_count++;
649 block_mesh->decreaseAnimationForceTimer();
654 Get the meshbuffers of the block
656 if (is_transparent_pass) {
657 // In transparent pass, the mesh will give us
658 // the partial buffers in the correct order
659 for (auto &buffer : block_mesh->getTransparentBuffers())
660 draw_order.emplace_back(block_pos, &buffer);
663 // otherwise, group buffers across meshes
664 // using MeshBufListList
665 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
666 scene::IMesh *mesh = block_mesh->getMesh(layer);
669 u32 c = mesh->getMeshBufferCount();
670 for (u32 i = 0; i < c; i++) {
671 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
673 video::SMaterial& material = buf->getMaterial();
674 video::IMaterialRenderer* rnd =
675 driver->getMaterialRenderer(material.MaterialType);
676 bool transparent = (rnd && rnd->isTransparent());
678 if (buf->getVertexCount() == 0)
679 errorstream << "Block [" << analyze_block(block)
680 << "] contains an empty meshbuf" << std::endl;
682 grouped_buffers.add(buf, block_pos, layer);
689 // Capture draw order for all solid meshes
690 for (auto &lists : grouped_buffers.lists) {
691 for (MeshBufList &list : lists) {
692 // iterate in reverse to draw closest blocks first
693 for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it) {
694 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
699 TimeTaker draw("Drawing mesh buffers");
701 core::matrix4 m; // Model matrix
702 v3f offset = intToFloat(m_camera_offset, BS);
703 u32 material_swaps = 0;
705 // Render all mesh buffers in order
706 drawcall_count += draw_order.size();
708 for (auto &descriptor : draw_order) {
709 scene::IMeshBuffer *buf = descriptor.getBuffer();
711 if (!descriptor.m_reuse_material) {
712 auto &material = buf->getMaterial();
714 // Apply filter settings
715 material.setFlag(video::EMF_TRILINEAR_FILTER,
716 m_cache_trilinear_filter);
717 material.setFlag(video::EMF_BILINEAR_FILTER,
718 m_cache_bilinear_filter);
719 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
720 m_cache_anistropic_filter);
721 material.setFlag(video::EMF_WIREFRAME,
722 m_control.show_wireframe);
724 // pass the shadow map texture to the buffer texture
725 ShadowRenderer *shadow = m_rendering_engine->get_shadow_renderer();
726 if (shadow && shadow->is_active()) {
727 auto &layer = material.TextureLayer[ShadowRenderer::TEXTURE_LAYER_SHADOW];
728 layer.Texture = shadow->get_texture();
729 layer.TextureWrapU = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
730 layer.TextureWrapV = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
731 // Do not enable filter on shadow texture to avoid visual artifacts
732 // with colored shadows.
733 // Filtering is done in shader code anyway
734 layer.BilinearFilter = false;
735 layer.AnisotropicFilter = false;
736 layer.TrilinearFilter = false;
738 driver->setMaterial(material);
740 material.TextureLayer[ShadowRenderer::TEXTURE_LAYER_SHADOW].Texture = nullptr;
743 v3f block_wpos = intToFloat(descriptor.m_pos / 8 * 8 * MAP_BLOCKSIZE, BS);
744 m.setTranslation(block_wpos - offset);
746 driver->setTransform(video::ETS_WORLD, m);
747 descriptor.draw(driver);
748 vertex_count += buf->getIndexCount();
751 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
753 // Log only on solid pass because values are the same
754 if (pass == scene::ESNRP_SOLID) {
755 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
758 if (pass == scene::ESNRP_TRANSPARENT) {
759 g_profiler->avg("renderMap(): transparent buffers [#]", draw_order.size());
762 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
763 g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
764 g_profiler->avg(prefix + "material swaps [#]", material_swaps);
767 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
768 float step_multiplier, float start_distance, float end_distance,
769 const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
770 int *result, bool *sunlight_seen)
772 int brightness_sum = 0;
773 int brightness_count = 0;
774 float distance = start_distance;
777 pf += dir * distance;
779 bool nonlight_seen = false;
780 bool allow_allowing_non_sunlight_propagates = false;
781 bool allow_non_sunlight_propagates = false;
782 // Check content nearly at camera position
784 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
785 MapNode n = map->getNode(p);
786 if(ndef->getLightingFlags(n).has_light &&
787 !ndef->getLightingFlags(n).sunlight_propagates)
788 allow_allowing_non_sunlight_propagates = true;
790 // If would start at CONTENT_IGNORE, start closer
792 v3s16 p = floatToInt(pf, BS);
793 MapNode n = map->getNode(p);
794 if(n.getContent() == CONTENT_IGNORE){
796 pf = p0 + dir * 2*newd;
801 for (int i=0; distance < end_distance; i++) {
804 step *= step_multiplier;
806 v3s16 p = floatToInt(pf, BS);
807 MapNode n = map->getNode(p);
808 ContentLightingFlags f = ndef->getLightingFlags(n);
809 if (allow_allowing_non_sunlight_propagates && i == 0 &&
810 f.has_light && !f.sunlight_propagates) {
811 allow_non_sunlight_propagates = true;
814 if (!f.has_light || (!f.sunlight_propagates && !allow_non_sunlight_propagates)){
815 nonlight_seen = true;
822 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
823 if (n.getLight(LIGHTBANK_DAY, f) == LIGHT_SUN)
824 *sunlight_seen = true;
826 brightness_sum += decode_light(n.getLightBlend(daylight_factor, f));
830 if(brightness_count == 0)
832 *result = brightness_sum / brightness_count;
833 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
834 <<(*result)<<std::endl;*/
838 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
839 int oldvalue, bool *sunlight_seen_result)
841 ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
842 static v3f z_directions[50] = {
845 static f32 z_offsets[50] = {
849 if (z_directions[0].X < -99) {
850 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
851 // Assumes FOV of 72 and 16/9 aspect ratio
852 z_directions[i] = v3f(
853 0.02 * myrand_range(-100, 100),
855 0.01 * myrand_range(-100, 100)
857 z_offsets[i] = 0.01 * myrand_range(0,100);
861 int sunlight_seen_count = 0;
862 float sunlight_min_d = max_d*0.8;
863 if(sunlight_min_d > 35*BS)
864 sunlight_min_d = 35*BS;
865 std::vector<int> values;
866 values.reserve(ARRLEN(z_directions));
867 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
868 v3f z_dir = z_directions[i];
869 core::CMatrix4<f32> a;
870 a.buildRotateFromTo(v3f(0,1,0), z_dir);
871 v3f dir = m_camera_direction;
876 step = max_d / 35 * 1.5;
877 float off = step * z_offsets[i];
878 bool sunlight_seen_now = false;
879 bool ok = getVisibleBrightness(this, m_camera_position, dir,
880 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
882 &br, &sunlight_seen_now);
883 if(sunlight_seen_now)
884 sunlight_seen_count++;
887 values.push_back(br);
888 // Don't try too much if being in the sun is clear
889 if(sunlight_seen_count >= 20)
892 int brightness_sum = 0;
893 int brightness_count = 0;
894 std::sort(values.begin(), values.end());
895 u32 num_values_to_use = values.size();
896 if(num_values_to_use >= 10)
897 num_values_to_use -= num_values_to_use/2;
898 else if(num_values_to_use >= 7)
899 num_values_to_use -= num_values_to_use/3;
900 u32 first_value_i = (values.size() - num_values_to_use) / 2;
902 for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
903 brightness_sum += values[i];
908 if(brightness_count == 0){
909 MapNode n = getNode(floatToInt(m_camera_position, BS));
910 ContentLightingFlags f = m_nodedef->getLightingFlags(n);
912 ret = decode_light(n.getLightBlend(daylight_factor, f));
917 ret = brightness_sum / brightness_count;
920 *sunlight_seen_result = (sunlight_seen_count > 0);
924 void ClientMap::renderPostFx(CameraMode cam_mode)
926 // Sadly ISceneManager has no "post effects" render pass, in that case we
927 // could just register for that and handle it in renderMap().
929 MapNode n = getNode(floatToInt(m_camera_position, BS));
931 const ContentFeatures& features = m_nodedef->get(n);
932 video::SColor post_effect_color = features.post_effect_color;
934 // If the camera is in a solid node, make everything black.
935 // (first person mode only)
936 if (features.solidness == 2 && cam_mode == CAMERA_MODE_FIRST &&
937 !m_control.allow_noclip) {
938 post_effect_color = video::SColor(255, 0, 0, 0);
941 if (post_effect_color.getAlpha() != 0) {
942 // Draw a full-screen rectangle
943 video::IVideoDriver* driver = SceneManager->getVideoDriver();
944 v2u32 ss = driver->getScreenSize();
945 core::rect<s32> rect(0,0, ss.X, ss.Y);
946 driver->draw2DRectangle(post_effect_color, rect);
950 void ClientMap::PrintInfo(std::ostream &out)
955 void ClientMap::renderMapShadows(video::IVideoDriver *driver,
956 const video::SMaterial &material, s32 pass, int frame, int total_frames)
958 bool is_transparent_pass = pass != scene::ESNRP_SOLID;
960 if (is_transparent_pass)
961 prefix = "renderMap(SHADOW TRANS): ";
963 prefix = "renderMap(SHADOW SOLID): ";
965 u32 drawcall_count = 0;
966 u32 vertex_count = 0;
968 MeshBufListList grouped_buffers;
969 std::vector<DrawDescriptor> draw_order;
973 int low_bound = is_transparent_pass ? 0 : m_drawlist_shadow.size() / total_frames * frame;
974 int high_bound = is_transparent_pass ? m_drawlist_shadow.size() : m_drawlist_shadow.size() / total_frames * (frame + 1);
976 // transparent pass should be rendered in one go
977 if (is_transparent_pass && frame != total_frames - 1) {
981 for (const auto &i : m_drawlist_shadow) {
982 // only process specific part of the list & break early
984 if (count <= low_bound)
986 if (count > high_bound)
989 v3s16 block_pos = i.first;
990 MapBlock *block = i.second;
992 // If the mesh of the block happened to get deleted, ignore it
997 Get the meshbuffers of the block
999 if (is_transparent_pass) {
1000 // In transparent pass, the mesh will give us
1001 // the partial buffers in the correct order
1002 for (auto &buffer : block->mesh->getTransparentBuffers())
1003 draw_order.emplace_back(block_pos, &buffer);
1006 // otherwise, group buffers across meshes
1007 // using MeshBufListList
1008 MapBlockMesh *mapBlockMesh = block->mesh;
1009 assert(mapBlockMesh);
1011 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
1012 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
1015 u32 c = mesh->getMeshBufferCount();
1016 for (u32 i = 0; i < c; i++) {
1017 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
1019 video::SMaterial &mat = buf->getMaterial();
1020 auto rnd = driver->getMaterialRenderer(mat.MaterialType);
1021 bool transparent = rnd && rnd->isTransparent();
1023 grouped_buffers.add(buf, block_pos, layer);
1029 u32 buffer_count = 0;
1030 for (auto &lists : grouped_buffers.lists)
1031 for (MeshBufList &list : lists)
1032 buffer_count += list.bufs.size();
1034 draw_order.reserve(draw_order.size() + buffer_count);
1036 // Capture draw order for all solid meshes
1037 for (auto &lists : grouped_buffers.lists) {
1038 for (MeshBufList &list : lists) {
1039 // iterate in reverse to draw closest blocks first
1040 for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it)
1041 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
1045 TimeTaker draw("Drawing shadow mesh buffers");
1047 core::matrix4 m; // Model matrix
1048 v3f offset = intToFloat(m_camera_offset, BS);
1049 u32 material_swaps = 0;
1051 // Render all mesh buffers in order
1052 drawcall_count += draw_order.size();
1054 for (auto &descriptor : draw_order) {
1055 scene::IMeshBuffer *buf = descriptor.getBuffer();
1057 if (!descriptor.m_reuse_material) {
1058 // override some material properties
1059 video::SMaterial local_material = buf->getMaterial();
1060 local_material.MaterialType = material.MaterialType;
1061 local_material.BackfaceCulling = material.BackfaceCulling;
1062 local_material.FrontfaceCulling = material.FrontfaceCulling;
1063 local_material.BlendOperation = material.BlendOperation;
1064 local_material.Lighting = false;
1065 driver->setMaterial(local_material);
1069 v3f block_wpos = intToFloat(descriptor.m_pos / 8 * 8 * MAP_BLOCKSIZE, BS);
1070 m.setTranslation(block_wpos - offset);
1072 driver->setTransform(video::ETS_WORLD, m);
1073 descriptor.draw(driver);
1074 vertex_count += buf->getIndexCount();
1077 // restore the driver material state
1078 video::SMaterial clean;
1079 clean.BlendOperation = video::EBO_ADD;
1080 driver->setMaterial(clean); // reset material to defaults
1081 driver->draw3DLine(v3f(), v3f(), video::SColor(0));
1083 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
1084 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
1085 g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
1086 g_profiler->avg(prefix + "material swaps [#]", material_swaps);
1090 Custom update draw list for the pov of shadow light.
1092 void ClientMap::updateDrawListShadow(v3f shadow_light_pos, v3f shadow_light_dir, float radius, float length)
1094 ScopeProfiler sp(g_profiler, "CM::updateDrawListShadow()", SPT_AVG);
1096 v3s16 cam_pos_nodes = floatToInt(shadow_light_pos, BS);
1099 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max, radius + length);
1101 for (auto &i : m_drawlist_shadow) {
1102 MapBlock *block = i.second;
1105 m_drawlist_shadow.clear();
1107 // Number of blocks currently loaded by the client
1108 u32 blocks_loaded = 0;
1109 // Number of blocks with mesh in rendering range
1110 u32 blocks_in_range_with_mesh = 0;
1111 // Number of blocks occlusion culled
1112 u32 blocks_occlusion_culled = 0;
1114 for (auto §or_it : m_sectors) {
1115 MapSector *sector = sector_it.second;
1118 blocks_loaded += sector->size();
1120 MapBlockVect sectorblocks;
1121 sector->getBlocks(sectorblocks);
1124 Loop through blocks in sector
1126 for (MapBlock *block : sectorblocks) {
1128 // Ignore if mesh doesn't exist
1132 v3f block_pos = intToFloat(block->getPos() * MAP_BLOCKSIZE, BS);
1133 v3f projection = shadow_light_pos + shadow_light_dir * shadow_light_dir.dotProduct(block_pos - shadow_light_pos);
1134 if (projection.getDistanceFrom(block_pos) > radius)
1137 blocks_in_range_with_mesh++;
1139 // This block is in range. Reset usage timer.
1140 block->resetUsageTimer();
1143 if (m_drawlist_shadow.emplace(block->getPos(), block).second) {
1149 g_profiler->avg("SHADOW MapBlock meshes in range [#]", blocks_in_range_with_mesh);
1150 g_profiler->avg("SHADOW MapBlocks occlusion culled [#]", blocks_occlusion_culled);
1151 g_profiler->avg("SHADOW MapBlocks drawn [#]", m_drawlist_shadow.size());
1152 g_profiler->avg("SHADOW MapBlocks loaded [#]", blocks_loaded);
1155 void ClientMap::reportMetrics(u64 save_time_us, u32 saved_blocks, u32 all_blocks)
1157 g_profiler->avg("CM::reportMetrics loaded blocks [#]", all_blocks);
1160 void ClientMap::updateTransparentMeshBuffers()
1162 ScopeProfiler sp(g_profiler, "CM::updateTransparentMeshBuffers", SPT_AVG);
1163 u32 sorted_blocks = 0;
1164 u32 unsorted_blocks = 0;
1165 f32 sorting_distance_sq = pow(m_cache_transparency_sorting_distance * BS, 2.0f);
1168 // Update the order of transparent mesh buffers in each mesh
1169 for (auto it = m_drawlist.begin(); it != m_drawlist.end(); it++) {
1170 MapBlock* block = it->second;
1174 if (m_needs_update_transparent_meshes ||
1175 block->mesh->getTransparentBuffers().size() == 0) {
1177 v3s16 block_pos = block->getPos();
1178 v3f block_pos_f = intToFloat(block_pos * MAP_BLOCKSIZE + MAP_BLOCKSIZE / 2, BS);
1179 f32 distance = m_camera_position.getDistanceFromSQ(block_pos_f);
1180 if (distance <= sorting_distance_sq) {
1181 block->mesh->updateTransparentBuffers(m_camera_position, block_pos);
1185 block->mesh->consolidateTransparentBuffers();
1191 g_profiler->avg("CM::Transparent Buffers - Sorted", sorted_blocks);
1192 g_profiler->avg("CM::Transparent Buffers - Unsorted", unsorted_blocks);
1193 m_needs_update_transparent_meshes = false;
1196 scene::IMeshBuffer* ClientMap::DrawDescriptor::getBuffer()
1198 return m_use_partial_buffer ? m_partial_buffer->getBuffer() : m_buffer;
1201 void ClientMap::DrawDescriptor::draw(video::IVideoDriver* driver)
1203 if (m_use_partial_buffer) {
1204 m_partial_buffer->beforeDraw();
1205 driver->drawMeshBuffer(m_partial_buffer->getBuffer());
1206 m_partial_buffer->afterDraw();
1208 driver->drawMeshBuffer(m_buffer);