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 MapDrawControl &control,
71 scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
72 RenderingEngine::get_scene_manager(), id),
76 m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
77 BS*1000000,BS*1000000,BS*1000000);
79 /* TODO: Add a callback function so these can be updated when a setting
80 * changes. At this point in time it doesn't matter (e.g. /set
81 * is documented to change server settings only)
83 * TODO: Local caching of settings is not optimal and should at some stage
84 * be updated to use a global settings object for getting thse values
85 * (as opposed to the this local caching). This can be addressed in
88 m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
89 m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
90 m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
94 MapSector * ClientMap::emergeSector(v2s16 p2d)
96 // Check that it doesn't exist already
97 MapSector *sector = getSectorNoGenerate(p2d);
99 // Create it if it does not exist yet
101 sector = new MapSector(this, p2d, m_gamedef);
102 m_sectors[p2d] = sector;
108 void ClientMap::OnRegisterSceneNode()
112 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
113 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
116 ISceneNode::OnRegisterSceneNode();
119 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
120 v3s16 *p_blocks_min, v3s16 *p_blocks_max)
122 v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
123 // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
124 // can exceed the range of v3s16 when a large view range is used near the
127 cam_pos_nodes.X - box_nodes_d.X,
128 cam_pos_nodes.Y - box_nodes_d.Y,
129 cam_pos_nodes.Z - box_nodes_d.Z);
131 cam_pos_nodes.X + box_nodes_d.X,
132 cam_pos_nodes.Y + box_nodes_d.Y,
133 cam_pos_nodes.Z + box_nodes_d.Z);
134 // Take a fair amount as we will be dropping more out later
135 // Umm... these additions are a bit strange but they are needed.
136 *p_blocks_min = v3s16(
137 p_nodes_min.X / MAP_BLOCKSIZE - 3,
138 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
139 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
140 *p_blocks_max = v3s16(
141 p_nodes_max.X / MAP_BLOCKSIZE + 1,
142 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
143 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
146 void ClientMap::updateDrawList()
148 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
150 for (auto &i : m_drawlist) {
151 MapBlock *block = i.second;
156 const v3f camera_position = m_camera_position;
157 const v3f camera_direction = m_camera_direction;
159 // Use a higher fov to accomodate faster camera movements.
160 // Blocks are cropped better when they are drawn.
161 const f32 camera_fov = m_camera_fov * 1.1f;
163 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
166 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
168 // Number of blocks currently loaded by the client
169 u32 blocks_loaded = 0;
170 // Number of blocks with mesh in rendering range
171 u32 blocks_in_range_with_mesh = 0;
172 // Number of blocks occlusion culled
173 u32 blocks_occlusion_culled = 0;
175 // No occlusion culling when free_move is on and camera is
177 bool occlusion_culling_enabled = true;
178 if ((g_settings->getBool("free_move") && g_settings->getBool("noclip")) || g_settings->getBool("freecam")) {
179 MapNode n = getNode(cam_pos_nodes);
180 if (n.getContent() == CONTENT_IGNORE ||
181 m_nodedef->get(n).solidness == 2)
182 occlusion_culling_enabled = false;
185 // Uncomment to debug occluded blocks in the wireframe mode
186 // TODO: Include this as a flag for an extended debugging setting
187 //if (occlusion_culling_enabled && m_control.show_wireframe)
188 // occlusion_culling_enabled = porting::getTimeS() & 1;
190 for (const auto §or_it : m_sectors) {
191 MapSector *sector = sector_it.second;
192 v2s16 sp = sector->getPos();
194 blocks_loaded += sector->size();
195 if (!m_control.range_all) {
196 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
197 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
201 MapBlockVect sectorblocks;
202 sector->getBlocks(sectorblocks);
205 Loop through blocks in sector
208 u32 sector_blocks_drawn = 0;
210 for (MapBlock *block : sectorblocks) {
212 Compare block position to camera position, skip
213 if not seen on display
217 // Ignore if mesh doesn't exist
221 float range = 100000 * BS;
222 if (!m_control.range_all)
223 range = m_control.wanted_range * BS;
226 if (!isBlockInSight(block->getPos(), camera_position,
227 camera_direction, camera_fov, range, &d))
230 blocks_in_range_with_mesh++;
235 if ((!m_control.range_all && d > m_control.wanted_range * BS) ||
236 (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) {
237 blocks_occlusion_culled++;
241 // This block is in range. Reset usage timer.
242 block->resetUsageTimer();
246 m_drawlist[block->getPos()] = block;
248 sector_blocks_drawn++;
249 } // foreach sectorblocks
251 if (sector_blocks_drawn != 0)
252 m_last_drawn_sectors.insert(sp);
255 g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
256 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
257 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
258 g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
261 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
263 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
266 if (pass == scene::ESNRP_SOLID)
267 prefix = "renderMap(SOLID): ";
269 prefix = "renderMap(TRANSPARENT): ";
272 This is called two times per frame, reset on the non-transparent one
274 if (pass == scene::ESNRP_SOLID)
275 m_last_drawn_sectors.clear();
278 Get animation parameters
280 const float animation_time = m_client->getAnimationTime();
281 const int crack = m_client->getCrackLevel();
282 const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
284 const v3f camera_position = m_camera_position;
285 const v3f camera_direction = m_camera_direction;
286 const f32 camera_fov = m_camera_fov;
289 Get all blocks and draw all visible ones
292 u32 vertex_count = 0;
293 u32 drawcall_count = 0;
295 // For limiting number of mesh animations per frame
296 u32 mesh_animate_count = 0;
297 //u32 mesh_animate_count_far = 0;
300 Draw the selected MapBlocks
303 MeshBufListList drawbufs;
305 for (auto &i : m_drawlist) {
306 v3s16 block_pos = i.first;
307 MapBlock *block = i.second;
309 // If the mesh of the block happened to get deleted, ignore it
314 if (!isBlockInSight(block->getPos(), camera_position,
315 camera_direction, camera_fov, 100000 * BS, &d))
319 if (pass == scene::ESNRP_SOLID) {
320 //MutexAutoLock lock(block->mesh_mutex);
321 MapBlockMesh *mapBlockMesh = block->mesh;
322 assert(mapBlockMesh);
323 // Pretty random but this should work somewhat nicely
324 bool faraway = d >= BS * 50;
325 if (mapBlockMesh->isAnimationForced() || !faraway ||
326 mesh_animate_count < (m_control.range_all ? 200 : 50)) {
328 bool animated = mapBlockMesh->animate(faraway, animation_time,
329 crack, daynight_ratio);
331 mesh_animate_count++;
333 mapBlockMesh->decreaseAnimationForceTimer();
338 Get the meshbuffers of the block
341 //MutexAutoLock lock(block->mesh_mutex);
343 MapBlockMesh *mapBlockMesh = block->mesh;
344 assert(mapBlockMesh);
346 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
347 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
350 u32 c = mesh->getMeshBufferCount();
351 for (u32 i = 0; i < c; i++) {
352 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
354 video::SMaterial& material = buf->getMaterial();
355 video::IMaterialRenderer* rnd =
356 driver->getMaterialRenderer(material.MaterialType);
357 bool transparent = (rnd && rnd->isTransparent());
358 if (transparent == is_transparent_pass) {
359 if (buf->getVertexCount() == 0)
360 errorstream << "Block [" << analyze_block(block)
361 << "] contains an empty meshbuf" << std::endl;
363 material.setFlag(video::EMF_TRILINEAR_FILTER,
364 m_cache_trilinear_filter);
365 material.setFlag(video::EMF_BILINEAR_FILTER,
366 m_cache_bilinear_filter);
367 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
368 m_cache_anistropic_filter);
369 material.setFlag(video::EMF_WIREFRAME,
370 m_control.show_wireframe);
372 drawbufs.add(buf, block_pos, layer);
379 TimeTaker draw("Drawing mesh buffers");
381 core::matrix4 m; // Model matrix
382 v3f offset = intToFloat(m_camera_offset, BS);
384 // Render all layers in order
385 for (auto &lists : drawbufs.lists) {
386 for (MeshBufList &list : lists) {
387 // Check and abort if the machine is swapping a lot
388 if (draw.getTimerTime() > 2000) {
389 infostream << "ClientMap::renderMap(): Rendering took >2s, " <<
390 "returning." << std::endl;
393 driver->setMaterial(list.m);
395 drawcall_count += list.bufs.size();
396 for (auto &pair : list.bufs) {
397 scene::IMeshBuffer *buf = pair.second;
399 v3f block_wpos = intToFloat(pair.first * MAP_BLOCKSIZE, BS);
400 m.setTranslation(block_wpos - offset);
402 driver->setTransform(video::ETS_WORLD, m);
403 driver->drawMeshBuffer(buf);
404 vertex_count += buf->getVertexCount();
408 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
410 // Log only on solid pass because values are the same
411 if (pass == scene::ESNRP_SOLID) {
412 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
415 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
416 g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
419 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
420 float step_multiplier, float start_distance, float end_distance,
421 const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
422 int *result, bool *sunlight_seen)
424 int brightness_sum = 0;
425 int brightness_count = 0;
426 float distance = start_distance;
429 pf += dir * distance;
431 bool nonlight_seen = false;
432 bool allow_allowing_non_sunlight_propagates = false;
433 bool allow_non_sunlight_propagates = false;
434 // Check content nearly at camera position
436 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
437 MapNode n = map->getNode(p);
438 if(ndef->get(n).param_type == CPT_LIGHT &&
439 !ndef->get(n).sunlight_propagates)
440 allow_allowing_non_sunlight_propagates = true;
442 // If would start at CONTENT_IGNORE, start closer
444 v3s16 p = floatToInt(pf, BS);
445 MapNode n = map->getNode(p);
446 if(n.getContent() == CONTENT_IGNORE){
448 pf = p0 + dir * 2*newd;
453 for (int i=0; distance < end_distance; i++) {
456 step *= step_multiplier;
458 v3s16 p = floatToInt(pf, BS);
459 MapNode n = map->getNode(p);
460 if (allow_allowing_non_sunlight_propagates && i == 0 &&
461 ndef->get(n).param_type == CPT_LIGHT &&
462 !ndef->get(n).sunlight_propagates) {
463 allow_non_sunlight_propagates = true;
466 if (ndef->get(n).param_type != CPT_LIGHT ||
467 (!ndef->get(n).sunlight_propagates &&
468 !allow_non_sunlight_propagates)){
469 nonlight_seen = true;
476 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
477 if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
478 *sunlight_seen = true;
480 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
484 if(brightness_count == 0)
486 *result = brightness_sum / brightness_count;
487 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
488 <<(*result)<<std::endl;*/
492 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
493 int oldvalue, bool *sunlight_seen_result)
495 ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
496 static v3f z_directions[50] = {
499 static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
503 if(z_directions[0].X < -99){
504 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
505 // Assumes FOV of 72 and 16/9 aspect ratio
506 z_directions[i] = v3f(
507 0.02 * myrand_range(-100, 100),
509 0.01 * myrand_range(-100, 100)
511 z_offsets[i] = 0.01 * myrand_range(0,100);
515 int sunlight_seen_count = 0;
516 float sunlight_min_d = max_d*0.8;
517 if(sunlight_min_d > 35*BS)
518 sunlight_min_d = 35*BS;
519 std::vector<int> values;
520 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
521 v3f z_dir = z_directions[i];
522 core::CMatrix4<f32> a;
523 a.buildRotateFromTo(v3f(0,1,0), z_dir);
524 v3f dir = m_camera_direction;
529 step = max_d / 35 * 1.5;
530 float off = step * z_offsets[i];
531 bool sunlight_seen_now = false;
532 bool ok = getVisibleBrightness(this, m_camera_position, dir,
533 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
535 &br, &sunlight_seen_now);
536 if(sunlight_seen_now)
537 sunlight_seen_count++;
540 values.push_back(br);
541 // Don't try too much if being in the sun is clear
542 if(sunlight_seen_count >= 20)
545 int brightness_sum = 0;
546 int brightness_count = 0;
547 std::sort(values.begin(), values.end());
548 u32 num_values_to_use = values.size();
549 if(num_values_to_use >= 10)
550 num_values_to_use -= num_values_to_use/2;
551 else if(num_values_to_use >= 7)
552 num_values_to_use -= num_values_to_use/3;
553 u32 first_value_i = (values.size() - num_values_to_use) / 2;
555 for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
556 brightness_sum += values[i];
561 if(brightness_count == 0){
562 MapNode n = getNode(floatToInt(m_camera_position, BS));
563 if(m_nodedef->get(n).param_type == CPT_LIGHT){
564 ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
569 ret = brightness_sum / brightness_count;
572 *sunlight_seen_result = (sunlight_seen_count > 0);
576 void ClientMap::renderPostFx(CameraMode cam_mode)
578 // Sadly ISceneManager has no "post effects" render pass, in that case we
579 // could just register for that and handle it in renderMap().
581 MapNode n = getNode(floatToInt(m_camera_position, BS));
583 // - If the player is in a solid node, make everything black.
584 // - If the player is in liquid, draw a semi-transparent overlay.
585 // - Do not if player is in third person mode
586 const ContentFeatures& features = m_nodedef->get(n);
587 video::SColor post_effect_color = features.post_effect_color;
588 if(features.solidness == 2 && !((g_settings->getBool("noclip") || g_settings->getBool("freecam")) &&
589 (m_client->checkLocalPrivilege("noclip") || g_settings->getBool("freecam"))) &&
590 cam_mode == CAMERA_MODE_FIRST)
592 post_effect_color = video::SColor(255, 0, 0, 0);
594 if (post_effect_color.getAlpha() != 0)
596 // Draw a full-screen rectangle
597 video::IVideoDriver* driver = SceneManager->getVideoDriver();
598 v2u32 ss = driver->getScreenSize();
599 core::rect<s32> rect(0,0, ss.X, ss.Y);
600 driver->draw2DRectangle(post_effect_color, rect);
604 void ClientMap::PrintInfo(std::ostream &out)