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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
15 You should have received a copy of the GNU 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
33 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
38 MapDrawControl &control,
39 scene::ISceneNode* parent,
40 scene::ISceneManager* mgr,
43 Map(dout_client, gamedef),
44 scene::ISceneNode(parent, mgr, id),
47 m_camera_position(0,0,0),
48 m_camera_direction(0,0,1),
51 m_camera_mutex.Init();
52 assert(m_camera_mutex.IsInitialized());
54 m_box = core::aabbox3d<f32>(-BS*1000000,-BS*1000000,-BS*1000000,
55 BS*1000000,BS*1000000,BS*1000000);
58 ClientMap::~ClientMap()
60 /*JMutexAutoLock lock(mesh_mutex);
69 MapSector * ClientMap::emergeSector(v2s16 p2d)
71 DSTACK(__FUNCTION_NAME);
72 // Check that it doesn't exist already
74 return getSectorNoGenerate(p2d);
76 catch(InvalidPositionException &e)
81 ClientMapSector *sector = new ClientMapSector(this, p2d, m_gamedef);
84 //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
85 m_sectors.insert(p2d, sector);
92 void ClientMap::deSerializeSector(v2s16 p2d, std::istream &is)
94 DSTACK(__FUNCTION_NAME);
95 ClientMapSector *sector = NULL;
97 //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
99 core::map<v2s16, MapSector*>::Node *n = m_sectors.find(p2d);
103 sector = (ClientMapSector*)n->getValue();
104 assert(sector->getId() == MAPSECTOR_CLIENT);
108 sector = new ClientMapSector(this, p2d);
110 //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
111 m_sectors.insert(p2d, sector);
115 sector->deSerialize(is);
119 void ClientMap::OnRegisterSceneNode()
123 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
124 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
127 ISceneNode::OnRegisterSceneNode();
130 static bool isOccluded(Map *map, v3s16 p0, v3s16 p1, float step, float stepfac,
131 float start_off, float end_off, u32 needed_count, INodeDefManager *nodemgr)
133 float d0 = (float)BS * p0.getDistanceFrom(p1);
135 v3f uf = v3f(u0.X, u0.Y, u0.Z) * BS;
137 v3f p0f = v3f(p0.X, p0.Y, p0.Z) * BS;
139 for(float s=start_off; s<d0+end_off; s+=step){
140 v3f pf = p0f + uf * s;
141 v3s16 p = floatToInt(pf, BS);
142 MapNode n = map->getNodeNoEx(p);
143 bool is_transparent = false;
144 const ContentFeatures &f = nodemgr->get(n);
146 is_transparent = (f.visual_solidness != 2);
148 is_transparent = (f.solidness != 2);
151 if(count >= needed_count)
159 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
161 INodeDefManager *nodemgr = m_gamedef->ndef();
163 //m_dout<<DTIME<<"Rendering map..."<<std::endl;
164 DSTACK(__FUNCTION_NAME);
166 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
169 if(pass == scene::ESNRP_SOLID)
170 prefix = "CM: solid: ";
172 prefix = "CM: transparent: ";
175 This is called two times per frame, reset on the non-transparent one
177 if(pass == scene::ESNRP_SOLID)
179 m_last_drawn_sectors.clear();
183 Get time for measuring timeout.
185 Measuring time is very useful for long delays when the
186 machine is swapping a lot.
191 Get animation parameters
193 float animation_time = m_client->getAnimationTime();
194 int crack = m_client->getCrackLevel();
195 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
197 m_camera_mutex.Lock();
198 v3f camera_position = m_camera_position;
199 v3f camera_direction = m_camera_direction;
200 f32 camera_fov = m_camera_fov;
201 m_camera_mutex.Unlock();
204 Get all blocks and draw all visible ones
207 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
209 v3s16 box_nodes_d = m_control.wanted_range * v3s16(1,1,1);
211 v3s16 p_nodes_min = cam_pos_nodes - box_nodes_d;
212 v3s16 p_nodes_max = cam_pos_nodes + box_nodes_d;
214 // Take a fair amount as we will be dropping more out later
215 // Umm... these additions are a bit strange but they are needed.
217 p_nodes_min.X / MAP_BLOCKSIZE - 3,
218 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
219 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
221 p_nodes_max.X / MAP_BLOCKSIZE + 1,
222 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
223 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
225 u32 vertex_count = 0;
226 u32 meshbuffer_count = 0;
228 // For limiting number of mesh animations per frame
229 u32 mesh_animate_count = 0;
230 u32 mesh_animate_count_far = 0;
232 // Number of blocks in rendering range
233 u32 blocks_in_range = 0;
234 // Number of blocks occlusion culled
235 u32 blocks_occlusion_culled = 0;
236 // Number of blocks in rendering range but don't have a mesh
237 u32 blocks_in_range_without_mesh = 0;
238 // Blocks that had mesh that would have been drawn according to
239 // rendering range (if max blocks limit didn't kick in)
240 u32 blocks_would_have_drawn = 0;
241 // Blocks that were drawn and had a mesh
242 u32 blocks_drawn = 0;
243 // Blocks which had a corresponding meshbuffer for this pass
244 u32 blocks_had_pass_meshbuf = 0;
245 // Blocks from which stuff was actually drawn
246 u32 blocks_without_stuff = 0;
249 Collect a set of blocks for drawing
252 core::map<v3s16, MapBlock*> drawset;
255 ScopeProfiler sp(g_profiler, prefix+"collecting blocks for drawing", SPT_AVG);
257 for(core::map<v2s16, MapSector*>::Iterator
258 si = m_sectors.getIterator();
259 si.atEnd() == false; si++)
261 MapSector *sector = si.getNode()->getValue();
262 v2s16 sp = sector->getPos();
264 if(m_control.range_all == false)
266 if(sp.X < p_blocks_min.X
267 || sp.X > p_blocks_max.X
268 || sp.Y < p_blocks_min.Z
269 || sp.Y > p_blocks_max.Z)
273 core::list< MapBlock * > sectorblocks;
274 sector->getBlocks(sectorblocks);
277 Loop through blocks in sector
280 u32 sector_blocks_drawn = 0;
282 core::list< MapBlock * >::Iterator i;
283 for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++)
285 MapBlock *block = *i;
288 Compare block position to camera position, skip
289 if not seen on display
292 float range = 100000 * BS;
293 if(m_control.range_all == false)
294 range = m_control.wanted_range * BS;
297 if(isBlockInSight(block->getPos(), camera_position,
298 camera_direction, camera_fov,
304 // This is ugly (spherical distance limit?)
305 /*if(m_control.range_all == false &&
306 d - 0.5*BS*MAP_BLOCKSIZE > range)
312 Ignore if mesh doesn't exist
315 //JMutexAutoLock lock(block->mesh_mutex);
317 if(block->mesh == NULL){
318 blocks_in_range_without_mesh++;
327 // No occlusion culling when free_move is on and camera is
329 bool occlusion_culling_enabled = true;
330 if(g_settings->getBool("free_move")){
331 MapNode n = getNodeNoEx(cam_pos_nodes);
332 if(n.getContent() == CONTENT_IGNORE ||
333 nodemgr->get(n).solidness == 2)
334 occlusion_culling_enabled = false;
337 v3s16 cpn = block->getPos() * MAP_BLOCKSIZE;
338 cpn += v3s16(MAP_BLOCKSIZE/2, MAP_BLOCKSIZE/2, MAP_BLOCKSIZE/2);
341 float startoff = BS*1;
342 float endoff = -BS*MAP_BLOCKSIZE*1.42*1.42;
343 v3s16 spn = cam_pos_nodes + v3s16(0,0,0);
344 s16 bs2 = MAP_BLOCKSIZE/2 + 1;
345 u32 needed_count = 1;
347 occlusion_culling_enabled &&
348 isOccluded(this, spn, cpn + v3s16(0,0,0),
349 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
350 isOccluded(this, spn, cpn + v3s16(bs2,bs2,bs2),
351 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
352 isOccluded(this, spn, cpn + v3s16(bs2,bs2,-bs2),
353 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
354 isOccluded(this, spn, cpn + v3s16(bs2,-bs2,bs2),
355 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
356 isOccluded(this, spn, cpn + v3s16(bs2,-bs2,-bs2),
357 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
358 isOccluded(this, spn, cpn + v3s16(-bs2,bs2,bs2),
359 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
360 isOccluded(this, spn, cpn + v3s16(-bs2,bs2,-bs2),
361 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
362 isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,bs2),
363 step, stepfac, startoff, endoff, needed_count, nodemgr) &&
364 isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,-bs2),
365 step, stepfac, startoff, endoff, needed_count, nodemgr)
368 blocks_occlusion_culled++;
372 // This block is in range. Reset usage timer.
373 block->resetUsageTimer();
375 // Limit block count in case of a sudden increase
376 blocks_would_have_drawn++;
377 if(blocks_drawn >= m_control.wanted_max_blocks
378 && m_control.range_all == false
379 && d > m_control.wanted_min_range * BS)
384 //JMutexAutoLock lock(block->mesh_mutex);
385 MapBlockMesh *mapBlockMesh = block->mesh;
386 // Pretty random but this should work somewhat nicely
387 bool faraway = d >= BS*50;
388 //bool faraway = d >= m_control.wanted_range * BS;
389 if(mapBlockMesh->isAnimationForced() ||
391 mesh_animate_count_far < (m_control.range_all ? 200 : 50))
393 bool animated = mapBlockMesh->animate(
399 mesh_animate_count++;
400 if(animated && faraway)
401 mesh_animate_count_far++;
405 mapBlockMesh->decreaseAnimationForceTimer();
410 drawset[block->getPos()] = block;
412 sector_blocks_drawn++;
415 } // foreach sectorblocks
417 if(sector_blocks_drawn != 0)
418 m_last_drawn_sectors[sp] = true;
423 Draw the selected MapBlocks
427 ScopeProfiler sp(g_profiler, prefix+"drawing blocks", SPT_AVG);
429 int timecheck_counter = 0;
430 for(core::map<v3s16, MapBlock*>::Iterator
431 i = drawset.getIterator();
432 i.atEnd() == false; i++)
436 if(timecheck_counter > 50)
438 timecheck_counter = 0;
440 if(time2 > time1 + 4)
442 infostream<<"ClientMap::renderMap(): "
443 "Rendering takes ages, returning."
450 MapBlock *block = i.getNode()->getValue();
453 Draw the faces of the block
456 //JMutexAutoLock lock(block->mesh_mutex);
458 MapBlockMesh *mapBlockMesh = block->mesh;
459 assert(mapBlockMesh);
461 scene::SMesh *mesh = mapBlockMesh->getMesh();
464 u32 c = mesh->getMeshBufferCount();
465 bool stuff_actually_drawn = false;
466 for(u32 i=0; i<c; i++)
468 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
469 const video::SMaterial& material = buf->getMaterial();
470 video::IMaterialRenderer* rnd =
471 driver->getMaterialRenderer(material.MaterialType);
472 bool transparent = (rnd && rnd->isTransparent());
473 // Render transparent on transparent pass and likewise.
474 if(transparent == is_transparent_pass)
476 if(buf->getVertexCount() == 0)
477 errorstream<<"Block ["<<analyze_block(block)
478 <<"] contains an empty meshbuf"<<std::endl;
480 This *shouldn't* hurt too much because Irrlicht
481 doesn't change opengl textures if the old
482 material has the same texture.
484 driver->setMaterial(buf->getMaterial());
485 driver->drawMeshBuffer(buf);
486 vertex_count += buf->getVertexCount();
488 stuff_actually_drawn = true;
491 if(stuff_actually_drawn)
492 blocks_had_pass_meshbuf++;
494 blocks_without_stuff++;
499 // Log only on solid pass because values are the same
500 if(pass == scene::ESNRP_SOLID){
501 g_profiler->avg("CM: blocks in range", blocks_in_range);
502 g_profiler->avg("CM: blocks occlusion culled", blocks_occlusion_culled);
503 if(blocks_in_range != 0)
504 g_profiler->avg("CM: blocks in range without mesh (frac)",
505 (float)blocks_in_range_without_mesh/blocks_in_range);
506 g_profiler->avg("CM: blocks drawn", blocks_drawn);
507 g_profiler->avg("CM: animated meshes", mesh_animate_count);
508 g_profiler->avg("CM: animated meshes (far)", mesh_animate_count_far);
511 g_profiler->avg(prefix+"vertices drawn", vertex_count);
512 if(blocks_had_pass_meshbuf != 0)
513 g_profiler->avg(prefix+"meshbuffers per block",
514 (float)meshbuffer_count / (float)blocks_had_pass_meshbuf);
515 if(blocks_drawn != 0)
516 g_profiler->avg(prefix+"empty blocks (frac)",
517 (float)blocks_without_stuff / blocks_drawn);
519 m_control.blocks_drawn = blocks_drawn;
520 m_control.blocks_would_have_drawn = blocks_would_have_drawn;
522 /*infostream<<"renderMap(): is_transparent_pass="<<is_transparent_pass
523 <<", rendered "<<vertex_count<<" vertices."<<std::endl;*/
526 static bool getVisibleBrightness(Map *map, v3f p0, v3f dir, float step,
527 float step_multiplier, float start_distance, float end_distance,
528 INodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
529 int *result, bool *sunlight_seen)
531 int brightness_sum = 0;
532 int brightness_count = 0;
533 float distance = start_distance;
536 pf += dir * distance;
538 bool nonlight_seen = false;
539 bool allow_allowing_non_sunlight_propagates = false;
540 bool allow_non_sunlight_propagates = false;
541 // Check content nearly at camera position
543 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
544 MapNode n = map->getNodeNoEx(p);
545 if(ndef->get(n).param_type == CPT_LIGHT &&
546 !ndef->get(n).sunlight_propagates)
547 allow_allowing_non_sunlight_propagates = true;
549 // If would start at CONTENT_IGNORE, start closer
551 v3s16 p = floatToInt(pf, BS);
552 MapNode n = map->getNodeNoEx(p);
553 if(n.getContent() == CONTENT_IGNORE){
555 pf = p0 + dir * 2*newd;
560 for(int i=0; distance < end_distance; i++){
563 step *= step_multiplier;
565 v3s16 p = floatToInt(pf, BS);
566 MapNode n = map->getNodeNoEx(p);
567 if(allow_allowing_non_sunlight_propagates && i == 0 &&
568 ndef->get(n).param_type == CPT_LIGHT &&
569 !ndef->get(n).sunlight_propagates){
570 allow_non_sunlight_propagates = true;
572 if(ndef->get(n).param_type != CPT_LIGHT ||
573 (!ndef->get(n).sunlight_propagates &&
574 !allow_non_sunlight_propagates)){
575 nonlight_seen = true;
581 if(distance >= sunlight_min_d && *sunlight_seen == false
582 && nonlight_seen == false)
583 if(n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
584 *sunlight_seen = true;
586 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
590 if(brightness_count == 0)
592 *result = brightness_sum / brightness_count;
593 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
594 <<(*result)<<std::endl;*/
598 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
599 int oldvalue, bool *sunlight_seen_result)
601 const bool debugprint = false;
602 INodeDefManager *ndef = m_gamedef->ndef();
603 static v3f z_directions[50] = {
606 static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
609 if(z_directions[0].X < -99){
610 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
611 z_directions[i] = v3f(
612 0.01 * myrand_range(-100, 100),
614 0.01 * myrand_range(-100, 100)
616 z_offsets[i] = 0.01 * myrand_range(0,100);
620 std::cerr<<"In goes "<<PP(m_camera_direction)<<", out comes ";
621 int sunlight_seen_count = 0;
622 float sunlight_min_d = max_d*0.8;
623 if(sunlight_min_d > 35*BS)
624 sunlight_min_d = 35*BS;
625 core::array<int> values;
626 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
627 v3f z_dir = z_directions[i];
629 core::CMatrix4<f32> a;
630 a.buildRotateFromTo(v3f(0,1,0), z_dir);
631 v3f dir = m_camera_direction;
636 step = max_d / 35 * 1.5;
637 float off = step * z_offsets[i];
638 bool sunlight_seen_now = false;
639 bool ok = getVisibleBrightness(this, m_camera_position, dir,
640 step, 1.0, max_d*0.6+off, max_d, ndef, daylight_factor,
642 &br, &sunlight_seen_now);
643 if(sunlight_seen_now)
644 sunlight_seen_count++;
647 values.push_back(br);
648 // Don't try too much if being in the sun is clear
649 if(sunlight_seen_count >= 20)
652 int brightness_sum = 0;
653 int brightness_count = 0;
655 u32 num_values_to_use = values.size();
656 if(num_values_to_use >= 10)
657 num_values_to_use -= num_values_to_use/2;
658 else if(num_values_to_use >= 7)
659 num_values_to_use -= num_values_to_use/3;
660 u32 first_value_i = (values.size() - num_values_to_use) / 2;
662 for(u32 i=0; i < first_value_i; i++)
663 std::cerr<<values[i]<<" ";
666 for(u32 i=first_value_i; i < first_value_i+num_values_to_use; i++){
668 std::cerr<<values[i]<<" ";
669 brightness_sum += values[i];
674 for(u32 i=first_value_i+num_values_to_use; i < values.size(); i++)
675 std::cerr<<values[i]<<" ";
678 if(brightness_count == 0){
679 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
680 if(ndef->get(n).param_type == CPT_LIGHT){
681 ret = decode_light(n.getLightBlend(daylight_factor, ndef));
684 //ret = blend_light(255, 0, daylight_factor);
687 /*float pre = (float)brightness_sum / (float)brightness_count;
693 ret = MYMAX(0, MYMIN(255, preint));*/
694 ret = brightness_sum / brightness_count;
697 std::cerr<<"Result: "<<ret<<" sunlight_seen_count="
698 <<sunlight_seen_count<<std::endl;
699 *sunlight_seen_result = (sunlight_seen_count > 0);
703 void ClientMap::renderPostFx()
705 INodeDefManager *nodemgr = m_gamedef->ndef();
707 // Sadly ISceneManager has no "post effects" render pass, in that case we
708 // could just register for that and handle it in renderMap().
710 m_camera_mutex.Lock();
711 v3f camera_position = m_camera_position;
712 m_camera_mutex.Unlock();
714 MapNode n = getNodeNoEx(floatToInt(camera_position, BS));
716 // - If the player is in a solid node, make everything black.
717 // - If the player is in liquid, draw a semi-transparent overlay.
718 const ContentFeatures& features = nodemgr->get(n);
719 video::SColor post_effect_color = features.post_effect_color;
720 if(features.solidness == 2 && g_settings->getBool("free_move") == false)
722 post_effect_color = video::SColor(255, 0, 0, 0);
724 if (post_effect_color.getAlpha() != 0)
726 // Draw a full-screen rectangle
727 video::IVideoDriver* driver = SceneManager->getVideoDriver();
728 v2u32 ss = driver->getScreenSize();
729 core::rect<s32> rect(0,0, ss.X, ss.Y);
730 driver->draw2DRectangle(post_effect_color, rect);
734 void ClientMap::PrintInfo(std::ostream &out)