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"
36 MapDrawControl &control,
39 Map(dout_client, client),
40 scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
41 RenderingEngine::get_scene_manager(), id),
45 m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
46 BS*1000000,BS*1000000,BS*1000000);
48 /* TODO: Add a callback function so these can be updated when a setting
49 * changes. At this point in time it doesn't matter (e.g. /set
50 * is documented to change server settings only)
52 * TODO: Local caching of settings is not optimal and should at some stage
53 * be updated to use a global settings object for getting thse values
54 * (as opposed to the this local caching). This can be addressed in
57 m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
58 m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
59 m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
63 MapSector * ClientMap::emergeSector(v2s16 p2d)
65 DSTACK(FUNCTION_NAME);
66 // Check that it doesn't exist already
68 return getSectorNoGenerate(p2d);
69 } catch(InvalidPositionException &e) {
73 MapSector *sector = new MapSector(this, p2d, m_gamedef);
74 m_sectors[p2d] = sector;
79 void ClientMap::OnRegisterSceneNode()
83 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
84 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
87 ISceneNode::OnRegisterSceneNode();
90 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
91 v3s16 *p_blocks_min, v3s16 *p_blocks_max)
93 v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
94 // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
95 // can exceed the range of v3s16 when a large view range is used near the
98 cam_pos_nodes.X - box_nodes_d.X,
99 cam_pos_nodes.Y - box_nodes_d.Y,
100 cam_pos_nodes.Z - box_nodes_d.Z);
102 cam_pos_nodes.X + box_nodes_d.X,
103 cam_pos_nodes.Y + box_nodes_d.Y,
104 cam_pos_nodes.Z + box_nodes_d.Z);
105 // Take a fair amount as we will be dropping more out later
106 // Umm... these additions are a bit strange but they are needed.
107 *p_blocks_min = v3s16(
108 p_nodes_min.X / MAP_BLOCKSIZE - 3,
109 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
110 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
111 *p_blocks_max = v3s16(
112 p_nodes_max.X / MAP_BLOCKSIZE + 1,
113 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
114 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
117 void ClientMap::updateDrawList()
119 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
120 g_profiler->add("CM::updateDrawList() count", 1);
122 for (auto &i : m_drawlist) {
123 MapBlock *block = i.second;
128 v3f camera_position = m_camera_position;
129 v3f camera_direction = m_camera_direction;
130 f32 camera_fov = m_camera_fov;
132 // Use a higher fov to accomodate faster camera movements.
133 // Blocks are cropped better when they are drawn.
134 // Or maybe they aren't? Well whatever.
137 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
140 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
142 // Number of blocks in rendering range
143 u32 blocks_in_range = 0;
144 // Number of blocks occlusion culled
145 u32 blocks_occlusion_culled = 0;
146 // Number of blocks in rendering range but don't have a mesh
147 u32 blocks_in_range_without_mesh = 0;
148 // Blocks that had mesh that would have been drawn according to
149 // rendering range (if max blocks limit didn't kick in)
150 u32 blocks_would_have_drawn = 0;
151 // Blocks that were drawn and had a mesh
152 u32 blocks_drawn = 0;
153 // Blocks which had a corresponding meshbuffer for this pass
154 //u32 blocks_had_pass_meshbuf = 0;
155 // Blocks from which stuff was actually drawn
156 //u32 blocks_without_stuff = 0;
157 // Distance to farthest drawn block
158 float farthest_drawn = 0;
160 // No occlusion culling when free_move is on and camera is
162 bool occlusion_culling_enabled = true;
163 if (g_settings->getBool("free_move")) {
164 MapNode n = getNodeNoEx(cam_pos_nodes);
165 if (n.getContent() == CONTENT_IGNORE ||
166 m_nodedef->get(n).solidness == 2)
167 occlusion_culling_enabled = false;
170 for (const auto §or_it : m_sectors) {
171 MapSector *sector = sector_it.second;
172 v2s16 sp = sector->getPos();
174 if (!m_control.range_all) {
175 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
176 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
180 MapBlockVect sectorblocks;
181 sector->getBlocks(sectorblocks);
184 Loop through blocks in sector
187 u32 sector_blocks_drawn = 0;
189 for (auto block : sectorblocks) {
191 Compare block position to camera position, skip
192 if not seen on display
196 block->mesh->updateCameraOffset(m_camera_offset);
198 float range = 100000 * BS;
199 if (!m_control.range_all)
200 range = m_control.wanted_range * BS;
203 if (!isBlockInSight(block->getPos(), camera_position,
204 camera_direction, camera_fov, range, &d))
210 Ignore if mesh doesn't exist
213 blocks_in_range_without_mesh++;
220 if (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes)) {
221 blocks_occlusion_culled++;
225 // This block is in range. Reset usage timer.
226 block->resetUsageTimer();
228 // Limit block count in case of a sudden increase
229 blocks_would_have_drawn++;
230 if (blocks_drawn >= m_control.wanted_max_blocks &&
231 !m_control.range_all &&
232 d > m_control.wanted_range * BS)
237 m_drawlist[block->getPos()] = block;
239 sector_blocks_drawn++;
241 if (d / BS > farthest_drawn)
242 farthest_drawn = d / BS;
244 } // foreach sectorblocks
246 if (sector_blocks_drawn != 0)
247 m_last_drawn_sectors.insert(sp);
250 g_profiler->avg("CM: blocks in range", blocks_in_range);
251 g_profiler->avg("CM: blocks occlusion culled", blocks_occlusion_culled);
252 if (blocks_in_range != 0)
253 g_profiler->avg("CM: blocks in range without mesh (frac)",
254 (float)blocks_in_range_without_mesh / blocks_in_range);
255 g_profiler->avg("CM: blocks drawn", blocks_drawn);
256 g_profiler->avg("CM: farthest drawn", farthest_drawn);
257 g_profiler->avg("CM: wanted max blocks", m_control.wanted_max_blocks);
263 std::vector<scene::IMeshBuffer*> bufs;
266 struct MeshBufListList
269 * Stores the mesh buffers of the world.
270 * The array index is the material's layer.
271 * The vector part groups vertices by material.
273 std::vector<MeshBufList> lists[MAX_TILE_LAYERS];
277 for (auto &list : lists)
281 void add(scene::IMeshBuffer *buf, u8 layer)
283 // Append to the correct layer
284 std::vector<MeshBufList> &list = lists[layer];
285 const video::SMaterial &m = buf->getMaterial();
286 for (MeshBufList &l : list) {
287 // comparing a full material is quite expensive so we don't do it if
288 // not even first texture is equal
289 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
293 l.bufs.push_back(buf);
299 l.bufs.push_back(buf);
304 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
306 DSTACK(FUNCTION_NAME);
308 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
311 if (pass == scene::ESNRP_SOLID)
312 prefix = "CM: solid: ";
314 prefix = "CM: transparent: ";
317 This is called two times per frame, reset on the non-transparent one
319 if (pass == scene::ESNRP_SOLID)
320 m_last_drawn_sectors.clear();
323 Get time for measuring timeout.
325 Measuring time is very useful for long delays when the
326 machine is swapping a lot.
328 std::time_t time1 = time(0);
331 Get animation parameters
333 float animation_time = m_client->getAnimationTime();
334 int crack = m_client->getCrackLevel();
335 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
337 v3f camera_position = m_camera_position;
338 v3f camera_direction = m_camera_direction;
339 f32 camera_fov = m_camera_fov;
342 Get all blocks and draw all visible ones
345 u32 vertex_count = 0;
346 u32 meshbuffer_count = 0;
348 // For limiting number of mesh animations per frame
349 u32 mesh_animate_count = 0;
350 u32 mesh_animate_count_far = 0;
352 // Blocks that were drawn and had a mesh
353 u32 blocks_drawn = 0;
354 // Blocks which had a corresponding meshbuffer for this pass
355 u32 blocks_had_pass_meshbuf = 0;
356 // Blocks from which stuff was actually drawn
357 u32 blocks_without_stuff = 0;
360 Draw the selected MapBlocks
364 ScopeProfiler sp(g_profiler, prefix + "drawing blocks", SPT_AVG);
366 MeshBufListList drawbufs;
368 for (auto &i : m_drawlist) {
369 MapBlock *block = i.second;
371 // If the mesh of the block happened to get deleted, ignore it
376 if (!isBlockInSight(block->getPos(), camera_position,
377 camera_direction, camera_fov, 100000 * BS, &d))
381 if (pass == scene::ESNRP_SOLID) {
382 //MutexAutoLock lock(block->mesh_mutex);
383 MapBlockMesh *mapBlockMesh = block->mesh;
384 assert(mapBlockMesh);
385 // Pretty random but this should work somewhat nicely
386 bool faraway = d >= BS * 50;
387 //bool faraway = d >= m_control.wanted_range * BS;
388 if (mapBlockMesh->isAnimationForced() || !faraway ||
389 mesh_animate_count_far < (m_control.range_all ? 200 : 50)) {
390 bool animated = mapBlockMesh->animate(faraway, animation_time,
391 crack, daynight_ratio);
393 mesh_animate_count++;
394 if (animated && faraway)
395 mesh_animate_count_far++;
397 mapBlockMesh->decreaseAnimationForceTimer();
402 Get the meshbuffers of the block
405 //MutexAutoLock lock(block->mesh_mutex);
407 MapBlockMesh *mapBlockMesh = block->mesh;
408 assert(mapBlockMesh);
410 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
411 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
414 u32 c = mesh->getMeshBufferCount();
415 for (u32 i = 0; i < c; i++) {
416 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
418 video::SMaterial& material = buf->getMaterial();
419 video::IMaterialRenderer* rnd =
420 driver->getMaterialRenderer(material.MaterialType);
421 bool transparent = (rnd && rnd->isTransparent());
422 if (transparent == is_transparent_pass) {
423 if (buf->getVertexCount() == 0)
424 errorstream << "Block [" << analyze_block(block)
425 << "] contains an empty meshbuf" << std::endl;
427 material.setFlag(video::EMF_TRILINEAR_FILTER,
428 m_cache_trilinear_filter);
429 material.setFlag(video::EMF_BILINEAR_FILTER,
430 m_cache_bilinear_filter);
431 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
432 m_cache_anistropic_filter);
433 material.setFlag(video::EMF_WIREFRAME,
434 m_control.show_wireframe);
436 drawbufs.add(buf, layer);
443 // Render all layers in order
444 for (auto &lists : drawbufs.lists) {
445 int timecheck_counter = 0;
446 for (MeshBufList &list : lists) {
448 if (timecheck_counter > 50) {
449 timecheck_counter = 0;
450 std::time_t time2 = time(0);
451 if (time2 > time1 + 4) {
452 infostream << "ClientMap::renderMap(): "
453 "Rendering takes ages, returning."
459 driver->setMaterial(list.m);
461 for (scene::IMeshBuffer *buf : list.bufs) {
462 driver->drawMeshBuffer(buf);
463 vertex_count += buf->getVertexCount();
470 // Log only on solid pass because values are the same
471 if (pass == scene::ESNRP_SOLID) {
472 g_profiler->avg("CM: animated meshes", mesh_animate_count);
473 g_profiler->avg("CM: animated meshes (far)", mesh_animate_count_far);
476 g_profiler->avg(prefix + "vertices drawn", vertex_count);
477 if (blocks_had_pass_meshbuf != 0)
478 g_profiler->avg(prefix + "meshbuffers per block",
479 (float)meshbuffer_count / (float)blocks_had_pass_meshbuf);
480 if (blocks_drawn != 0)
481 g_profiler->avg(prefix + "empty blocks (frac)",
482 (float)blocks_without_stuff / blocks_drawn);
485 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
486 float step_multiplier, float start_distance, float end_distance,
487 INodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
488 int *result, bool *sunlight_seen)
490 int brightness_sum = 0;
491 int brightness_count = 0;
492 float distance = start_distance;
495 pf += dir * distance;
497 bool nonlight_seen = false;
498 bool allow_allowing_non_sunlight_propagates = false;
499 bool allow_non_sunlight_propagates = false;
500 // Check content nearly at camera position
502 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
503 MapNode n = map->getNodeNoEx(p);
504 if(ndef->get(n).param_type == CPT_LIGHT &&
505 !ndef->get(n).sunlight_propagates)
506 allow_allowing_non_sunlight_propagates = true;
508 // If would start at CONTENT_IGNORE, start closer
510 v3s16 p = floatToInt(pf, BS);
511 MapNode n = map->getNodeNoEx(p);
512 if(n.getContent() == CONTENT_IGNORE){
514 pf = p0 + dir * 2*newd;
519 for (int i=0; distance < end_distance; i++) {
522 step *= step_multiplier;
524 v3s16 p = floatToInt(pf, BS);
525 MapNode n = map->getNodeNoEx(p);
526 if (allow_allowing_non_sunlight_propagates && i == 0 &&
527 ndef->get(n).param_type == CPT_LIGHT &&
528 !ndef->get(n).sunlight_propagates) {
529 allow_non_sunlight_propagates = true;
532 if (ndef->get(n).param_type != CPT_LIGHT ||
533 (!ndef->get(n).sunlight_propagates &&
534 !allow_non_sunlight_propagates)){
535 nonlight_seen = true;
542 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
543 if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
544 *sunlight_seen = true;
546 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
550 if(brightness_count == 0)
552 *result = brightness_sum / brightness_count;
553 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
554 <<(*result)<<std::endl;*/
558 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
559 int oldvalue, bool *sunlight_seen_result)
561 static v3f z_directions[50] = {
564 static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
568 if(z_directions[0].X < -99){
569 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
570 // Assumes FOV of 72 and 16/9 aspect ratio
571 z_directions[i] = v3f(
572 0.02 * myrand_range(-100, 100),
574 0.01 * myrand_range(-100, 100)
576 z_offsets[i] = 0.01 * myrand_range(0,100);
580 int sunlight_seen_count = 0;
581 float sunlight_min_d = max_d*0.8;
582 if(sunlight_min_d > 35*BS)
583 sunlight_min_d = 35*BS;
584 std::vector<int> values;
585 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
586 v3f z_dir = z_directions[i];
587 core::CMatrix4<f32> a;
588 a.buildRotateFromTo(v3f(0,1,0), z_dir);
589 v3f dir = m_camera_direction;
594 step = max_d / 35 * 1.5;
595 float off = step * z_offsets[i];
596 bool sunlight_seen_now = false;
597 bool ok = getVisibleBrightness(this, m_camera_position, dir,
598 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
600 &br, &sunlight_seen_now);
601 if(sunlight_seen_now)
602 sunlight_seen_count++;
605 values.push_back(br);
606 // Don't try too much if being in the sun is clear
607 if(sunlight_seen_count >= 20)
610 int brightness_sum = 0;
611 int brightness_count = 0;
612 std::sort(values.begin(), values.end());
613 u32 num_values_to_use = values.size();
614 if(num_values_to_use >= 10)
615 num_values_to_use -= num_values_to_use/2;
616 else if(num_values_to_use >= 7)
617 num_values_to_use -= num_values_to_use/3;
618 u32 first_value_i = (values.size() - num_values_to_use) / 2;
620 for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
621 brightness_sum += values[i];
626 if(brightness_count == 0){
627 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
628 if(m_nodedef->get(n).param_type == CPT_LIGHT){
629 ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
634 ret = brightness_sum / brightness_count;
637 *sunlight_seen_result = (sunlight_seen_count > 0);
641 void ClientMap::renderPostFx(CameraMode cam_mode)
643 // Sadly ISceneManager has no "post effects" render pass, in that case we
644 // could just register for that and handle it in renderMap().
646 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
648 // - If the player is in a solid node, make everything black.
649 // - If the player is in liquid, draw a semi-transparent overlay.
650 // - Do not if player is in third person mode
651 const ContentFeatures& features = m_nodedef->get(n);
652 video::SColor post_effect_color = features.post_effect_color;
653 if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
654 m_client->checkLocalPrivilege("noclip")) &&
655 cam_mode == CAMERA_MODE_FIRST)
657 post_effect_color = video::SColor(255, 0, 0, 0);
659 if (post_effect_color.getAlpha() != 0)
661 // Draw a full-screen rectangle
662 video::IVideoDriver* driver = SceneManager->getVideoDriver();
663 v2u32 ss = driver->getScreenSize();
664 core::rect<s32> rect(0,0, ss.X, ss.Y);
665 driver->draw2DRectangle(post_effect_color, rect);
669 void ClientMap::PrintInfo(std::ostream &out)