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"
32 #include "client/renderingengine.h"
34 // struct MeshBufListList
35 void MeshBufListList::clear()
37 for (auto &list : lists)
41 void MeshBufListList::add(scene::IMeshBuffer *buf, v3s16 position, u8 layer)
43 // Append to the correct layer
44 std::vector<MeshBufList> &list = lists[layer];
45 const video::SMaterial &m = buf->getMaterial();
46 for (MeshBufList &l : list) {
47 // comparing a full material is quite expensive so we don't do it if
48 // not even first texture is equal
49 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
53 l.bufs.emplace_back(position, buf);
59 l.bufs.emplace_back(position, buf);
67 RenderingEngine *rendering_engine,
68 MapDrawControl &control,
72 scene::ISceneNode(rendering_engine->get_scene_manager()->getRootSceneNode(),
73 rendering_engine->get_scene_manager(), id),
75 m_rendering_engine(rendering_engine),
77 m_drawlist(MapBlockComparer(v3s16(0,0,0)))
81 * @Liso: Sadly C++ doesn't have introspection, so the only way we have to know
82 * the class is whith a name ;) Name property cames from ISceneNode base class.
85 m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
86 BS*1000000,BS*1000000,BS*1000000);
88 /* TODO: Add a callback function so these can be updated when a setting
89 * changes. At this point in time it doesn't matter (e.g. /set
90 * is documented to change server settings only)
92 * TODO: Local caching of settings is not optimal and should at some stage
93 * be updated to use a global settings object for getting thse values
94 * (as opposed to the this local caching). This can be addressed in
97 m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
98 m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
99 m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
100 m_cache_transparency_sorting_distance = g_settings->getU16("transparency_sorting_distance");
104 void ClientMap::updateCamera(v3f pos, v3f dir, f32 fov, v3s16 offset)
106 v3s16 previous_node = floatToInt(m_camera_position, BS) + m_camera_offset;
107 v3s16 previous_block = getContainerPos(previous_node, MAP_BLOCKSIZE);
109 m_camera_position = pos;
110 m_camera_direction = dir;
112 m_camera_offset = offset;
114 v3s16 current_node = floatToInt(m_camera_position, BS) + m_camera_offset;
115 v3s16 current_block = getContainerPos(current_node, MAP_BLOCKSIZE);
117 // reorder the blocks when camera crosses block boundary
118 if (previous_block != current_block)
119 m_needs_update_drawlist = true;
121 // reorder transparent meshes when camera crosses node boundary
122 if (previous_node != current_node)
123 m_needs_update_transparent_meshes = true;
126 MapSector * ClientMap::emergeSector(v2s16 p2d)
128 // Check that it doesn't exist already
129 MapSector *sector = getSectorNoGenerate(p2d);
131 // Create it if it does not exist yet
133 sector = new MapSector(this, p2d, m_gamedef);
134 m_sectors[p2d] = sector;
140 void ClientMap::OnRegisterSceneNode()
144 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
145 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
148 ISceneNode::OnRegisterSceneNode();
150 if (!m_added_to_shadow_renderer) {
151 m_added_to_shadow_renderer = true;
152 if (auto shadows = m_rendering_engine->get_shadow_renderer())
153 shadows->addNodeToShadowList(this);
157 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
158 v3s16 *p_blocks_min, v3s16 *p_blocks_max, float range)
161 range = m_control.wanted_range;
163 v3s16 box_nodes_d = range * v3s16(1, 1, 1);
164 // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
165 // can exceed the range of v3s16 when a large view range is used near the
168 cam_pos_nodes.X - box_nodes_d.X,
169 cam_pos_nodes.Y - box_nodes_d.Y,
170 cam_pos_nodes.Z - box_nodes_d.Z);
172 cam_pos_nodes.X + box_nodes_d.X,
173 cam_pos_nodes.Y + box_nodes_d.Y,
174 cam_pos_nodes.Z + box_nodes_d.Z);
175 // Take a fair amount as we will be dropping more out later
176 // Umm... these additions are a bit strange but they are needed.
177 *p_blocks_min = v3s16(
178 p_nodes_min.X / MAP_BLOCKSIZE - 3,
179 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
180 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
181 *p_blocks_max = v3s16(
182 p_nodes_max.X / MAP_BLOCKSIZE + 1,
183 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
184 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
187 void ClientMap::updateDrawList()
189 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
191 m_needs_update_drawlist = false;
193 for (auto &i : m_drawlist) {
194 MapBlock *block = i.second;
199 const v3f camera_position = m_camera_position;
200 const v3f camera_direction = m_camera_direction;
202 // Use a higher fov to accomodate faster camera movements.
203 // Blocks are cropped better when they are drawn.
204 const f32 camera_fov = m_camera_fov * 1.1f;
206 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
210 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
212 // Read the vision range, unless unlimited range is enabled.
213 float range = m_control.range_all ? 1e7 : m_control.wanted_range;
215 // Number of blocks currently loaded by the client
216 u32 blocks_loaded = 0;
217 // Number of blocks with mesh in rendering range
218 u32 blocks_in_range_with_mesh = 0;
219 // Number of blocks occlusion culled
220 u32 blocks_occlusion_culled = 0;
222 // No occlusion culling when free_move is on and camera is
224 bool occlusion_culling_enabled = true;
225 if (g_settings->getBool("free_move") && g_settings->getBool("noclip")) {
226 MapNode n = getNode(cam_pos_nodes);
227 if (n.getContent() == CONTENT_IGNORE ||
228 m_nodedef->get(n).solidness == 2)
229 occlusion_culling_enabled = false;
232 v3s16 camera_block = getContainerPos(cam_pos_nodes, MAP_BLOCKSIZE);
233 m_drawlist = std::map<v3s16, MapBlock*, MapBlockComparer>(MapBlockComparer(camera_block));
235 // Uncomment to debug occluded blocks in the wireframe mode
236 // TODO: Include this as a flag for an extended debugging setting
237 //if (occlusion_culling_enabled && m_control.show_wireframe)
238 // occlusion_culling_enabled = porting::getTimeS() & 1;
240 for (const auto §or_it : m_sectors) {
241 MapSector *sector = sector_it.second;
242 v2s16 sp = sector->getPos();
244 blocks_loaded += sector->size();
245 if (!m_control.range_all) {
246 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
247 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
251 MapBlockVect sectorblocks;
252 sector->getBlocks(sectorblocks);
255 Loop through blocks in sector
258 u32 sector_blocks_drawn = 0;
260 for (MapBlock *block : sectorblocks) {
262 Compare block position to camera position, skip
263 if not seen on display
267 // Ignore if mesh doesn't exist
271 v3s16 block_coord = block->getPos();
272 v3s16 block_position = block->getPosRelative() + MAP_BLOCKSIZE / 2;
274 // First, perform a simple distance check, with a padding of one extra block.
275 if (!m_control.range_all &&
276 block_position.getDistanceFrom(cam_pos_nodes) > range + MAP_BLOCKSIZE)
277 continue; // Out of range, skip.
279 // Keep the block alive as long as it is in range.
280 block->resetUsageTimer();
281 blocks_in_range_with_mesh++;
285 if (!isBlockInSight(block_coord, camera_position,
286 camera_direction, camera_fov, range * BS, &d))
290 if ((!m_control.range_all && d > m_control.wanted_range * BS) ||
291 (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) {
292 blocks_occlusion_culled++;
298 m_drawlist[block_coord] = block;
300 sector_blocks_drawn++;
301 } // foreach sectorblocks
303 if (sector_blocks_drawn != 0)
304 m_last_drawn_sectors.insert(sp);
307 g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
308 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
309 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
310 g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
313 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
315 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
318 if (pass == scene::ESNRP_SOLID)
319 prefix = "renderMap(SOLID): ";
321 prefix = "renderMap(TRANSPARENT): ";
324 This is called two times per frame, reset on the non-transparent one
326 if (pass == scene::ESNRP_SOLID)
327 m_last_drawn_sectors.clear();
330 Get animation parameters
332 const float animation_time = m_client->getAnimationTime();
333 const int crack = m_client->getCrackLevel();
334 const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
336 const v3f camera_position = m_camera_position;
339 Get all blocks and draw all visible ones
342 u32 vertex_count = 0;
343 u32 drawcall_count = 0;
345 // For limiting number of mesh animations per frame
346 u32 mesh_animate_count = 0;
347 //u32 mesh_animate_count_far = 0;
350 Update transparent meshes
352 if (is_transparent_pass)
353 updateTransparentMeshBuffers();
356 Draw the selected MapBlocks
359 MeshBufListList grouped_buffers;
360 std::vector<DrawDescriptor> draw_order;
361 video::SMaterial previous_material;
363 for (auto &i : m_drawlist) {
364 v3s16 block_pos = i.first;
365 MapBlock *block = i.second;
367 // If the mesh of the block happened to get deleted, ignore it
371 v3f block_pos_r = intToFloat(block->getPosRelative() + MAP_BLOCKSIZE / 2, BS);
372 float d = camera_position.getDistanceFrom(block_pos_r);
373 d = MYMAX(0,d - BLOCK_MAX_RADIUS);
376 if (pass == scene::ESNRP_SOLID) {
377 MapBlockMesh *mapBlockMesh = block->mesh;
378 assert(mapBlockMesh);
379 // Pretty random but this should work somewhat nicely
380 bool faraway = d >= BS * 50;
381 if (mapBlockMesh->isAnimationForced() || !faraway ||
382 mesh_animate_count < (m_control.range_all ? 200 : 50)) {
384 bool animated = mapBlockMesh->animate(faraway, animation_time,
385 crack, daynight_ratio);
387 mesh_animate_count++;
389 mapBlockMesh->decreaseAnimationForceTimer();
394 Get the meshbuffers of the block
396 if (is_transparent_pass) {
397 // In transparent pass, the mesh will give us
398 // the partial buffers in the correct order
399 for (auto &buffer : block->mesh->getTransparentBuffers())
400 draw_order.emplace_back(block_pos, &buffer);
403 // otherwise, group buffers across meshes
404 // using MeshBufListList
405 MapBlockMesh *mapBlockMesh = block->mesh;
406 assert(mapBlockMesh);
408 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
409 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
412 u32 c = mesh->getMeshBufferCount();
413 for (u32 i = 0; i < c; i++) {
414 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
416 video::SMaterial& material = buf->getMaterial();
417 video::IMaterialRenderer* rnd =
418 driver->getMaterialRenderer(material.MaterialType);
419 bool transparent = (rnd && rnd->isTransparent());
421 if (buf->getVertexCount() == 0)
422 errorstream << "Block [" << analyze_block(block)
423 << "] contains an empty meshbuf" << std::endl;
425 grouped_buffers.add(buf, block_pos, layer);
432 // Capture draw order for all solid meshes
433 for (auto &lists : grouped_buffers.lists) {
434 for (MeshBufList &list : lists) {
435 // iterate in reverse to draw closest blocks first
436 for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it) {
437 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
442 TimeTaker draw("Drawing mesh buffers");
444 core::matrix4 m; // Model matrix
445 v3f offset = intToFloat(m_camera_offset, BS);
446 u32 material_swaps = 0;
448 // Render all mesh buffers in order
449 drawcall_count += draw_order.size();
451 for (auto &descriptor : draw_order) {
452 scene::IMeshBuffer *buf = descriptor.getBuffer();
454 // Check and abort if the machine is swapping a lot
455 if (draw.getTimerTime() > 2000) {
456 infostream << "ClientMap::renderMap(): Rendering took >2s, " <<
457 "returning." << std::endl;
461 if (!descriptor.m_reuse_material) {
462 auto &material = buf->getMaterial();
464 // Apply filter settings
465 material.setFlag(video::EMF_TRILINEAR_FILTER,
466 m_cache_trilinear_filter);
467 material.setFlag(video::EMF_BILINEAR_FILTER,
468 m_cache_bilinear_filter);
469 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
470 m_cache_anistropic_filter);
471 material.setFlag(video::EMF_WIREFRAME,
472 m_control.show_wireframe);
474 // pass the shadow map texture to the buffer texture
475 ShadowRenderer *shadow = m_rendering_engine->get_shadow_renderer();
476 if (shadow && shadow->is_active()) {
477 auto &layer = material.TextureLayer[3];
478 layer.Texture = shadow->get_texture();
479 layer.TextureWrapU = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
480 layer.TextureWrapV = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
481 // Do not enable filter on shadow texture to avoid visual artifacts
482 // with colored shadows.
483 // Filtering is done in shader code anyway
484 layer.BilinearFilter = false;
485 layer.AnisotropicFilter = false;
486 layer.TrilinearFilter = false;
488 driver->setMaterial(material);
492 v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS);
493 m.setTranslation(block_wpos - offset);
495 driver->setTransform(video::ETS_WORLD, m);
496 descriptor.draw(driver);
497 vertex_count += buf->getIndexCount();
500 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
502 // Log only on solid pass because values are the same
503 if (pass == scene::ESNRP_SOLID) {
504 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
507 if (pass == scene::ESNRP_TRANSPARENT) {
508 g_profiler->avg("renderMap(): transparent buffers [#]", draw_order.size());
511 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
512 g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
513 g_profiler->avg(prefix + "material swaps [#]", material_swaps);
516 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
517 float step_multiplier, float start_distance, float end_distance,
518 const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
519 int *result, bool *sunlight_seen)
521 int brightness_sum = 0;
522 int brightness_count = 0;
523 float distance = start_distance;
526 pf += dir * distance;
528 bool nonlight_seen = false;
529 bool allow_allowing_non_sunlight_propagates = false;
530 bool allow_non_sunlight_propagates = false;
531 // Check content nearly at camera position
533 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
534 MapNode n = map->getNode(p);
535 if(ndef->get(n).param_type == CPT_LIGHT &&
536 !ndef->get(n).sunlight_propagates)
537 allow_allowing_non_sunlight_propagates = true;
539 // If would start at CONTENT_IGNORE, start closer
541 v3s16 p = floatToInt(pf, BS);
542 MapNode n = map->getNode(p);
543 if(n.getContent() == CONTENT_IGNORE){
545 pf = p0 + dir * 2*newd;
550 for (int i=0; distance < end_distance; i++) {
553 step *= step_multiplier;
555 v3s16 p = floatToInt(pf, BS);
556 MapNode n = map->getNode(p);
557 if (allow_allowing_non_sunlight_propagates && i == 0 &&
558 ndef->get(n).param_type == CPT_LIGHT &&
559 !ndef->get(n).sunlight_propagates) {
560 allow_non_sunlight_propagates = true;
563 if (ndef->get(n).param_type != CPT_LIGHT ||
564 (!ndef->get(n).sunlight_propagates &&
565 !allow_non_sunlight_propagates)){
566 nonlight_seen = true;
573 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
574 if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
575 *sunlight_seen = true;
577 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
581 if(brightness_count == 0)
583 *result = brightness_sum / brightness_count;
584 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
585 <<(*result)<<std::endl;*/
589 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
590 int oldvalue, bool *sunlight_seen_result)
592 ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
593 static v3f z_directions[50] = {
596 static f32 z_offsets[50] = {
600 if (z_directions[0].X < -99) {
601 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
602 // Assumes FOV of 72 and 16/9 aspect ratio
603 z_directions[i] = v3f(
604 0.02 * myrand_range(-100, 100),
606 0.01 * myrand_range(-100, 100)
608 z_offsets[i] = 0.01 * myrand_range(0,100);
612 int sunlight_seen_count = 0;
613 float sunlight_min_d = max_d*0.8;
614 if(sunlight_min_d > 35*BS)
615 sunlight_min_d = 35*BS;
616 std::vector<int> values;
617 values.reserve(ARRLEN(z_directions));
618 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
619 v3f z_dir = z_directions[i];
620 core::CMatrix4<f32> a;
621 a.buildRotateFromTo(v3f(0,1,0), z_dir);
622 v3f dir = m_camera_direction;
627 step = max_d / 35 * 1.5;
628 float off = step * z_offsets[i];
629 bool sunlight_seen_now = false;
630 bool ok = getVisibleBrightness(this, m_camera_position, dir,
631 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
633 &br, &sunlight_seen_now);
634 if(sunlight_seen_now)
635 sunlight_seen_count++;
638 values.push_back(br);
639 // Don't try too much if being in the sun is clear
640 if(sunlight_seen_count >= 20)
643 int brightness_sum = 0;
644 int brightness_count = 0;
645 std::sort(values.begin(), values.end());
646 u32 num_values_to_use = values.size();
647 if(num_values_to_use >= 10)
648 num_values_to_use -= num_values_to_use/2;
649 else if(num_values_to_use >= 7)
650 num_values_to_use -= num_values_to_use/3;
651 u32 first_value_i = (values.size() - num_values_to_use) / 2;
653 for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
654 brightness_sum += values[i];
659 if(brightness_count == 0){
660 MapNode n = getNode(floatToInt(m_camera_position, BS));
661 if(m_nodedef->get(n).param_type == CPT_LIGHT){
662 ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
667 ret = brightness_sum / brightness_count;
670 *sunlight_seen_result = (sunlight_seen_count > 0);
674 void ClientMap::renderPostFx(CameraMode cam_mode)
676 // Sadly ISceneManager has no "post effects" render pass, in that case we
677 // could just register for that and handle it in renderMap().
679 MapNode n = getNode(floatToInt(m_camera_position, BS));
681 // - If the player is in a solid node, make everything black.
682 // - If the player is in liquid, draw a semi-transparent overlay.
683 // - Do not if player is in third person mode
684 const ContentFeatures& features = m_nodedef->get(n);
685 video::SColor post_effect_color = features.post_effect_color;
686 if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
687 m_client->checkLocalPrivilege("noclip")) &&
688 cam_mode == CAMERA_MODE_FIRST)
690 post_effect_color = video::SColor(255, 0, 0, 0);
692 if (post_effect_color.getAlpha() != 0)
694 // Draw a full-screen rectangle
695 video::IVideoDriver* driver = SceneManager->getVideoDriver();
696 v2u32 ss = driver->getScreenSize();
697 core::rect<s32> rect(0,0, ss.X, ss.Y);
698 driver->draw2DRectangle(post_effect_color, rect);
702 void ClientMap::PrintInfo(std::ostream &out)
707 void ClientMap::renderMapShadows(video::IVideoDriver *driver,
708 const video::SMaterial &material, s32 pass, int frame, int total_frames)
710 bool is_transparent_pass = pass != scene::ESNRP_SOLID;
712 if (is_transparent_pass)
713 prefix = "renderMap(SHADOW TRANS): ";
715 prefix = "renderMap(SHADOW SOLID): ";
717 u32 drawcall_count = 0;
718 u32 vertex_count = 0;
720 MeshBufListList grouped_buffers;
721 std::vector<DrawDescriptor> draw_order;
725 int low_bound = is_transparent_pass ? 0 : m_drawlist_shadow.size() / total_frames * frame;
726 int high_bound = is_transparent_pass ? m_drawlist_shadow.size() : m_drawlist_shadow.size() / total_frames * (frame + 1);
728 // transparent pass should be rendered in one go
729 if (is_transparent_pass && frame != total_frames - 1) {
733 for (auto &i : m_drawlist_shadow) {
734 // only process specific part of the list & break early
736 if (count <= low_bound)
738 if (count > high_bound)
741 v3s16 block_pos = i.first;
742 MapBlock *block = i.second;
744 // If the mesh of the block happened to get deleted, ignore it
749 Get the meshbuffers of the block
751 if (is_transparent_pass) {
752 // In transparent pass, the mesh will give us
753 // the partial buffers in the correct order
754 for (auto &buffer : block->mesh->getTransparentBuffers())
755 draw_order.emplace_back(block_pos, &buffer);
758 // otherwise, group buffers across meshes
759 // using MeshBufListList
760 MapBlockMesh *mapBlockMesh = block->mesh;
761 assert(mapBlockMesh);
763 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
764 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
767 u32 c = mesh->getMeshBufferCount();
768 for (u32 i = 0; i < c; i++) {
769 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
771 video::SMaterial &mat = buf->getMaterial();
772 auto rnd = driver->getMaterialRenderer(mat.MaterialType);
773 bool transparent = rnd && rnd->isTransparent();
775 grouped_buffers.add(buf, block_pos, layer);
781 u32 buffer_count = 0;
782 for (auto &lists : grouped_buffers.lists)
783 for (MeshBufList &list : lists)
784 buffer_count += list.bufs.size();
786 draw_order.reserve(draw_order.size() + buffer_count);
788 // Capture draw order for all solid meshes
789 for (auto &lists : grouped_buffers.lists) {
790 for (MeshBufList &list : lists) {
791 // iterate in reverse to draw closest blocks first
792 for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it)
793 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
797 TimeTaker draw("Drawing shadow mesh buffers");
799 core::matrix4 m; // Model matrix
800 v3f offset = intToFloat(m_camera_offset, BS);
801 u32 material_swaps = 0;
803 // Render all mesh buffers in order
804 drawcall_count += draw_order.size();
806 for (auto &descriptor : draw_order) {
807 scene::IMeshBuffer *buf = descriptor.getBuffer();
809 // Check and abort if the machine is swapping a lot
810 if (draw.getTimerTime() > 1000) {
811 infostream << "ClientMap::renderMapShadows(): Rendering "
812 "took >1s, returning." << std::endl;
816 if (!descriptor.m_reuse_material) {
817 // override some material properties
818 video::SMaterial local_material = buf->getMaterial();
819 local_material.MaterialType = material.MaterialType;
820 local_material.BackfaceCulling = material.BackfaceCulling;
821 local_material.FrontfaceCulling = material.FrontfaceCulling;
822 local_material.BlendOperation = material.BlendOperation;
823 local_material.Lighting = false;
824 driver->setMaterial(local_material);
828 v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS);
829 m.setTranslation(block_wpos - offset);
831 driver->setTransform(video::ETS_WORLD, m);
832 descriptor.draw(driver);
833 vertex_count += buf->getIndexCount();
836 // restore the driver material state
837 video::SMaterial clean;
838 clean.BlendOperation = video::EBO_ADD;
839 driver->setMaterial(clean); // reset material to defaults
840 driver->draw3DLine(v3f(), v3f(), video::SColor(0));
842 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
843 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
844 g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
845 g_profiler->avg(prefix + "material swaps [#]", material_swaps);
849 Custom update draw list for the pov of shadow light.
851 void ClientMap::updateDrawListShadow(v3f shadow_light_pos, v3f shadow_light_dir, float radius, float length)
853 ScopeProfiler sp(g_profiler, "CM::updateDrawListShadow()", SPT_AVG);
855 v3s16 cam_pos_nodes = floatToInt(shadow_light_pos, BS);
858 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max, radius + length);
860 std::vector<v2s16> blocks_in_range;
862 for (auto &i : m_drawlist_shadow) {
863 MapBlock *block = i.second;
866 m_drawlist_shadow.clear();
868 // Number of blocks currently loaded by the client
869 u32 blocks_loaded = 0;
870 // Number of blocks with mesh in rendering range
871 u32 blocks_in_range_with_mesh = 0;
872 // Number of blocks occlusion culled
873 u32 blocks_occlusion_culled = 0;
875 for (auto §or_it : m_sectors) {
876 MapSector *sector = sector_it.second;
879 blocks_loaded += sector->size();
881 MapBlockVect sectorblocks;
882 sector->getBlocks(sectorblocks);
885 Loop through blocks in sector
887 for (MapBlock *block : sectorblocks) {
889 // Ignore if mesh doesn't exist
893 v3f block_pos = intToFloat(block->getPos() * MAP_BLOCKSIZE, BS);
894 v3f projection = shadow_light_pos + shadow_light_dir * shadow_light_dir.dotProduct(block_pos - shadow_light_pos);
895 if (projection.getDistanceFrom(block_pos) > radius)
898 blocks_in_range_with_mesh++;
900 // This block is in range. Reset usage timer.
901 block->resetUsageTimer();
904 if (m_drawlist_shadow.find(block->getPos()) == m_drawlist_shadow.end()) {
906 m_drawlist_shadow[block->getPos()] = block;
911 g_profiler->avg("SHADOW MapBlock meshes in range [#]", blocks_in_range_with_mesh);
912 g_profiler->avg("SHADOW MapBlocks occlusion culled [#]", blocks_occlusion_culled);
913 g_profiler->avg("SHADOW MapBlocks drawn [#]", m_drawlist_shadow.size());
914 g_profiler->avg("SHADOW MapBlocks loaded [#]", blocks_loaded);
917 void ClientMap::updateTransparentMeshBuffers()
919 ScopeProfiler sp(g_profiler, "CM::updateTransparentMeshBuffers", SPT_AVG);
920 u32 sorted_blocks = 0;
921 u32 unsorted_blocks = 0;
922 f32 sorting_distance_sq = pow(m_cache_transparency_sorting_distance * BS, 2.0f);
925 // Update the order of transparent mesh buffers in each mesh
926 for (auto it = m_drawlist.begin(); it != m_drawlist.end(); it++) {
927 MapBlock* block = it->second;
931 if (m_needs_update_transparent_meshes ||
932 block->mesh->getTransparentBuffers().size() == 0) {
934 v3s16 block_pos = block->getPos();
935 v3f block_pos_f = intToFloat(block_pos * MAP_BLOCKSIZE + MAP_BLOCKSIZE / 2, BS);
936 f32 distance = m_camera_position.getDistanceFromSQ(block_pos_f);
937 if (distance <= sorting_distance_sq) {
938 block->mesh->updateTransparentBuffers(m_camera_position, block_pos);
942 block->mesh->consolidateTransparentBuffers();
948 g_profiler->avg("CM::Transparent Buffers - Sorted", sorted_blocks);
949 g_profiler->avg("CM::Transparent Buffers - Unsorted", unsorted_blocks);
950 m_needs_update_transparent_meshes = false;
953 scene::IMeshBuffer* ClientMap::DrawDescriptor::getBuffer()
955 return m_use_partial_buffer ? m_partial_buffer->getBuffer() : m_buffer;
958 void ClientMap::DrawDescriptor::draw(video::IVideoDriver* driver)
960 if (m_use_partial_buffer) {
961 m_partial_buffer->beforeDraw();
962 driver->drawMeshBuffer(m_partial_buffer->getBuffer());
963 m_partial_buffer->afterDraw();
965 driver->drawMeshBuffer(m_buffer);