sceneCullingState.cpp 32 KB

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