sceneCullingState.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "scene/culling/sceneCullingState.h"
  24. #include "scene/sceneManager.h"
  25. #include "scene/sceneObject.h"
  26. #include "scene/zones/sceneZoneSpace.h"
  27. #include "math/mathUtils.h"
  28. #include "platform/profiler.h"
  29. #include "terrain/terrData.h"
  30. #include "util/tempAlloc.h"
  31. #include "gfx/sim/debugDraw.h"
  32. extern bool gEditingMission;
  33. bool SceneCullingState::smDisableTerrainOcclusion = false;
  34. bool SceneCullingState::smDisableZoneCulling = false;
  35. U32 SceneCullingState::smMaxOccludersPerZone = 4;
  36. F32 SceneCullingState::smOccluderMinWidthPercentage = 0.1f;
  37. F32 SceneCullingState::smOccluderMinHeightPercentage = 0.1f;
  38. //-----------------------------------------------------------------------------
  39. SceneCullingState::SceneCullingState( SceneManager* sceneManager, const SceneCameraState& viewState )
  40. : mSceneManager( sceneManager ),
  41. mCameraState( viewState ),
  42. mDisableZoneCulling( smDisableZoneCulling ),
  43. mDisableTerrainOcclusion( smDisableTerrainOcclusion )
  44. {
  45. AssertFatal( sceneManager->getZoneManager(), "SceneCullingState::SceneCullingState - SceneManager must have a zone manager!" );
  46. VECTOR_SET_ASSOCIATION( mZoneStates );
  47. VECTOR_SET_ASSOCIATION( mAddedOccluderObjects );
  48. // Allocate zone states.
  49. const U32 numZones = sceneManager->getZoneManager()->getNumZones();
  50. mZoneStates.setSize( numZones );
  51. dMemset( mZoneStates.address(), 0, sizeof( SceneZoneCullingState ) * numZones );
  52. // Allocate the zone visibility flags.
  53. mZoneVisibilityFlags.setSize( numZones );
  54. mZoneVisibilityFlags.clear();
  55. // Construct the root culling volume from
  56. // the camera's view frustum. Omit the frustum's
  57. // near and far plane so we don't test it repeatedly.
  58. const Frustum& frustum = mCameraState.getFrustum();
  59. PlaneF* planes = allocateData< PlaneF >( 4 );
  60. planes[ 0 ] = frustum.getPlanes()[ Frustum::PlaneLeft ];
  61. planes[ 1 ] = frustum.getPlanes()[ Frustum::PlaneRight ];
  62. planes[ 2 ] = frustum.getPlanes()[ Frustum::PlaneTop];
  63. planes[ 3 ] = frustum.getPlanes()[ Frustum::PlaneBottom ];
  64. mRootVolume = SceneCullingVolume(
  65. SceneCullingVolume::Includer,
  66. PlaneSetF( planes, 4 )
  67. );
  68. }
  69. //-----------------------------------------------------------------------------
  70. bool SceneCullingState::isWithinVisibleZone( SceneObject* object ) const
  71. {
  72. for( SceneObject::ZoneRef* ref = object->_getZoneRefHead();
  73. ref != NULL; ref = ref->nextInObj )
  74. if( mZoneVisibilityFlags.test( ref->zone ) )
  75. return true;
  76. return false;
  77. }
  78. //-----------------------------------------------------------------------------
  79. void SceneCullingState::addOccluder( SceneObject* object )
  80. {
  81. PROFILE_SCOPE( SceneCullingState_addOccluder );
  82. // If the occluder is itself occluded, don't add it.
  83. //
  84. // NOTE: We do allow near plane intersections here. Silhouette extraction
  85. // should take that into account.
  86. if( cullObjects( &object, 1, DontCullRenderDisabled ) != 1 )
  87. return;
  88. // If the occluder has already been added, do nothing. Check this
  89. // after the culling check since the same occluder can be added by
  90. // two separate zones and not be visible in one yet be visible in the
  91. // other.
  92. if( mAddedOccluderObjects.contains( object ) )
  93. return;
  94. mAddedOccluderObjects.push_back( object );
  95. // Let the object build a silhouette. If it doesn't
  96. // return one, abort.
  97. Vector< Point3F > silhouette;
  98. object->buildSilhouette( getCameraState(), silhouette );
  99. if( silhouette.empty() || silhouette.size() < 3 )
  100. return;
  101. // Generate the culling volume.
  102. SceneCullingVolume volume;
  103. if( !createCullingVolume(
  104. silhouette.address(),
  105. silhouette.size(),
  106. SceneCullingVolume::Occluder,
  107. volume ) )
  108. return;
  109. // Add the frustum to all zones that the object is assigned to.
  110. for( SceneObject::ZoneRef* ref = object->_getZoneRefHead(); ref != NULL; ref = ref->nextInObj )
  111. addCullingVolumeToZone( ref->zone, volume );
  112. }
  113. //-----------------------------------------------------------------------------
  114. bool SceneCullingState::addCullingVolumeToZone( U32 zoneId, const SceneCullingVolume& volume )
  115. {
  116. PROFILE_SCOPE( SceneCullingState_addCullingVolumeToZone );
  117. AssertFatal( zoneId < mZoneStates.size(), "SceneCullingState::addCullingVolumeToZone - Zone ID out of range" );
  118. SceneZoneCullingState& zoneState = mZoneStates[ zoneId ];
  119. // [rene, 07-Apr-10] I previously used to attempt to merge things here and detect whether
  120. // the visibility state of the zone has changed at all. Since we allow polyhedra to be
  121. // degenerate here and since polyhedra cannot be merged easily like frustums, I have opted
  122. // to remove this for now. I'm also convinced that with the current traversal system it
  123. // adds little benefit.
  124. // Link the volume to the zone state.
  125. typedef SceneZoneCullingState::CullingVolumeLink LinkType;
  126. LinkType* link = reinterpret_cast< LinkType* >( allocateData( sizeof( LinkType ) ) );
  127. link->mVolume = volume;
  128. link->mNext = zoneState.mCullingVolumes;
  129. zoneState.mCullingVolumes = link;
  130. if( volume.isOccluder() )
  131. zoneState.mHaveOccluders = true;
  132. else
  133. zoneState.mHaveIncluders = true;
  134. // Mark sorting state as dirty.
  135. zoneState.mHaveSortedVolumes = false;
  136. // Set the visibility flag for the zone.
  137. if( volume.isIncluder() )
  138. mZoneVisibilityFlags.set( zoneId );
  139. return true;
  140. }
  141. //-----------------------------------------------------------------------------
  142. bool SceneCullingState::addCullingVolumeToZone( U32 zoneId, SceneCullingVolume::Type type, const AnyPolyhedron& polyhedron )
  143. {
  144. // Allocate space on our chunker.
  145. const U32 numPlanes = polyhedron.getNumPlanes();
  146. PlaneF* planes = allocateData< PlaneF >( numPlanes );
  147. // Copy the planes over.
  148. dMemcpy( planes, polyhedron.getPlanes(), numPlanes * sizeof( planes[ 0 ] ) );
  149. // Create a culling volume.
  150. SceneCullingVolume volume(
  151. type,
  152. PlaneSetF( planes, numPlanes )
  153. );
  154. // And add it.
  155. return addCullingVolumeToZone( zoneId, volume );
  156. }
  157. //-----------------------------------------------------------------------------
  158. bool SceneCullingState::createCullingVolume( const Point3F* vertices, U32 numVertices, SceneCullingVolume::Type type, SceneCullingVolume& outVolume )
  159. {
  160. const Point3F& viewPos = getCameraState().getViewPosition();
  161. const Point3F& viewDir = getCameraState().getViewDirection();
  162. const bool isOrtho = getFrustum().isOrtho();
  163. //TODO: check if we need to handle penetration of the near plane for occluders specially
  164. // Allocate space for the clipping planes we generate. Assume the worst case
  165. // of every edge generating a plane and, for includers, all edges meeting at
  166. // steep angles so we need to insert extra planes (the latter is not possible,
  167. // of course, but it makes things less complicated here). For occluders, add
  168. // an extra plane for the near cap.
  169. const U32 maxPlanes = ( type == SceneCullingVolume::Occluder ? numVertices + 1 : numVertices * 2 );
  170. PlaneF* planes = allocateData< PlaneF >( maxPlanes );
  171. // Keep track of the world-space bounds of the polygon. We use this later
  172. // to derive some metrics.
  173. Box3F wsPolyBounds;
  174. wsPolyBounds.minExtents = Point3F( TypeTraits< F32 >::MAX, TypeTraits< F32 >::MAX, TypeTraits< F32 >::MAX );
  175. wsPolyBounds.maxExtents = Point3F( TypeTraits< F32 >::MIN, TypeTraits< F32 >::MIN, TypeTraits< F32 >::MIN );
  176. // For occluders, also keep track of the nearest, and two farthest silhouette points. We use
  177. // this later to construct a near capping plane.
  178. F32 minVertexDistanceSquared = TypeTraits< F32 >::MAX;
  179. U32 leastDistantVert = 0;
  180. F32 maxVertexDistancesSquared[ 2 ] = { TypeTraits< F32 >::MIN, TypeTraits< F32 >::MIN };
  181. U32 mostDistantVertices[ 2 ] = { 0, 0 };
  182. // Generate the extrusion volume. For orthographic projections, extrude
  183. // parallel to the view direction whereas for parallel projections, extrude
  184. // from the viewpoint.
  185. U32 numPlanes = 0;
  186. U32 lastVertex = numVertices - 1;
  187. bool invert = false;
  188. for( U32 i = 0; i < numVertices; lastVertex = i, ++ i )
  189. {
  190. AssertFatal( numPlanes < maxPlanes, "SceneCullingState::createCullingVolume - Did not allocate enough planes!" );
  191. const Point3F& v1 = vertices[ i ];
  192. const Point3F& v2 = vertices[ lastVertex ];
  193. // Keep track of bounds.
  194. wsPolyBounds.minExtents.setMin( v1 );
  195. wsPolyBounds.maxExtents.setMax( v1 );
  196. // Skip the edge if it's length is really short.
  197. const Point3F edgeVector = v2 - v1;
  198. const F32 edgeVectorLenSquared = edgeVector.lenSquared();
  199. if( edgeVectorLenSquared < 0.025f )
  200. continue;
  201. //TODO: might need to do additional checks here for non-planar polygons used by occluders
  202. //TODO: test for colinearity of edge vector with view vector (occluders only)
  203. // Create a plane for the edge.
  204. if( isOrtho )
  205. {
  206. // Compute a plane through the two edge vertices and one
  207. // of the vertices extended along the view direction.
  208. if( !invert )
  209. planes[ numPlanes ] = PlaneF( v1, v1 + viewDir, v2 );
  210. else
  211. planes[ numPlanes ] = PlaneF( v2, v1 + viewDir, v1 );
  212. }
  213. else
  214. {
  215. // Compute a plane going through the viewpoint and the two
  216. // edge vertices.
  217. if( !invert )
  218. planes[ numPlanes ] = PlaneF( v1, viewPos, v2 );
  219. else
  220. planes[ numPlanes ] = PlaneF( v2, viewPos, v1 );
  221. }
  222. numPlanes ++;
  223. // If this is the first plane that we have created, find out whether
  224. // the vertex ordering is giving us the plane orientations that we want
  225. // (facing inside). If not, invert vertex order from now on.
  226. if( numPlanes == 1 )
  227. {
  228. Point3F center( 0, 0, 0 );
  229. for( U32 n = 0; n < numVertices; ++ n )
  230. center += vertices[n];
  231. center /= numVertices;
  232. if( planes[numPlanes - 1].whichSide( center ) == PlaneF::Back )
  233. {
  234. invert = true;
  235. planes[ numPlanes - 1 ].invert();
  236. }
  237. }
  238. // For occluders, keep tabs of the nearest, and two farthest vertices.
  239. if( type == SceneCullingVolume::Occluder )
  240. {
  241. const F32 distSquared = ( v1 - viewPos ).lenSquared();
  242. if( distSquared < minVertexDistanceSquared )
  243. {
  244. minVertexDistanceSquared = distSquared;
  245. leastDistantVert = i;
  246. }
  247. if( distSquared > maxVertexDistancesSquared[ 0 ] )
  248. {
  249. // Move 0 to 1.
  250. maxVertexDistancesSquared[ 1 ] = maxVertexDistancesSquared[ 0 ];
  251. mostDistantVertices[ 1 ] = mostDistantVertices[ 0 ];
  252. // Replace 0.
  253. maxVertexDistancesSquared[ 0 ] = distSquared;
  254. mostDistantVertices[ 0 ] = i;
  255. }
  256. else if( distSquared > maxVertexDistancesSquared[ 1 ] )
  257. {
  258. // Replace 1.
  259. maxVertexDistancesSquared[ 1 ] = distSquared;
  260. mostDistantVertices[ 1 ] = i;
  261. }
  262. }
  263. }
  264. // If the extrusion produced no useful result, abort.
  265. if( numPlanes < 3 )
  266. return false;
  267. // For includers, test the angle of the edges at the current vertex.
  268. // If too steep, add an extra plane to improve culling efficiency.
  269. if( false )//type == SceneCullingVolume::Includer )
  270. {
  271. const U32 numOriginalPlanes = numPlanes;
  272. U32 lastPlaneIndex = numPlanes - 1;
  273. for( U32 i = 0; i < numOriginalPlanes; lastPlaneIndex = i, ++ i )
  274. {
  275. const PlaneF& currentPlane = planes[ i ];
  276. const PlaneF& lastPlane = planes[ lastPlaneIndex ];
  277. // Compute the cosine of the angle between the two plane normals.
  278. const F32 cosAngle = mFabs( mDot( currentPlane, lastPlane ) );
  279. // The planes meet at increasingly steep angles the more they point
  280. // in opposite directions, i.e the closer the angle of their normals
  281. // is to 180 degrees. Skip any two planes that don't get near that.
  282. if( cosAngle > 0.1f )
  283. continue;
  284. //TODO
  285. const Point3F addNormals = currentPlane + lastPlane;
  286. const Point3F crossNormals = mCross( currentPlane, lastPlane );
  287. Point3F newNormal = currentPlane + lastPlane;//addNormals - mDot( addNormals, crossNormals ) * crossNormals;
  288. //
  289. planes[ numPlanes ] = PlaneF( currentPlane.getPosition(), newNormal );
  290. numPlanes ++;
  291. }
  292. }
  293. // Compute the metrics of the culling volume in relation to the view frustum.
  294. //
  295. // For this, we are short-circuiting things slightly. The correct way (other than doing
  296. // full screen projections) would be to transform all the polygon points into camera
  297. // space, lay an AABB around those points, and then find the X and Z extents on the near plane.
  298. //
  299. // However, while not as accurate, a faster way is to just project the axial vectors
  300. // of the bounding box onto both the camera right and up vector. This gives us a rough
  301. // estimate of the camera-space size of the polygon we're looking at.
  302. const MatrixF& cameraTransform = getCameraState().getViewWorldMatrix();
  303. const Point3F cameraRight = cameraTransform.getRightVector();
  304. const Point3F cameraUp = cameraTransform.getUpVector();
  305. const Point3F wsPolyBoundsExtents = wsPolyBounds.getExtents();
  306. F32 widthEstimate =
  307. getMax( mFabs( wsPolyBoundsExtents.x * cameraRight.x ),
  308. getMax( mFabs( wsPolyBoundsExtents.y * cameraRight.y ),
  309. mFabs( wsPolyBoundsExtents.z * cameraRight.z ) ) );
  310. F32 heightEstimate =
  311. getMax( mFabs( wsPolyBoundsExtents.x * cameraUp.x ),
  312. getMax( mFabs( wsPolyBoundsExtents.y * cameraUp.y ),
  313. mFabs( wsPolyBoundsExtents.z * cameraUp.z ) ) );
  314. // If the current camera is a perspective one, divide the two estimates
  315. // by the distance of the nearest bounding box vertex to the camera
  316. // to account for perspective distortion.
  317. if( !isOrtho )
  318. {
  319. const Point3F nearestVertex = wsPolyBounds.computeVertex(
  320. Box3F::getPointIndexFromOctant( - viewDir )
  321. );
  322. const F32 distance = ( nearestVertex - viewPos ).len();
  323. widthEstimate /= distance;
  324. heightEstimate /= distance;
  325. }
  326. // If we are creating an occluder, check to see if the estimates fit
  327. // our minimum requirements.
  328. if( type == SceneCullingVolume::Occluder )
  329. {
  330. const F32 widthEstimatePercentage = widthEstimate / getFrustum().getWidth();
  331. const F32 heightEstimatePercentage = heightEstimate / getFrustum().getHeight();
  332. if( widthEstimatePercentage < smOccluderMinWidthPercentage ||
  333. heightEstimatePercentage < smOccluderMinHeightPercentage )
  334. return false; // Reject.
  335. }
  336. // Use the area estimate as the volume's sort point.
  337. const F32 sortPoint = widthEstimate * heightEstimate;
  338. // Finally, if it's an occluder, compute a near cap. The near cap prevents objects
  339. // in front of the occluder from testing positive. The same could be achieved by
  340. // manually comparing distances before testing objects but since that would amount
  341. // to the same checks the plane/AABB tests do, it's easier to just add another plane.
  342. // Additionally, it gives the benefit of being able to create more precise culling
  343. // results by angling the plane.
  344. //NOTE: Could consider adding a near cap for includers too when generating a volume
  345. // for the outdoor zone as that may prevent quite a bit of space from being included.
  346. // However, given that this space will most likely just be filled with interior
  347. // stuff anyway, it's probably not worth it.
  348. if( type == SceneCullingVolume::Occluder )
  349. {
  350. const U32 nearCapIndex = numPlanes;
  351. planes[ nearCapIndex ] = PlaneF(
  352. vertices[ mostDistantVertices[ 0 ] ],
  353. vertices[ mostDistantVertices[ 1 ] ],
  354. vertices[ leastDistantVert ] );
  355. // Invert the plane, if necessary.
  356. if( planes[ nearCapIndex ].whichSide( viewPos ) == PlaneF::Front )
  357. planes[ nearCapIndex ].invert();
  358. numPlanes ++;
  359. }
  360. // Create the volume from the planes.
  361. outVolume = SceneCullingVolume(
  362. type,
  363. PlaneSetF( planes, numPlanes )
  364. );
  365. outVolume.setSortPoint( sortPoint );
  366. // Done.
  367. return true;
  368. }
  369. //-----------------------------------------------------------------------------
  370. namespace {
  371. struct ZoneArrayIterator
  372. {
  373. U32 mCurrent;
  374. U32 mNumZones;
  375. const U32* mZones;
  376. ZoneArrayIterator( const U32* zones, U32 numZones )
  377. : mCurrent( 0 ),
  378. mNumZones( numZones ),
  379. mZones( zones ) {}
  380. bool isValid() const
  381. {
  382. return ( mCurrent < mNumZones );
  383. }
  384. ZoneArrayIterator& operator ++()
  385. {
  386. mCurrent ++;
  387. return *this;
  388. }
  389. U32 operator *() const
  390. {
  391. return mZones[ mCurrent ];
  392. }
  393. };
  394. }
  395. template< typename T, typename Iter >
  396. inline SceneZoneCullingState::CullingTestResult SceneCullingState::_testOccludersOnly( const T& bounds, Iter zoneIter ) const
  397. {
  398. // Test the culling states of all zones that the object
  399. // is assigned to.
  400. for( ; zoneIter.isValid(); ++ zoneIter )
  401. {
  402. const SceneZoneCullingState& zoneState = getZoneState( *zoneIter );
  403. // Skip zone if there are no occluders.
  404. if( !zoneState.hasOccluders() )
  405. continue;
  406. // If the object's world bounds overlaps any of the volumes
  407. // for this zone, it's rendered.
  408. if( zoneState.testVolumes( bounds, true ) == SceneZoneCullingState::CullingTestPositiveByOcclusion )
  409. return SceneZoneCullingState::CullingTestPositiveByOcclusion;
  410. }
  411. return SceneZoneCullingState::CullingTestNegative;
  412. }
  413. template< typename T, typename Iter >
  414. inline SceneZoneCullingState::CullingTestResult SceneCullingState::_test( const T& bounds, Iter zoneIter,
  415. const PlaneF& nearPlane, const PlaneF& farPlane ) const
  416. {
  417. // Defer test of near and far plane until we've hit a zone
  418. // which actually has visible space. This prevents us from
  419. // doing near/far tests on objects that were included in the
  420. // potential render list but aren't actually in any visible
  421. // zone.
  422. bool haveTestedNearAndFar = false;
  423. // Test the culling states of all zones that the object
  424. // is assigned to.
  425. for( ; zoneIter.isValid(); ++ zoneIter )
  426. {
  427. const SceneZoneCullingState& zoneState = getZoneState( *zoneIter );
  428. // Skip zone if there are no positive culling volumes.
  429. if( !zoneState.hasIncluders() )
  430. continue;
  431. // If we haven't tested the near and far plane yet, do so
  432. // now.
  433. if( !haveTestedNearAndFar )
  434. {
  435. // Test near plane.
  436. PlaneF::Side nearSide = nearPlane.whichSide( bounds );
  437. if( nearSide == PlaneF::Back )
  438. return SceneZoneCullingState::CullingTestNegative;
  439. // Test far plane.
  440. PlaneF::Side farSide = farPlane.whichSide( bounds );
  441. if( farSide == PlaneF::Back )
  442. return SceneZoneCullingState::CullingTestNegative;
  443. haveTestedNearAndFar = true;
  444. }
  445. // If the object's world bounds overlaps any of the volumes
  446. // for this zone, it's rendered.
  447. SceneZoneCullingState::CullingTestResult result = zoneState.testVolumes( bounds );
  448. if( result == SceneZoneCullingState::CullingTestPositiveByInclusion )
  449. return result;
  450. else if( result == SceneZoneCullingState::CullingTestPositiveByOcclusion )
  451. return result;
  452. }
  453. return SceneZoneCullingState::CullingTestNegative;
  454. }
  455. //-----------------------------------------------------------------------------
  456. template< bool OCCLUDERS_ONLY, typename T >
  457. inline SceneZoneCullingState::CullingTestResult SceneCullingState::_test( const T& bounds, const U32* zones, U32 numZones ) const
  458. {
  459. // If zone culling is disabled, only test against
  460. // the root frustum.
  461. if( disableZoneCulling() )
  462. {
  463. if( !OCCLUDERS_ONLY && !getFrustum().isCulled( bounds ) )
  464. return SceneZoneCullingState::CullingTestPositiveByInclusion;
  465. return SceneZoneCullingState::CullingTestNegative;
  466. }
  467. // Otherwise test each of the zones.
  468. if( OCCLUDERS_ONLY )
  469. {
  470. return _testOccludersOnly(
  471. bounds,
  472. ZoneArrayIterator( zones, numZones )
  473. );
  474. }
  475. else
  476. {
  477. const PlaneF* frustumPlanes = getFrustum().getPlanes();
  478. return _test(
  479. bounds,
  480. ZoneArrayIterator( zones, numZones ),
  481. frustumPlanes[ Frustum::PlaneNear ],
  482. frustumPlanes[ Frustum::PlaneFar ]
  483. );
  484. }
  485. }
  486. //-----------------------------------------------------------------------------
  487. bool SceneCullingState::isCulled( const Box3F& aabb, const U32* zones, U32 numZones ) const
  488. {
  489. SceneZoneCullingState::CullingTestResult result = _test< false >( aabb, zones, numZones );
  490. return ( result == SceneZoneCullingState::CullingTestNegative ||
  491. result == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  492. }
  493. //-----------------------------------------------------------------------------
  494. bool SceneCullingState::isCulled( const OrientedBox3F& obb, const U32* zones, U32 numZones ) const
  495. {
  496. SceneZoneCullingState::CullingTestResult result = _test< false >( obb, zones, numZones );
  497. return ( result == SceneZoneCullingState::CullingTestNegative ||
  498. result == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  499. }
  500. //-----------------------------------------------------------------------------
  501. bool SceneCullingState::isCulled( const SphereF& sphere, const U32* zones, U32 numZones ) const
  502. {
  503. SceneZoneCullingState::CullingTestResult result = _test< false >( sphere, zones, numZones );
  504. return ( result == SceneZoneCullingState::CullingTestNegative ||
  505. result == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  506. }
  507. //-----------------------------------------------------------------------------
  508. bool SceneCullingState::isOccluded( SceneObject* object ) const
  509. {
  510. if( disableZoneCulling() )
  511. return false;
  512. CullingTestResult result = _testOccludersOnly(
  513. object->getWorldBox(),
  514. SceneObject::ObjectZonesIterator( object )
  515. );
  516. return ( result == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  517. }
  518. //-----------------------------------------------------------------------------
  519. bool SceneCullingState::isOccluded( const Box3F& aabb, const U32* zones, U32 numZones ) const
  520. {
  521. return ( _test< true >( aabb, zones, numZones ) == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  522. }
  523. //-----------------------------------------------------------------------------
  524. bool SceneCullingState::isOccluded( const OrientedBox3F& obb, const U32* zones, U32 numZones ) const
  525. {
  526. return ( _test< true >( obb, zones, numZones ) == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  527. }
  528. //-----------------------------------------------------------------------------
  529. bool SceneCullingState::isOccluded( const SphereF& sphere, const U32* zones, U32 numZones ) const
  530. {
  531. return ( _test< true >( sphere, zones, numZones ) == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  532. }
  533. //-----------------------------------------------------------------------------
  534. U32 SceneCullingState::cullObjects( SceneObject** objects, U32 numObjects, U32 cullOptions ) const
  535. {
  536. PROFILE_SCOPE( SceneCullingState_cullObjects );
  537. U32 numRemainingObjects = 0;
  538. // We test near and far planes separately in order to not do the tests
  539. // repeatedly, so fetch the planes now.
  540. const PlaneF& nearPlane = getFrustum().getPlanes()[ Frustum::PlaneNear ];
  541. const PlaneF& farPlane = getFrustum().getPlanes()[ Frustum::PlaneFar ];
  542. for( U32 i = 0; i < numObjects; ++ i )
  543. {
  544. SceneObject* object = objects[ i ];
  545. bool isCulled = true;
  546. // If we should respect editor overrides, test that now.
  547. if( !( cullOptions & CullEditorOverrides ) &&
  548. gEditingMission &&
  549. ( ( object->isCullingDisabledInEditor() && object->isRenderEnabled() ) || object->isSelected() ) )
  550. {
  551. isCulled = false;
  552. }
  553. // If the object is render-disabled, it gets culled. The only
  554. // way around this is the editor override above.
  555. else if( !( cullOptions & DontCullRenderDisabled ) &&
  556. !object->isRenderEnabled() )
  557. {
  558. isCulled = true;
  559. }
  560. // Global bounds objects are never culled. Note that this means
  561. // that if these objects are to respect zoning, they need to manually
  562. // trigger the respective culling checks for whatever they want to
  563. // batch.
  564. else if( object->isGlobalBounds() )
  565. isCulled = false;
  566. // If terrain occlusion checks are enabled, run them now.
  567. else if( !mDisableTerrainOcclusion &&
  568. object->getWorldBox().minExtents.x > -1e5 &&
  569. isOccludedByTerrain( object ) )
  570. {
  571. // Occluded by terrain.
  572. isCulled = true;
  573. }
  574. // If the object shouldn't be subjected to more fine-grained culling
  575. // or if zone culling is disabled, just test against the root frustum.
  576. else if( !( object->getTypeMask() & CULLING_INCLUDE_TYPEMASK ) ||
  577. ( object->getTypeMask() & CULLING_EXCLUDE_TYPEMASK ) ||
  578. disableZoneCulling() )
  579. {
  580. isCulled = getFrustum().isCulled( object->getWorldBox() );
  581. }
  582. // Go through the zones that the object is assigned to and
  583. // test the object against the frustums of each of the zones.
  584. else
  585. {
  586. CullingTestResult result = _test(
  587. object->getWorldBox(),
  588. SceneObject::ObjectZonesIterator( object ),
  589. nearPlane,
  590. farPlane
  591. );
  592. isCulled = ( result == SceneZoneCullingState::CullingTestNegative ||
  593. result == SceneZoneCullingState::CullingTestPositiveByOcclusion );
  594. }
  595. if( !isCulled )
  596. objects[ numRemainingObjects ++ ] = object;
  597. }
  598. return numRemainingObjects;
  599. }
  600. //-----------------------------------------------------------------------------
  601. bool SceneCullingState::isOccludedByTerrain( SceneObject* object ) const
  602. {
  603. PROFILE_SCOPE( SceneCullingState_isOccludedByTerrain );
  604. // Don't try to occlude globally bounded objects.
  605. if( object->isGlobalBounds() )
  606. return false;
  607. const Vector< SceneObject* >& terrains = getSceneManager()->getContainer()->getTerrains();
  608. const U32 numTerrains = terrains.size();
  609. for( U32 terrainIdx = 0; terrainIdx < numTerrains; ++ terrainIdx )
  610. {
  611. TerrainBlock* terrain = dynamic_cast< TerrainBlock* >( terrains[ terrainIdx ] );
  612. if( !terrain )
  613. continue;
  614. Point3F localCamPos = getCameraState().getViewPosition();
  615. terrain->getWorldTransform().mulP( localCamPos );
  616. F32 height;
  617. terrain->getHeight( Point2F( localCamPos.x, localCamPos.y ), &height );
  618. bool aboveTerrain = ( height <= localCamPos.z );
  619. // Don't occlude if we're below the terrain. This prevents problems when
  620. // looking out from underground bases...
  621. if( !aboveTerrain )
  622. continue;
  623. const Box3F& oBox = object->getObjBox();
  624. F32 minSide = getMin(oBox.len_x(), oBox.len_y());
  625. if (minSide > 85.0f)
  626. continue;
  627. const Box3F& rBox = object->getWorldBox();
  628. Point3F ul(rBox.minExtents.x, rBox.minExtents.y, rBox.maxExtents.z);
  629. Point3F ur(rBox.minExtents.x, rBox.maxExtents.y, rBox.maxExtents.z);
  630. Point3F ll(rBox.maxExtents.x, rBox.minExtents.y, rBox.maxExtents.z);
  631. Point3F lr(rBox.maxExtents.x, rBox.maxExtents.y, rBox.maxExtents.z);
  632. terrain->getWorldTransform().mulP(ul);
  633. terrain->getWorldTransform().mulP(ur);
  634. terrain->getWorldTransform().mulP(ll);
  635. terrain->getWorldTransform().mulP(lr);
  636. Point3F xBaseL0_s = ul - localCamPos;
  637. Point3F xBaseL0_e = lr - localCamPos;
  638. Point3F xBaseL1_s = ur - localCamPos;
  639. Point3F xBaseL1_e = ll - localCamPos;
  640. static F32 checkPoints[3] = {0.75, 0.5, 0.25};
  641. RayInfo rinfo;
  642. for( U32 i = 0; i < 3; i ++ )
  643. {
  644. Point3F start = (xBaseL0_s * checkPoints[i]) + localCamPos;
  645. Point3F end = (xBaseL0_e * checkPoints[i]) + localCamPos;
  646. if (terrain->castRay(start, end, &rinfo))
  647. continue;
  648. terrain->getHeight(Point2F(start.x, start.y), &height);
  649. if ((height <= start.z) == aboveTerrain)
  650. continue;
  651. start = (xBaseL1_s * checkPoints[i]) + localCamPos;
  652. end = (xBaseL1_e * checkPoints[i]) + localCamPos;
  653. if (terrain->castRay(start, end, &rinfo))
  654. continue;
  655. Point3F test = (start + end) * 0.5;
  656. if (terrain->castRay(localCamPos, test, &rinfo) == false)
  657. continue;
  658. return true;
  659. }
  660. }
  661. return false;
  662. }
  663. //-----------------------------------------------------------------------------
  664. void SceneCullingState::debugRenderCullingVolumes() const
  665. {
  666. const ColorI occluderColor( 255, 0, 0, 255 );
  667. const ColorI includerColor( 0, 255, 0, 255 );
  668. const PlaneF& nearPlane = getFrustum().getPlanes()[ Frustum::PlaneNear ];
  669. const PlaneF& farPlane = getFrustum().getPlanes()[ Frustum::PlaneFar ];
  670. DebugDrawer* drawer = DebugDrawer::get();
  671. const SceneZoneSpaceManager* zoneManager = mSceneManager->getZoneManager();
  672. bool haveDebugZone = false;
  673. const U32 numZones = mZoneStates.size();
  674. for( S32 zoneId = numZones - 1; zoneId >= 0; -- zoneId )
  675. {
  676. if( !zoneManager->isValidZoneId( zoneId ) )
  677. continue;
  678. const SceneZoneCullingState& zoneState = mZoneStates[ zoneId ];
  679. if( !zoneManager->getZoneOwner( zoneId )->isSelected() && ( zoneId != SceneZoneSpaceManager::RootZoneId || haveDebugZone ) )
  680. continue;
  681. haveDebugZone = true;
  682. for( SceneZoneCullingState::CullingVolumeIterator iter( zoneState );
  683. iter.isValid(); ++ iter )
  684. {
  685. // Temporarily add near and far plane to culling volume so that
  686. // no matter how it is defined, it has a chance of being properly
  687. // capped.
  688. const U32 numPlanes = iter->getPlanes().getNumPlanes();
  689. const PlaneF* planes = iter->getPlanes().getPlanes();
  690. TempAlloc< PlaneF > tempPlanes( numPlanes + 2 );
  691. tempPlanes[ 0 ] = nearPlane;
  692. tempPlanes[ 1 ] = farPlane;
  693. dMemcpy( &tempPlanes[ 2 ], planes, numPlanes * sizeof( PlaneF ) );
  694. // Build a polyhedron from the plane set.
  695. Polyhedron polyhedron;
  696. polyhedron.buildFromPlanes(
  697. PlaneSetF( tempPlanes, numPlanes + 2 )
  698. );
  699. // If the polyhedron has any renderable data,
  700. // hand it over to the debug drawer.
  701. if( polyhedron.getNumEdges() )
  702. drawer->drawPolyhedron( polyhedron, iter->isOccluder() ? occluderColor : includerColor );
  703. }
  704. }
  705. }