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 v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
264 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
266 // Number of blocks occlusion culled
267 u32 blocks_occlusion_culled = 0;
268 // Blocks visited by the algorithm
269 u32 blocks_visited = 0;
270 // Block sides that were not traversed
271 u32 sides_skipped = 0;
273 // No occlusion culling when free_move is on and camera is inside ground
274 bool occlusion_culling_enabled = true;
275 if (m_control.allow_noclip) {
276 MapNode n = getNode(cam_pos_nodes);
277 if (n.getContent() == CONTENT_IGNORE || m_nodedef->get(n).solidness == 2)
278 occlusion_culling_enabled = false;
281 v3s16 camera_block = getContainerPos(cam_pos_nodes, MAP_BLOCKSIZE);
282 m_drawlist = std::map<v3s16, MapBlock*, MapBlockComparer>(MapBlockComparer(camera_block));
284 auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
286 // Uncomment to debug occluded blocks in the wireframe mode
287 // TODO: Include this as a flag for an extended debugging setting
288 // if (occlusion_culling_enabled && m_control.show_wireframe)
289 // occlusion_culling_enabled = porting::getTimeS() & 1;
291 std::queue<v3s16> blocks_to_consider;
294 // [ visited | 0 | 0 | 0 | 0 | Z visible | Y visible | X visible ]
295 MapBlockFlags blocks_seen(p_blocks_min, p_blocks_max);
297 // Start breadth-first search with the block the camera is in
298 blocks_to_consider.push(camera_block);
299 blocks_seen.getChunk(camera_block).getBits(camera_block) = 0x07; // mark all sides as visible
301 // Recursively walk the space and pick mapblocks for drawing
302 while (blocks_to_consider.size() > 0) {
304 v3s16 block_coord = blocks_to_consider.front();
305 blocks_to_consider.pop();
307 auto &flags = blocks_seen.getChunk(block_coord).getBits(block_coord);
309 // Only visit each block once (it may have been queued up to three times)
310 if ((flags & 0x80) == 0x80)
316 // Get the sector, block and mesh
317 MapSector *sector = this->getSectorNoGenerate(v2s16(block_coord.X, block_coord.Z));
322 MapBlock *block = sector->getBlockNoCreateNoEx(block_coord.Y);
324 MapBlockMesh *mesh = block ? block->mesh : nullptr;
327 // Calculate the coordinates for range and frutum culling
328 v3f mesh_sphere_center;
329 f32 mesh_sphere_radius;
331 v3s16 block_pos_nodes = block_coord * MAP_BLOCKSIZE;
334 mesh_sphere_center = intToFloat(block_pos_nodes, BS)
335 + mesh->getBoundingSphereCenter();
336 mesh_sphere_radius = mesh->getBoundingRadius();
339 mesh_sphere_center = intToFloat(block_pos_nodes, BS) + v3f((MAP_BLOCKSIZE * 0.5f - 0.5f) * BS);
340 mesh_sphere_radius = 0.0f;
343 // First, perform a simple distance check.
344 if (!m_control.range_all &&
345 mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
346 m_control.wanted_range * BS + mesh_sphere_radius)
347 continue; // Out of range, skip.
350 // Only do coarse culling here, to account for fast camera movement.
351 // This is needed because this function is not called every frame.
352 float frustum_cull_extra_radius = 300.0f;
353 if (is_frustum_culled(mesh_sphere_center,
354 mesh_sphere_radius + frustum_cull_extra_radius))
357 // Calculate the vector from the camera block to the current block
358 // We use it to determine through which sides of the current block we can continue the search
359 v3s16 look = block_coord - camera_block;
361 // Occluded near sides will further occlude the far sides
362 u8 visible_outer_sides = flags & 0x07;
364 // Raytraced occlusion culling - send rays from the camera to the block's corners
365 if (occlusion_culling_enabled && m_enable_raytraced_culling &&
367 visible_outer_sides != 0x07 && isBlockOccluded(block, cam_pos_nodes)) {
368 blocks_occlusion_culled++;
372 // The block is visible, add to the draw list
376 m_drawlist[block_coord] = block;
379 // Decide which sides to traverse next or to block away
381 // First, find the near sides that would occlude the far sides
382 // * A near side can itself be occluded by a nearby block (the test above ^^)
383 // * A near side can be visible but fully opaque by itself (e.g. ground at the 0 level)
385 // mesh solid sides are +Z-Z+Y-Y+X-X
386 // if we are inside the block's coordinates on an axis,
387 // treat these sides as opaque, as they should not allow to reach the far sides
388 u8 block_inner_sides = (look.X == 0 ? 3 : 0) |
389 (look.Y == 0 ? 12 : 0) |
390 (look.Z == 0 ? 48 : 0);
392 // get the mask for the sides that are relevant based on the direction
393 u8 near_inner_sides = (look.X > 0 ? 1 : 2) |
394 (look.Y > 0 ? 4 : 8) |
395 (look.Z > 0 ? 16 : 32);
397 // This bitset is +Z-Z+Y-Y+X-X (See MapBlockMesh), and axis is XYZ.
398 // Get he block's transparent sides
399 u8 transparent_sides = (occlusion_culling_enabled && block) ? ~block->solid_sides : 0x3F;
401 // compress block transparent sides to ZYX mask of see-through axes
402 u8 near_transparency = (block_inner_sides == 0x3F) ? near_inner_sides : (transparent_sides & near_inner_sides);
404 // when we are inside the camera block, do not block any sides
405 if (block_inner_sides == 0x3F)
406 block_inner_sides = 0;
408 near_transparency &= ~block_inner_sides & 0x3F;
410 near_transparency |= (near_transparency >> 1);
411 near_transparency = (near_transparency & 1) |
412 ((near_transparency >> 1) & 2) |
413 ((near_transparency >> 2) & 4);
415 // combine with known visible sides that matter
416 near_transparency &= visible_outer_sides;
418 // The rule for any far side to be visible:
419 // * Any of the adjacent near sides is transparent (different axes)
420 // * The opposite near side (same axis) is transparent, if it is the dominant axis of the look vector
422 // Calculate vector from camera to mapblock center. Because we only need relation between
423 // coordinates we scale by 2 to avoid precision loss.
424 v3s16 precise_look = 2 * (block_pos_nodes - cam_pos_nodes) + MAP_BLOCKSIZE - 1;
426 // dominant axis flag
427 u8 dominant_axis = (abs(precise_look.X) > abs(precise_look.Y) && abs(precise_look.X) > abs(precise_look.Z)) |
428 ((abs(precise_look.Y) > abs(precise_look.Z) && abs(precise_look.Y) > abs(precise_look.X)) << 1) |
429 ((abs(precise_look.Z) > abs(precise_look.X) && abs(precise_look.Z) > abs(precise_look.Y)) << 2);
431 // Queue next blocks for processing:
432 // - Examine "far" sides of the current blocks, i.e. never move towards the camera
433 // - Only traverse the sides that are not occluded
434 // - Only traverse the sides that are not opaque
435 // When queueing, mark the relevant side on the next block as 'visible'
436 for (s16 axis = 0; axis < 3; axis++) {
438 // Select a bit from transparent_sides for the side
439 u8 far_side_mask = 1 << (2 * axis);
442 u8 my_side = 1 << axis;
443 u8 adjacent_sides = my_side ^ 0x07;
445 auto traverse_far_side = [&](s8 next_pos_offset) {
446 // far side is visible if adjacent near sides are transparent, or if opposite side on dominant axis is transparent
447 bool side_visible = ((near_transparency & adjacent_sides) | (near_transparency & my_side & dominant_axis)) != 0;
448 side_visible = side_visible && ((far_side_mask & transparent_sides) != 0);
450 v3s16 next_pos = block_coord;
451 next_pos[axis] += next_pos_offset;
453 // If a side is a see-through, mark the next block's side as visible, and queue
455 auto &next_flags = blocks_seen.getChunk(next_pos).getBits(next_pos);
456 next_flags |= my_side;
457 blocks_to_consider.push(next_pos);
465 // Test the '-' direction of the axis
466 if (look[axis] <= 0 && block_coord[axis] > p_blocks_min[axis])
467 traverse_far_side(-1);
469 // Test the '+' direction of the axis
472 if (look[axis] >= 0 && block_coord[axis] < p_blocks_max[axis])
473 traverse_far_side(+1);
477 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
478 g_profiler->avg("MapBlocks sides skipped [#]", sides_skipped);
479 g_profiler->avg("MapBlocks examined [#]", blocks_visited);
480 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
483 void ClientMap::touchMapBlocks()
485 v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
489 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
491 // Number of blocks currently loaded by the client
492 u32 blocks_loaded = 0;
493 // Number of blocks with mesh in rendering range
494 u32 blocks_in_range_with_mesh = 0;
496 for (const auto §or_it : m_sectors) {
497 MapSector *sector = sector_it.second;
498 v2s16 sp = sector->getPos();
500 blocks_loaded += sector->size();
501 if (!m_control.range_all) {
502 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
503 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
507 MapBlockVect sectorblocks;
508 sector->getBlocks(sectorblocks);
511 Loop through blocks in sector
514 for (MapBlock *block : sectorblocks) {
516 Compare block position to camera position, skip
517 if not seen on display
521 // Ignore if mesh doesn't exist
525 v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
526 + block->mesh->getBoundingSphereCenter();
527 f32 mesh_sphere_radius = block->mesh->getBoundingRadius();
528 // First, perform a simple distance check.
529 if (!m_control.range_all &&
530 mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
531 m_control.wanted_range * BS + mesh_sphere_radius)
532 continue; // Out of range, skip.
534 // Keep the block alive as long as it is in range.
535 block->resetUsageTimer();
536 blocks_in_range_with_mesh++;
539 g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
540 g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
543 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
545 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
548 if (pass == scene::ESNRP_SOLID)
549 prefix = "renderMap(SOLID): ";
551 prefix = "renderMap(TRANSPARENT): ";
554 This is called two times per frame, reset on the non-transparent one
556 if (pass == scene::ESNRP_SOLID)
557 m_last_drawn_sectors.clear();
560 Get animation parameters
562 const float animation_time = m_client->getAnimationTime();
563 const int crack = m_client->getCrackLevel();
564 const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
566 const v3f camera_position = m_camera_position;
569 Get all blocks and draw all visible ones
572 u32 vertex_count = 0;
573 u32 drawcall_count = 0;
575 // For limiting number of mesh animations per frame
576 u32 mesh_animate_count = 0;
577 //u32 mesh_animate_count_far = 0;
580 Update transparent meshes
582 if (is_transparent_pass)
583 updateTransparentMeshBuffers();
586 Draw the selected MapBlocks
589 MeshBufListList grouped_buffers;
590 std::vector<DrawDescriptor> draw_order;
591 video::SMaterial previous_material;
593 auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
595 for (auto &i : m_drawlist) {
596 v3s16 block_pos = i.first;
597 MapBlock *block = i.second;
598 MapBlockMesh *block_mesh = block->mesh;
600 // If the mesh of the block happened to get deleted, ignore it
604 // Do exact frustum culling
605 // (The one in updateDrawList is only coarse.)
606 v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
607 + block_mesh->getBoundingSphereCenter();
608 f32 mesh_sphere_radius = block_mesh->getBoundingRadius();
609 if (is_frustum_culled(mesh_sphere_center, mesh_sphere_radius))
612 v3f block_pos_r = intToFloat(block->getPosRelative() + MAP_BLOCKSIZE / 2, BS);
614 float d = camera_position.getDistanceFrom(block_pos_r);
615 d = MYMAX(0,d - BLOCK_MAX_RADIUS);
618 if (pass == scene::ESNRP_SOLID) {
619 // Pretty random but this should work somewhat nicely
620 bool faraway = d >= BS * 50;
621 if (block_mesh->isAnimationForced() || !faraway ||
622 mesh_animate_count < (m_control.range_all ? 200 : 50)) {
624 bool animated = block_mesh->animate(faraway, animation_time,
625 crack, daynight_ratio);
627 mesh_animate_count++;
629 block_mesh->decreaseAnimationForceTimer();
634 Get the meshbuffers of the block
636 if (is_transparent_pass) {
637 // In transparent pass, the mesh will give us
638 // the partial buffers in the correct order
639 for (auto &buffer : block_mesh->getTransparentBuffers())
640 draw_order.emplace_back(block_pos, &buffer);
643 // otherwise, group buffers across meshes
644 // using MeshBufListList
645 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
646 scene::IMesh *mesh = block_mesh->getMesh(layer);
649 u32 c = mesh->getMeshBufferCount();
650 for (u32 i = 0; i < c; i++) {
651 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
653 video::SMaterial& material = buf->getMaterial();
654 video::IMaterialRenderer* rnd =
655 driver->getMaterialRenderer(material.MaterialType);
656 bool transparent = (rnd && rnd->isTransparent());
658 if (buf->getVertexCount() == 0)
659 errorstream << "Block [" << analyze_block(block)
660 << "] contains an empty meshbuf" << std::endl;
662 grouped_buffers.add(buf, block_pos, layer);
669 // Capture draw order for all solid meshes
670 for (auto &lists : grouped_buffers.lists) {
671 for (MeshBufList &list : lists) {
672 // iterate in reverse to draw closest blocks first
673 for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it) {
674 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
679 TimeTaker draw("Drawing mesh buffers");
681 core::matrix4 m; // Model matrix
682 v3f offset = intToFloat(m_camera_offset, BS);
683 u32 material_swaps = 0;
685 // Render all mesh buffers in order
686 drawcall_count += draw_order.size();
688 for (auto &descriptor : draw_order) {
689 scene::IMeshBuffer *buf = descriptor.getBuffer();
691 if (!descriptor.m_reuse_material) {
692 auto &material = buf->getMaterial();
694 // Apply filter settings
695 material.setFlag(video::EMF_TRILINEAR_FILTER,
696 m_cache_trilinear_filter);
697 material.setFlag(video::EMF_BILINEAR_FILTER,
698 m_cache_bilinear_filter);
699 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
700 m_cache_anistropic_filter);
701 material.setFlag(video::EMF_WIREFRAME,
702 m_control.show_wireframe);
704 // pass the shadow map texture to the buffer texture
705 ShadowRenderer *shadow = m_rendering_engine->get_shadow_renderer();
706 if (shadow && shadow->is_active()) {
707 auto &layer = material.TextureLayer[ShadowRenderer::TEXTURE_LAYER_SHADOW];
708 layer.Texture = shadow->get_texture();
709 layer.TextureWrapU = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
710 layer.TextureWrapV = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
711 // Do not enable filter on shadow texture to avoid visual artifacts
712 // with colored shadows.
713 // Filtering is done in shader code anyway
714 layer.BilinearFilter = false;
715 layer.AnisotropicFilter = false;
716 layer.TrilinearFilter = false;
718 driver->setMaterial(material);
720 material.TextureLayer[ShadowRenderer::TEXTURE_LAYER_SHADOW].Texture = nullptr;
723 v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS);
724 m.setTranslation(block_wpos - offset);
726 driver->setTransform(video::ETS_WORLD, m);
727 descriptor.draw(driver);
728 vertex_count += buf->getIndexCount();
731 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
733 // Log only on solid pass because values are the same
734 if (pass == scene::ESNRP_SOLID) {
735 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
738 if (pass == scene::ESNRP_TRANSPARENT) {
739 g_profiler->avg("renderMap(): transparent buffers [#]", draw_order.size());
742 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
743 g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
744 g_profiler->avg(prefix + "material swaps [#]", material_swaps);
747 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
748 float step_multiplier, float start_distance, float end_distance,
749 const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
750 int *result, bool *sunlight_seen)
752 int brightness_sum = 0;
753 int brightness_count = 0;
754 float distance = start_distance;
757 pf += dir * distance;
759 bool nonlight_seen = false;
760 bool allow_allowing_non_sunlight_propagates = false;
761 bool allow_non_sunlight_propagates = false;
762 // Check content nearly at camera position
764 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
765 MapNode n = map->getNode(p);
766 if(ndef->getLightingFlags(n).has_light &&
767 !ndef->getLightingFlags(n).sunlight_propagates)
768 allow_allowing_non_sunlight_propagates = true;
770 // If would start at CONTENT_IGNORE, start closer
772 v3s16 p = floatToInt(pf, BS);
773 MapNode n = map->getNode(p);
774 if(n.getContent() == CONTENT_IGNORE){
776 pf = p0 + dir * 2*newd;
781 for (int i=0; distance < end_distance; i++) {
784 step *= step_multiplier;
786 v3s16 p = floatToInt(pf, BS);
787 MapNode n = map->getNode(p);
788 ContentLightingFlags f = ndef->getLightingFlags(n);
789 if (allow_allowing_non_sunlight_propagates && i == 0 &&
790 f.has_light && !f.sunlight_propagates) {
791 allow_non_sunlight_propagates = true;
794 if (!f.has_light || (!f.sunlight_propagates && !allow_non_sunlight_propagates)){
795 nonlight_seen = true;
802 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
803 if (n.getLight(LIGHTBANK_DAY, f) == LIGHT_SUN)
804 *sunlight_seen = true;
806 brightness_sum += decode_light(n.getLightBlend(daylight_factor, f));
810 if(brightness_count == 0)
812 *result = brightness_sum / brightness_count;
813 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
814 <<(*result)<<std::endl;*/
818 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
819 int oldvalue, bool *sunlight_seen_result)
821 ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
822 static v3f z_directions[50] = {
825 static f32 z_offsets[50] = {
829 if (z_directions[0].X < -99) {
830 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
831 // Assumes FOV of 72 and 16/9 aspect ratio
832 z_directions[i] = v3f(
833 0.02 * myrand_range(-100, 100),
835 0.01 * myrand_range(-100, 100)
837 z_offsets[i] = 0.01 * myrand_range(0,100);
841 int sunlight_seen_count = 0;
842 float sunlight_min_d = max_d*0.8;
843 if(sunlight_min_d > 35*BS)
844 sunlight_min_d = 35*BS;
845 std::vector<int> values;
846 values.reserve(ARRLEN(z_directions));
847 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
848 v3f z_dir = z_directions[i];
849 core::CMatrix4<f32> a;
850 a.buildRotateFromTo(v3f(0,1,0), z_dir);
851 v3f dir = m_camera_direction;
856 step = max_d / 35 * 1.5;
857 float off = step * z_offsets[i];
858 bool sunlight_seen_now = false;
859 bool ok = getVisibleBrightness(this, m_camera_position, dir,
860 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
862 &br, &sunlight_seen_now);
863 if(sunlight_seen_now)
864 sunlight_seen_count++;
867 values.push_back(br);
868 // Don't try too much if being in the sun is clear
869 if(sunlight_seen_count >= 20)
872 int brightness_sum = 0;
873 int brightness_count = 0;
874 std::sort(values.begin(), values.end());
875 u32 num_values_to_use = values.size();
876 if(num_values_to_use >= 10)
877 num_values_to_use -= num_values_to_use/2;
878 else if(num_values_to_use >= 7)
879 num_values_to_use -= num_values_to_use/3;
880 u32 first_value_i = (values.size() - num_values_to_use) / 2;
882 for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
883 brightness_sum += values[i];
888 if(brightness_count == 0){
889 MapNode n = getNode(floatToInt(m_camera_position, BS));
890 ContentLightingFlags f = m_nodedef->getLightingFlags(n);
892 ret = decode_light(n.getLightBlend(daylight_factor, f));
897 ret = brightness_sum / brightness_count;
900 *sunlight_seen_result = (sunlight_seen_count > 0);
904 void ClientMap::renderPostFx(CameraMode cam_mode)
906 // Sadly ISceneManager has no "post effects" render pass, in that case we
907 // could just register for that and handle it in renderMap().
909 MapNode n = getNode(floatToInt(m_camera_position, BS));
911 const ContentFeatures& features = m_nodedef->get(n);
912 video::SColor post_effect_color = features.post_effect_color;
914 // If the camera is in a solid node, make everything black.
915 // (first person mode only)
916 if (features.solidness == 2 && cam_mode == CAMERA_MODE_FIRST &&
917 !m_control.allow_noclip) {
918 post_effect_color = video::SColor(255, 0, 0, 0);
921 if (post_effect_color.getAlpha() != 0) {
922 // Draw a full-screen rectangle
923 video::IVideoDriver* driver = SceneManager->getVideoDriver();
924 v2u32 ss = driver->getScreenSize();
925 core::rect<s32> rect(0,0, ss.X, ss.Y);
926 driver->draw2DRectangle(post_effect_color, rect);
930 void ClientMap::PrintInfo(std::ostream &out)
935 void ClientMap::renderMapShadows(video::IVideoDriver *driver,
936 const video::SMaterial &material, s32 pass, int frame, int total_frames)
938 bool is_transparent_pass = pass != scene::ESNRP_SOLID;
940 if (is_transparent_pass)
941 prefix = "renderMap(SHADOW TRANS): ";
943 prefix = "renderMap(SHADOW SOLID): ";
945 u32 drawcall_count = 0;
946 u32 vertex_count = 0;
948 MeshBufListList grouped_buffers;
949 std::vector<DrawDescriptor> draw_order;
953 int low_bound = is_transparent_pass ? 0 : m_drawlist_shadow.size() / total_frames * frame;
954 int high_bound = is_transparent_pass ? m_drawlist_shadow.size() : m_drawlist_shadow.size() / total_frames * (frame + 1);
956 // transparent pass should be rendered in one go
957 if (is_transparent_pass && frame != total_frames - 1) {
961 for (const auto &i : m_drawlist_shadow) {
962 // only process specific part of the list & break early
964 if (count <= low_bound)
966 if (count > high_bound)
969 v3s16 block_pos = i.first;
970 MapBlock *block = i.second;
972 // If the mesh of the block happened to get deleted, ignore it
977 Get the meshbuffers of the block
979 if (is_transparent_pass) {
980 // In transparent pass, the mesh will give us
981 // the partial buffers in the correct order
982 for (auto &buffer : block->mesh->getTransparentBuffers())
983 draw_order.emplace_back(block_pos, &buffer);
986 // otherwise, group buffers across meshes
987 // using MeshBufListList
988 MapBlockMesh *mapBlockMesh = block->mesh;
989 assert(mapBlockMesh);
991 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
992 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
995 u32 c = mesh->getMeshBufferCount();
996 for (u32 i = 0; i < c; i++) {
997 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
999 video::SMaterial &mat = buf->getMaterial();
1000 auto rnd = driver->getMaterialRenderer(mat.MaterialType);
1001 bool transparent = rnd && rnd->isTransparent();
1003 grouped_buffers.add(buf, block_pos, layer);
1009 u32 buffer_count = 0;
1010 for (auto &lists : grouped_buffers.lists)
1011 for (MeshBufList &list : lists)
1012 buffer_count += list.bufs.size();
1014 draw_order.reserve(draw_order.size() + buffer_count);
1016 // Capture draw order for all solid meshes
1017 for (auto &lists : grouped_buffers.lists) {
1018 for (MeshBufList &list : lists) {
1019 // iterate in reverse to draw closest blocks first
1020 for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it)
1021 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
1025 TimeTaker draw("Drawing shadow mesh buffers");
1027 core::matrix4 m; // Model matrix
1028 v3f offset = intToFloat(m_camera_offset, BS);
1029 u32 material_swaps = 0;
1031 // Render all mesh buffers in order
1032 drawcall_count += draw_order.size();
1034 for (auto &descriptor : draw_order) {
1035 scene::IMeshBuffer *buf = descriptor.getBuffer();
1037 if (!descriptor.m_reuse_material) {
1038 // override some material properties
1039 video::SMaterial local_material = buf->getMaterial();
1040 local_material.MaterialType = material.MaterialType;
1041 local_material.BackfaceCulling = material.BackfaceCulling;
1042 local_material.FrontfaceCulling = material.FrontfaceCulling;
1043 local_material.BlendOperation = material.BlendOperation;
1044 local_material.Lighting = false;
1045 driver->setMaterial(local_material);
1049 v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS);
1050 m.setTranslation(block_wpos - offset);
1052 driver->setTransform(video::ETS_WORLD, m);
1053 descriptor.draw(driver);
1054 vertex_count += buf->getIndexCount();
1057 // restore the driver material state
1058 video::SMaterial clean;
1059 clean.BlendOperation = video::EBO_ADD;
1060 driver->setMaterial(clean); // reset material to defaults
1061 driver->draw3DLine(v3f(), v3f(), video::SColor(0));
1063 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
1064 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
1065 g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
1066 g_profiler->avg(prefix + "material swaps [#]", material_swaps);
1070 Custom update draw list for the pov of shadow light.
1072 void ClientMap::updateDrawListShadow(v3f shadow_light_pos, v3f shadow_light_dir, float radius, float length)
1074 ScopeProfiler sp(g_profiler, "CM::updateDrawListShadow()", SPT_AVG);
1076 v3s16 cam_pos_nodes = floatToInt(shadow_light_pos, BS);
1079 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max, radius + length);
1081 for (auto &i : m_drawlist_shadow) {
1082 MapBlock *block = i.second;
1085 m_drawlist_shadow.clear();
1087 // Number of blocks currently loaded by the client
1088 u32 blocks_loaded = 0;
1089 // Number of blocks with mesh in rendering range
1090 u32 blocks_in_range_with_mesh = 0;
1091 // Number of blocks occlusion culled
1092 u32 blocks_occlusion_culled = 0;
1094 for (auto §or_it : m_sectors) {
1095 MapSector *sector = sector_it.second;
1098 blocks_loaded += sector->size();
1100 MapBlockVect sectorblocks;
1101 sector->getBlocks(sectorblocks);
1104 Loop through blocks in sector
1106 for (MapBlock *block : sectorblocks) {
1108 // Ignore if mesh doesn't exist
1112 v3f block_pos = intToFloat(block->getPos() * MAP_BLOCKSIZE, BS);
1113 v3f projection = shadow_light_pos + shadow_light_dir * shadow_light_dir.dotProduct(block_pos - shadow_light_pos);
1114 if (projection.getDistanceFrom(block_pos) > radius)
1117 blocks_in_range_with_mesh++;
1119 // This block is in range. Reset usage timer.
1120 block->resetUsageTimer();
1123 if (m_drawlist_shadow.find(block->getPos()) == m_drawlist_shadow.end()) {
1125 m_drawlist_shadow[block->getPos()] = block;
1130 g_profiler->avg("SHADOW MapBlock meshes in range [#]", blocks_in_range_with_mesh);
1131 g_profiler->avg("SHADOW MapBlocks occlusion culled [#]", blocks_occlusion_culled);
1132 g_profiler->avg("SHADOW MapBlocks drawn [#]", m_drawlist_shadow.size());
1133 g_profiler->avg("SHADOW MapBlocks loaded [#]", blocks_loaded);
1136 void ClientMap::updateTransparentMeshBuffers()
1138 ScopeProfiler sp(g_profiler, "CM::updateTransparentMeshBuffers", SPT_AVG);
1139 u32 sorted_blocks = 0;
1140 u32 unsorted_blocks = 0;
1141 f32 sorting_distance_sq = pow(m_cache_transparency_sorting_distance * BS, 2.0f);
1144 // Update the order of transparent mesh buffers in each mesh
1145 for (auto it = m_drawlist.begin(); it != m_drawlist.end(); it++) {
1146 MapBlock* block = it->second;
1150 if (m_needs_update_transparent_meshes ||
1151 block->mesh->getTransparentBuffers().size() == 0) {
1153 v3s16 block_pos = block->getPos();
1154 v3f block_pos_f = intToFloat(block_pos * MAP_BLOCKSIZE + MAP_BLOCKSIZE / 2, BS);
1155 f32 distance = m_camera_position.getDistanceFromSQ(block_pos_f);
1156 if (distance <= sorting_distance_sq) {
1157 block->mesh->updateTransparentBuffers(m_camera_position, block_pos);
1161 block->mesh->consolidateTransparentBuffers();
1167 g_profiler->avg("CM::Transparent Buffers - Sorted", sorted_blocks);
1168 g_profiler->avg("CM::Transparent Buffers - Unsorted", unsorted_blocks);
1169 m_needs_update_transparent_meshes = false;
1172 scene::IMeshBuffer* ClientMap::DrawDescriptor::getBuffer()
1174 return m_use_partial_buffer ? m_partial_buffer->getBuffer() : m_buffer;
1177 void ClientMap::DrawDescriptor::draw(video::IVideoDriver* driver)
1179 if (m_use_partial_buffer) {
1180 m_partial_buffer->beforeDraw();
1181 driver->drawMeshBuffer(m_partial_buffer->getBuffer());
1182 m_partial_buffer->afterDraw();
1184 driver->drawMeshBuffer(m_buffer);