3 Copyright (C) 2010-2012 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>
26 #include "mapsector.h"
27 #include "main.h" // dout_client, g_settings
32 #include "util/mathconstants.h"
34 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
39 MapDrawControl &control,
40 scene::ISceneNode* parent,
41 scene::ISceneManager* mgr,
44 Map(dout_client, gamedef),
45 scene::ISceneNode(parent, mgr, id),
48 m_camera_position(0,0,0),
49 m_camera_direction(0,0,1),
52 m_camera_mutex.Init();
53 assert(m_camera_mutex.IsInitialized());
55 m_box = core::aabbox3d<f32>(-BS*1000000,-BS*1000000,-BS*1000000,
56 BS*1000000,BS*1000000,BS*1000000);
59 ClientMap::~ClientMap()
61 /*JMutexAutoLock lock(mesh_mutex);
70 MapSector * ClientMap::emergeSector(v2s16 p2d)
72 DSTACK(__FUNCTION_NAME);
73 // Check that it doesn't exist already
75 return getSectorNoGenerate(p2d);
77 catch(InvalidPositionException &e)
82 ClientMapSector *sector = new ClientMapSector(this, p2d, m_gamedef);
85 //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
86 m_sectors.insert(p2d, sector);
93 void ClientMap::deSerializeSector(v2s16 p2d, std::istream &is)
95 DSTACK(__FUNCTION_NAME);
96 ClientMapSector *sector = NULL;
98 //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
100 core::map<v2s16, MapSector*>::Node *n = m_sectors.find(p2d);
104 sector = (ClientMapSector*)n->getValue();
105 assert(sector->getId() == MAPSECTOR_CLIENT);
109 sector = new ClientMapSector(this, p2d);
111 //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
112 m_sectors.insert(p2d, sector);
116 sector->deSerialize(is);
120 void ClientMap::OnRegisterSceneNode()
124 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
125 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
128 ISceneNode::OnRegisterSceneNode();
131 static bool isOccluded(Map *map, v3s16 p0, v3s16 p1, float step, float stepfac,
132 float start_off, float end_off, u32 needed_count, INodeDefManager *nodemgr)
134 float d0 = (float)BS * p0.getDistanceFrom(p1);
136 v3f uf = v3f(u0.X, u0.Y, u0.Z) * BS;
138 v3f p0f = v3f(p0.X, p0.Y, p0.Z) * BS;
140 for(float s=start_off; s<d0+end_off; s+=step){
141 v3f pf = p0f + uf * s;
142 v3s16 p = floatToInt(pf, BS);
143 MapNode n = map->getNodeNoEx(p);
144 bool is_transparent = false;
145 const ContentFeatures &f = nodemgr->get(n);
147 is_transparent = (f.visual_solidness != 2);
149 is_transparent = (f.solidness != 2);
152 if(count >= needed_count)
160 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
162 INodeDefManager *nodemgr = m_gamedef->ndef();
164 //m_dout<<DTIME<<"Rendering map..."<<std::endl;
165 DSTACK(__FUNCTION_NAME);
167 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
170 if(pass == scene::ESNRP_SOLID)
171 prefix = "CM: solid: ";
173 prefix = "CM: transparent: ";
176 This is called two times per frame, reset on the non-transparent one
178 if(pass == scene::ESNRP_SOLID)
180 m_last_drawn_sectors.clear();
184 Get time for measuring timeout.
186 Measuring time is very useful for long delays when the
187 machine is swapping a lot.
192 Get animation parameters
194 float animation_time = m_client->getAnimationTime();
195 int crack = m_client->getCrackLevel();
196 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
198 m_camera_mutex.Lock();
199 v3f camera_position = m_camera_position;
200 v3f camera_direction = m_camera_direction;
201 f32 camera_fov = m_camera_fov;
202 m_camera_mutex.Unlock();
205 Get all blocks and draw all visible ones
208 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
210 v3s16 box_nodes_d = m_control.wanted_range * v3s16(1,1,1);
212 v3s16 p_nodes_min = cam_pos_nodes - box_nodes_d;
213 v3s16 p_nodes_max = cam_pos_nodes + box_nodes_d;
215 // Take a fair amount as we will be dropping more out later
216 // Umm... these additions are a bit strange but they are needed.
218 p_nodes_min.X / MAP_BLOCKSIZE - 3,
219 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
220 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
222 p_nodes_max.X / MAP_BLOCKSIZE + 1,
223 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
224 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
226 u32 vertex_count = 0;
227 u32 meshbuffer_count = 0;
229 // For limiting number of mesh animations per frame
230 u32 mesh_animate_count = 0;
231 u32 mesh_animate_count_far = 0;
233 // Number of blocks in rendering range
234 u32 blocks_in_range = 0;
235 // Number of blocks occlusion culled
236 u32 blocks_occlusion_culled = 0;
237 // Number of blocks in rendering range but don't have a mesh
238 u32 blocks_in_range_without_mesh = 0;
239 // Blocks that had mesh that would have been drawn according to
240 // rendering range (if max blocks limit didn't kick in)
241 u32 blocks_would_have_drawn = 0;
242 // Blocks that were drawn and had a mesh
243 u32 blocks_drawn = 0;
244 // Blocks which had a corresponding meshbuffer for this pass
245 u32 blocks_had_pass_meshbuf = 0;
246 // Blocks from which stuff was actually drawn
247 u32 blocks_without_stuff = 0;
250 Collect a set of blocks for drawing
253 core::map<v3s16, MapBlock*> drawset;
256 ScopeProfiler sp(g_profiler, prefix+"collecting blocks for drawing", SPT_AVG);
258 for(core::map<v2s16, MapSector*>::Iterator
259 si = m_sectors.getIterator();
260 si.atEnd() == false; si++)
262 MapSector *sector = si.getNode()->getValue();
263 v2s16 sp = sector->getPos();
265 if(m_control.range_all == false)
267 if(sp.X < p_blocks_min.X
268 || sp.X > p_blocks_max.X
269 || sp.Y < p_blocks_min.Z
270 || sp.Y > p_blocks_max.Z)
274 core::list< MapBlock * > sectorblocks;
275 sector->getBlocks(sectorblocks);
278 Loop through blocks in sector
281 u32 sector_blocks_drawn = 0;
283 core::list< MapBlock * >::Iterator i;
284 for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++)
286 MapBlock *block = *i;
289 Compare block position to camera position, skip
290 if not seen on display
293 float range = 100000 * BS;
294 if(m_control.range_all == false)
295 range = m_control.wanted_range * BS;
298 if(isBlockInSight(block->getPos(), camera_position,
299 camera_direction, camera_fov,
305 // This is ugly (spherical distance limit?)
306 /*if(m_control.range_all == false &&
307 d - 0.5*BS*MAP_BLOCKSIZE > range)
313 Ignore if mesh doesn't exist
316 //JMutexAutoLock lock(block->mesh_mutex);
318 if(block->mesh == NULL){
319 blocks_in_range_without_mesh++;
328 // No occlusion culling when free_move is on and camera is
330 bool occlusion_culling_enabled = true;
331 if(g_settings->getBool("free_move")){
332 MapNode n = getNodeNoEx(cam_pos_nodes);
333 if(n.getContent() == CONTENT_IGNORE ||
334 nodemgr->get(n).solidness == 2)
335 occlusion_culling_enabled = false;
338 v3s16 cpn = block->getPos() * MAP_BLOCKSIZE;
339 cpn += v3s16(MAP_BLOCKSIZE/2, MAP_BLOCKSIZE/2, MAP_BLOCKSIZE/2);
342 float startoff = BS*1;
343 float endoff = -BS*MAP_BLOCKSIZE*1.42*1.42;
344 v3s16 spn = cam_pos_nodes + v3s16(0,0,0);
345 s16 bs2 = MAP_BLOCKSIZE/2 + 1;
346 u32 needed_count = 1;
348 occlusion_culling_enabled &&
349 isOccluded(this, spn, cpn + v3s16(0,0,0),
350 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
351 isOccluded(this, spn, cpn + v3s16(bs2,bs2,bs2),
352 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
353 isOccluded(this, spn, cpn + v3s16(bs2,bs2,-bs2),
354 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
355 isOccluded(this, spn, cpn + v3s16(bs2,-bs2,bs2),
356 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
357 isOccluded(this, spn, cpn + v3s16(bs2,-bs2,-bs2),
358 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
359 isOccluded(this, spn, cpn + v3s16(-bs2,bs2,bs2),
360 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
361 isOccluded(this, spn, cpn + v3s16(-bs2,bs2,-bs2),
362 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
363 isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,bs2),
364 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
365 isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,-bs2),
366 step, stepfac, startoff, endoff, needed_count, nodemgr)
369 blocks_occlusion_culled++;
373 // This block is in range. Reset usage timer.
374 block->resetUsageTimer();
376 // Limit block count in case of a sudden increase
377 blocks_would_have_drawn++;
378 if(blocks_drawn >= m_control.wanted_max_blocks
379 && m_control.range_all == false
380 && d > m_control.wanted_min_range * BS)
385 //JMutexAutoLock lock(block->mesh_mutex);
386 MapBlockMesh *mapBlockMesh = block->mesh;
387 // Pretty random but this should work somewhat nicely
388 bool faraway = d >= BS*50;
389 //bool faraway = d >= m_control.wanted_range * BS;
390 if(mapBlockMesh->isAnimationForced() ||
392 mesh_animate_count_far < (m_control.range_all ? 200 : 50))
394 bool animated = mapBlockMesh->animate(
400 mesh_animate_count++;
401 if(animated && faraway)
402 mesh_animate_count_far++;
406 mapBlockMesh->decreaseAnimationForceTimer();
411 drawset[block->getPos()] = block;
413 sector_blocks_drawn++;
416 } // foreach sectorblocks
418 if(sector_blocks_drawn != 0)
419 m_last_drawn_sectors[sp] = true;
424 Draw the selected MapBlocks
428 ScopeProfiler sp(g_profiler, prefix+"drawing blocks", SPT_AVG);
430 int timecheck_counter = 0;
431 for(core::map<v3s16, MapBlock*>::Iterator
432 i = drawset.getIterator();
433 i.atEnd() == false; i++)
437 if(timecheck_counter > 50)
439 timecheck_counter = 0;
441 if(time2 > time1 + 4)
443 infostream<<"ClientMap::renderMap(): "
444 "Rendering takes ages, returning."
451 MapBlock *block = i.getNode()->getValue();
454 Draw the faces of the block
457 //JMutexAutoLock lock(block->mesh_mutex);
459 MapBlockMesh *mapBlockMesh = block->mesh;
460 assert(mapBlockMesh);
462 scene::SMesh *mesh = mapBlockMesh->getMesh();
465 u32 c = mesh->getMeshBufferCount();
466 bool stuff_actually_drawn = false;
467 for(u32 i=0; i<c; i++)
469 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
470 const video::SMaterial& material = buf->getMaterial();
471 video::IMaterialRenderer* rnd =
472 driver->getMaterialRenderer(material.MaterialType);
473 bool transparent = (rnd && rnd->isTransparent());
474 // Render transparent on transparent pass and likewise.
475 if(transparent == is_transparent_pass)
477 if(buf->getVertexCount() == 0)
478 errorstream<<"Block ["<<analyze_block(block)
479 <<"] contains an empty meshbuf"<<std::endl;
481 This *shouldn't* hurt too much because Irrlicht
482 doesn't change opengl textures if the old
483 material has the same texture.
485 driver->setMaterial(buf->getMaterial());
486 driver->drawMeshBuffer(buf);
487 vertex_count += buf->getVertexCount();
489 stuff_actually_drawn = true;
492 if(stuff_actually_drawn)
493 blocks_had_pass_meshbuf++;
495 blocks_without_stuff++;
500 // Log only on solid pass because values are the same
501 if(pass == scene::ESNRP_SOLID){
502 g_profiler->avg("CM: blocks in range", blocks_in_range);
503 g_profiler->avg("CM: blocks occlusion culled", blocks_occlusion_culled);
504 if(blocks_in_range != 0)
505 g_profiler->avg("CM: blocks in range without mesh (frac)",
506 (float)blocks_in_range_without_mesh/blocks_in_range);
507 g_profiler->avg("CM: blocks drawn", blocks_drawn);
508 g_profiler->avg("CM: animated meshes", mesh_animate_count);
509 g_profiler->avg("CM: animated meshes (far)", mesh_animate_count_far);
512 g_profiler->avg(prefix+"vertices drawn", vertex_count);
513 if(blocks_had_pass_meshbuf != 0)
514 g_profiler->avg(prefix+"meshbuffers per block",
515 (float)meshbuffer_count / (float)blocks_had_pass_meshbuf);
516 if(blocks_drawn != 0)
517 g_profiler->avg(prefix+"empty blocks (frac)",
518 (float)blocks_without_stuff / blocks_drawn);
520 m_control.blocks_drawn = blocks_drawn;
521 m_control.blocks_would_have_drawn = blocks_would_have_drawn;
523 /*infostream<<"renderMap(): is_transparent_pass="<<is_transparent_pass
524 <<", rendered "<<vertex_count<<" vertices."<<std::endl;*/
527 static bool getVisibleBrightness(Map *map, v3f p0, v3f dir, float step,
528 float step_multiplier, float start_distance, float end_distance,
529 INodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
530 int *result, bool *sunlight_seen)
532 int brightness_sum = 0;
533 int brightness_count = 0;
534 float distance = start_distance;
537 pf += dir * distance;
539 bool nonlight_seen = false;
540 bool allow_allowing_non_sunlight_propagates = false;
541 bool allow_non_sunlight_propagates = false;
542 // Check content nearly at camera position
544 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
545 MapNode n = map->getNodeNoEx(p);
546 if(ndef->get(n).param_type == CPT_LIGHT &&
547 !ndef->get(n).sunlight_propagates)
548 allow_allowing_non_sunlight_propagates = true;
550 // If would start at CONTENT_IGNORE, start closer
552 v3s16 p = floatToInt(pf, BS);
553 MapNode n = map->getNodeNoEx(p);
554 if(n.getContent() == CONTENT_IGNORE){
556 pf = p0 + dir * 2*newd;
561 for(int i=0; distance < end_distance; i++){
564 step *= step_multiplier;
566 v3s16 p = floatToInt(pf, BS);
567 MapNode n = map->getNodeNoEx(p);
568 if(allow_allowing_non_sunlight_propagates && i == 0 &&
569 ndef->get(n).param_type == CPT_LIGHT &&
570 !ndef->get(n).sunlight_propagates){
571 allow_non_sunlight_propagates = true;
573 if(ndef->get(n).param_type != CPT_LIGHT ||
574 (!ndef->get(n).sunlight_propagates &&
575 !allow_non_sunlight_propagates)){
576 nonlight_seen = true;
582 if(distance >= sunlight_min_d && *sunlight_seen == false
583 && nonlight_seen == false)
584 if(n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
585 *sunlight_seen = true;
587 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
591 if(brightness_count == 0)
593 *result = brightness_sum / brightness_count;
594 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
595 <<(*result)<<std::endl;*/
599 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
600 int oldvalue, bool *sunlight_seen_result)
602 const bool debugprint = false;
603 INodeDefManager *ndef = m_gamedef->ndef();
604 static v3f z_directions[50] = {
607 static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
610 if(z_directions[0].X < -99){
611 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
612 z_directions[i] = v3f(
613 0.01 * myrand_range(-100, 100),
615 0.01 * myrand_range(-100, 100)
617 z_offsets[i] = 0.01 * myrand_range(0,100);
621 std::cerr<<"In goes "<<PP(m_camera_direction)<<", out comes ";
622 int sunlight_seen_count = 0;
623 float sunlight_min_d = max_d*0.8;
624 if(sunlight_min_d > 35*BS)
625 sunlight_min_d = 35*BS;
626 core::array<int> values;
627 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
628 v3f z_dir = z_directions[i];
630 core::CMatrix4<f32> a;
631 a.buildRotateFromTo(v3f(0,1,0), z_dir);
632 v3f dir = m_camera_direction;
637 step = max_d / 35 * 1.5;
638 float off = step * z_offsets[i];
639 bool sunlight_seen_now = false;
640 bool ok = getVisibleBrightness(this, m_camera_position, dir,
641 step, 1.0, max_d*0.6+off, max_d, ndef, daylight_factor,
643 &br, &sunlight_seen_now);
644 if(sunlight_seen_now)
645 sunlight_seen_count++;
648 values.push_back(br);
649 // Don't try too much if being in the sun is clear
650 if(sunlight_seen_count >= 20)
653 int brightness_sum = 0;
654 int brightness_count = 0;
656 u32 num_values_to_use = values.size();
657 if(num_values_to_use >= 10)
658 num_values_to_use -= num_values_to_use/2;
659 else if(num_values_to_use >= 7)
660 num_values_to_use -= num_values_to_use/3;
661 u32 first_value_i = (values.size() - num_values_to_use) / 2;
663 for(u32 i=0; i < first_value_i; i++)
664 std::cerr<<values[i]<<" ";
667 for(u32 i=first_value_i; i < first_value_i+num_values_to_use; i++){
669 std::cerr<<values[i]<<" ";
670 brightness_sum += values[i];
675 for(u32 i=first_value_i+num_values_to_use; i < values.size(); i++)
676 std::cerr<<values[i]<<" ";
679 if(brightness_count == 0){
680 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
681 if(ndef->get(n).param_type == CPT_LIGHT){
682 ret = decode_light(n.getLightBlend(daylight_factor, ndef));
685 //ret = blend_light(255, 0, daylight_factor);
688 /*float pre = (float)brightness_sum / (float)brightness_count;
694 ret = MYMAX(0, MYMIN(255, preint));*/
695 ret = brightness_sum / brightness_count;
698 std::cerr<<"Result: "<<ret<<" sunlight_seen_count="
699 <<sunlight_seen_count<<std::endl;
700 *sunlight_seen_result = (sunlight_seen_count > 0);
704 void ClientMap::renderPostFx()
706 INodeDefManager *nodemgr = m_gamedef->ndef();
708 // Sadly ISceneManager has no "post effects" render pass, in that case we
709 // could just register for that and handle it in renderMap().
711 m_camera_mutex.Lock();
712 v3f camera_position = m_camera_position;
713 m_camera_mutex.Unlock();
715 MapNode n = getNodeNoEx(floatToInt(camera_position, BS));
717 // - If the player is in a solid node, make everything black.
718 // - If the player is in liquid, draw a semi-transparent overlay.
719 const ContentFeatures& features = nodemgr->get(n);
720 video::SColor post_effect_color = features.post_effect_color;
721 if(features.solidness == 2 && g_settings->getBool("free_move") == false)
723 post_effect_color = video::SColor(255, 0, 0, 0);
725 if (post_effect_color.getAlpha() != 0)
727 // Draw a full-screen rectangle
728 video::IVideoDriver* driver = SceneManager->getVideoDriver();
729 v2u32 ss = driver->getScreenSize();
730 core::rect<s32> rect(0,0, ss.X, ss.Y);
731 driver->draw2DRectangle(post_effect_color, rect);
735 void ClientMap::PrintInfo(std::ostream &out)