forestCell.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 "forest/forestCell.h"
  24. #include "forest/forest.h"
  25. #include "forest/forestCellBatch.h"
  26. #include "forest/forestCollision.h"
  27. #include "T3D/physics/physicsPlugin.h"
  28. #include "T3D/physics/physicsBody.h"
  29. #include "T3D/physics/physicsCollision.h"
  30. #include "collision/concretePolyList.h"
  31. #include "gfx/gfxDrawUtil.h"
  32. #include "math/util/frustum.h"
  33. ForestCell::ForestCell( const RectF &rect ) :
  34. mRect( rect ),
  35. mBounds( Box3F::Invalid ),
  36. mIsDirty( false ),
  37. mLargestItem( ForestItem::Invalid ),
  38. mIsInteriorOnly( false )
  39. {
  40. dMemset( mSubCells, 0, sizeof( mSubCells ) );
  41. dMemset( mPhysicsRep, 0, sizeof( mPhysicsRep ) );
  42. }
  43. ForestCell::~ForestCell()
  44. {
  45. mItems.clear();
  46. for ( U32 i=0; i < 4; i++ )
  47. SAFE_DELETE( mSubCells[i] );
  48. freeBatches();
  49. SAFE_DELETE( mPhysicsRep[0] );
  50. SAFE_DELETE( mPhysicsRep[1] );
  51. }
  52. void ForestCell::freeBatches()
  53. {
  54. for ( U32 i=0; i < mBatches.size(); i++ )
  55. SAFE_DELETE( mBatches[i] );
  56. mBatches.clear();
  57. }
  58. void ForestCell::buildBatches()
  59. {
  60. // Gather items for batches.
  61. Vector<ForestItem> items;
  62. getItems( &items );
  63. // Ask the item to batch itself.
  64. Vector<ForestItem>::const_iterator item = items.begin();
  65. bool batched = false;
  66. for ( ; item != items.end(); item++ )
  67. {
  68. // Loop thru the batches till someone
  69. // takes this guy off our hands.
  70. batched = false;
  71. for ( S32 i=0; i < mBatches.size(); i++ )
  72. {
  73. if ( mBatches[i]->add( *item ) )
  74. {
  75. batched = true;
  76. break;
  77. }
  78. }
  79. if ( batched )
  80. continue;
  81. // Gotta create a new batch.
  82. ForestCellBatch *batch = item->getData()->allocateBatch();
  83. if ( batch )
  84. {
  85. batch->add( *item );
  86. mBatches.push_back( batch );
  87. }
  88. }
  89. }
  90. S32 ForestCell::renderBatches( SceneRenderState *state, Frustum *culler )
  91. {
  92. PROFILE_SCOPE( ForestCell_renderBatches );
  93. if ( !hasBatches() )
  94. return 0;
  95. S32 renderedItems = 0;
  96. for ( S32 i=0; i < mBatches.size(); i++ )
  97. {
  98. // Is this batch entirely culled?
  99. if ( culler && culler->isCulled( mBatches[i]->getWorldBox() ) )
  100. continue;
  101. if( state->getCullingState().isOccludedWithExtraPlanesCull( mBatches[i]->getWorldBox() ) )
  102. continue;
  103. mBatches[i]->render( state );
  104. renderedItems += mBatches[i]->getItemCount();
  105. }
  106. return renderedItems;
  107. }
  108. S32 ForestCell::render( TSRenderState *rdata, const Frustum *culler )
  109. {
  110. PROFILE_SCOPE( ForestCell_render );
  111. AssertFatal( isLeaf(), "ForestCell::render() - This shouldn't be called on non-leaf cells!" );
  112. U32 itemsRendered = 0;
  113. // TODO: Items are generated in order of type,
  114. // so we can maybe save some overhead by preparing
  115. // the item for rendering once.
  116. Vector<ForestItem>::iterator item = mItems.begin();
  117. for ( ; item != mItems.end(); item++ )
  118. {
  119. // Do we need to cull individual items?
  120. if ( culler && culler->isCulled( item->getWorldBox() ) )
  121. continue;
  122. if ( item->getData()->render( rdata, *item ) )
  123. ++itemsRendered;
  124. }
  125. return itemsRendered;
  126. }
  127. void ForestCell::_updateBounds()
  128. {
  129. mIsDirty = false;
  130. mBounds = Box3F::Invalid;
  131. mLargestItem = ForestItem::Invalid;
  132. F32 radius;
  133. if ( isBranch() )
  134. {
  135. for ( U32 i=0; i < 4; i++ )
  136. {
  137. mBounds.intersect( mSubCells[i]->getBounds() );
  138. radius = mSubCells[i]->mLargestItem.getRadius();
  139. if ( radius > mLargestItem.getRadius() )
  140. mLargestItem = mSubCells[i]->mLargestItem;
  141. }
  142. return;
  143. }
  144. // Loop thru all the items in this cell.
  145. Vector<ForestItem>::const_iterator item = mItems.begin();
  146. for ( ; item != mItems.end(); item++ )
  147. {
  148. mBounds.intersect( (*item).getWorldBox() );
  149. radius = (*item).getRadius();
  150. if ( radius > mLargestItem.getRadius() )
  151. mLargestItem = (*item);
  152. }
  153. }
  154. void ForestCell::_updateZoning( const SceneZoneSpaceManager *zoneManager )
  155. {
  156. PROFILE_SCOPE( ForestCell_UpdateZoning );
  157. mZoneOverlap.setSize( zoneManager->getNumZones() );
  158. mZoneOverlap.clear();
  159. mIsInteriorOnly = true;
  160. if ( isLeaf() )
  161. {
  162. // Skip empty cells... they don't have valid bounds.
  163. if ( mItems.empty() )
  164. return;
  165. Vector<U32> zones;
  166. zoneManager->findZones( getBounds(), zones );
  167. for ( U32 i=0; i < zones.size(); i++ )
  168. {
  169. // Set overlap bit for zone except it's the outdoor zone.
  170. if( zones[ i ] != SceneZoneSpaceManager::RootZoneId )
  171. mZoneOverlap.set( zones[i] );
  172. else
  173. mIsInteriorOnly = false;
  174. }
  175. return;
  176. }
  177. for ( U32 i = 0; i < 4; i++ )
  178. {
  179. ForestCell *cell = mSubCells[i];
  180. cell->_updateZoning( zoneManager );
  181. mZoneOverlap.combineOR( cell->getZoneOverlap() );
  182. mIsInteriorOnly &= cell->mIsInteriorOnly;
  183. }
  184. }
  185. bool ForestCell::findIndexByKey( ForestItemKey key, U32 *outIndex ) const
  186. {
  187. // Do a simple binary search.
  188. U32 i = 0,
  189. lo = 0,
  190. hi = mItems.size();
  191. const ForestItem *items = mItems.address();
  192. while ( lo < hi )
  193. {
  194. i = (lo + hi) / 2;
  195. if ( key < items[i].getKey() )
  196. hi = i;
  197. else if ( key > items[i].getKey() )
  198. lo = i + 1;
  199. else
  200. {
  201. *outIndex = i;
  202. return true;
  203. }
  204. }
  205. *outIndex = lo;
  206. return false;
  207. }
  208. const ForestItem& ForestCell::insertItem( ForestItemKey key,
  209. ForestItemData *data,
  210. const MatrixF &xfm,
  211. F32 scale )
  212. {
  213. AssertFatal( key != 0, "ForestCell::insertItem() - Got null key!" );
  214. AssertFatal( data != NULL, "ForestCell::insertItem() - Got null datablock!" );
  215. // Make sure we update the bounds later.
  216. mIsDirty = true;
  217. // PhysicsBody is now invalid and must be rebuilt later.
  218. SAFE_DELETE( mPhysicsRep[0] );
  219. SAFE_DELETE( mPhysicsRep[1] );
  220. // Destroy batches so we recreate it on
  221. // the next next render.
  222. freeBatches();
  223. // Ok... do we need to split this cell?
  224. if ( isLeaf() && mItems.size() > MaxItems )
  225. {
  226. // Add the children.
  227. for ( U32 i=0; i < 4; i++ )
  228. mSubCells[i] = new ForestCell( _makeChildRect( i ) );
  229. // Now push all our current children down.
  230. Vector<ForestItem>::iterator item = mItems.begin();
  231. for ( ; item != mItems.end(); item++ )
  232. {
  233. U32 index = _getSubCell( item->getPosition().x, item->getPosition().y );
  234. mSubCells[index]->insertItem( item->getKey(),
  235. item->getData(),
  236. item->getTransform(),
  237. item->getScale() );
  238. }
  239. // Clean up.
  240. mItems.clear();
  241. mItems.compact();
  242. }
  243. // Do we have children?
  244. if ( isBranch() )
  245. {
  246. // Ok... kick this item down then.
  247. U32 index = _getSubCell( xfm.getPosition().x, xfm.getPosition().y );
  248. const ForestItem &result = mSubCells[index]->insertItem( key, data, xfm, scale );
  249. AssertFatal( index == _getSubCell( result.getPosition().x, result.getPosition().y ), "ForestCell::insertItem() - binning is hosed." );
  250. return result;
  251. }
  252. // Do the datablock preload here to insure it happens
  253. // before an item is used in the scene.
  254. data->preload();
  255. // First see if we can find it. This is nifty so
  256. // I'll explain it a bit more.
  257. //
  258. // The find function does a binary search thru the
  259. // sorted item list.
  260. //
  261. // If found the index is the position of the item.
  262. //
  263. // If not found the index is the correct insertion
  264. // position for adding the new item.
  265. //
  266. // So not only do we have a fast find which is worst
  267. // case O(log n)... but we also have the proper insert
  268. // position to maintain a sorted item list.
  269. //
  270. U32 index;
  271. bool found = findIndexByKey( key, &index );
  272. // If we didn't find one then insert it.
  273. if ( !found )
  274. mItems.insert( index );
  275. // Update the item settings.
  276. ForestItem &item = mItems[ index ];
  277. item.setData( data );
  278. item.setTransform( xfm, scale );
  279. if ( !found )
  280. item.setKey( key );
  281. return item;
  282. }
  283. bool ForestCell::removeItem( ForestItemKey key, const Point3F &keyPos, bool deleteIfEmpty )
  284. {
  285. PROFILE_SCOPE( ForestCell_removeItem );
  286. AssertFatal( key != 0, "ForestCell::removeItem() - Got null key!" );
  287. // If this cell has no items then check the children.
  288. if ( mItems.empty() )
  289. {
  290. // Let the child deal with it.
  291. U32 index = _getSubCell( keyPos.x, keyPos.y );
  292. if ( !mSubCells[index]->removeItem( key, keyPos, deleteIfEmpty ) )
  293. {
  294. // For debugging lets make sure we didn't pick the wrong subCell...
  295. return false;
  296. }
  297. // If requested by the caller delete our empty subcells.
  298. // Note that by deleting SubCell[0] we have become a leaf with no items
  299. // and will return true to our parent's isEmpty test.
  300. if ( deleteIfEmpty &&
  301. mSubCells[0]->isEmpty() &&
  302. mSubCells[1]->isEmpty() &&
  303. mSubCells[2]->isEmpty() &&
  304. mSubCells[3]->isEmpty() )
  305. {
  306. SAFE_DELETE( mSubCells[0] );
  307. SAFE_DELETE( mSubCells[1] );
  308. SAFE_DELETE( mSubCells[2] );
  309. SAFE_DELETE( mSubCells[3] );
  310. }
  311. }
  312. else
  313. {
  314. // First see if we can find it.
  315. U32 index;
  316. if ( !findIndexByKey( key, &index ) )
  317. return false;
  318. // Erase it.
  319. mItems.erase( index );
  320. }
  321. // Do a full bounds update on the next request.
  322. mIsDirty = true;
  323. // PhysicsBody is now invalid and must be rebuilt later.
  324. SAFE_DELETE( mPhysicsRep[0] );
  325. SAFE_DELETE( mPhysicsRep[1] );
  326. // Destroy batches so we recreate it on
  327. // the next next render.
  328. freeBatches();
  329. return true;
  330. }
  331. void ForestCell::getItems( Vector<ForestItem> *outItems ) const
  332. {
  333. Vector<const ForestCell*> stack;
  334. stack.push_back( this );
  335. // Now loop till we run out of cells.
  336. while ( !stack.empty() )
  337. {
  338. // Pop off the next cell.
  339. const ForestCell *cell = stack.last();
  340. stack.pop_back();
  341. // Recurse thru non-leaf cells.
  342. if ( !cell->isLeaf() )
  343. {
  344. stack.merge( cell->mSubCells, 4 );
  345. continue;
  346. }
  347. // Get the items.
  348. outItems->merge( cell->getItems() );
  349. }
  350. }
  351. void ForestCell::buildPhysicsRep( Forest *forest )
  352. {
  353. AssertFatal( isLeaf(), "ForestCell::buildPhysicsRep() - This shouldn't be called on non-leaf cells!" );
  354. bool isServer = forest->isServerObject();
  355. // Already has a PhysicsBody, if it needed to be rebuilt it would
  356. // already be null.
  357. if ( mPhysicsRep[ isServer ] )
  358. return;
  359. if ( !PHYSICSMGR )
  360. return;
  361. PhysicsCollision *colShape = NULL;
  362. // If we can steal the collision shape from the server-side cell
  363. // then do so as it saves us alot of cpu time and memory.
  364. if ( mPhysicsRep[ 1 ] )
  365. {
  366. colShape = mPhysicsRep[ 1 ]->getColShape();
  367. }
  368. else
  369. {
  370. // We must pass a sphere to buildPolyList but it is not used.
  371. const static SphereF dummySphere( Point3F::Zero, 0 );
  372. // Step thru them and build collision data.
  373. ForestItemVector::iterator itemItr = mItems.begin();
  374. ConcretePolyList polyList;
  375. for ( ; itemItr != mItems.end(); itemItr++ )
  376. {
  377. const ForestItem &item = *itemItr;
  378. const ForestItemData *itemData = item.getData();
  379. // If not collidable don't need to build anything.
  380. if ( !itemData->mCollidable )
  381. continue;
  382. // TODO: When we add breakable tree support this is where
  383. // we would need to store their collision data seperately.
  384. item.buildPolyList( &polyList, item.getWorldBox(), dummySphere );
  385. // TODO: Need to support multiple collision shapes
  386. // for really big forests at some point in the future.
  387. }
  388. if ( !polyList.isEmpty() )
  389. {
  390. colShape = PHYSICSMGR->createCollision();
  391. if ( !colShape->addTriangleMesh( polyList.mVertexList.address(),
  392. polyList.mVertexList.size(),
  393. polyList.mIndexList.address(),
  394. polyList.mIndexList.size() / 3,
  395. MatrixF::Identity ) )
  396. {
  397. SAFE_DELETE( colShape );
  398. }
  399. }
  400. }
  401. // We might not have any trees.
  402. if ( !colShape )
  403. return;
  404. PhysicsWorld *world = PHYSICSMGR->getWorld( isServer ? "server" : "client" );
  405. mPhysicsRep[ isServer ] = PHYSICSMGR->createBody();
  406. mPhysicsRep[ isServer ]->init( colShape, 0, 0, forest, world );
  407. }
  408. void ForestCell::clearPhysicsRep( Forest *forest )
  409. {
  410. bool isServer = forest->isServerObject();
  411. SAFE_DELETE( mPhysicsRep[ isServer ] );
  412. }