decalManager.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707
  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 "T3D/decal/decalManager.h"
  24. #include "scene/sceneManager.h"
  25. #include "scene/sceneRenderState.h"
  26. #include "ts/tsShapeInstance.h"
  27. #include "console/console.h"
  28. #include "console/dynamicTypes.h"
  29. #include "gfx/primBuilder.h"
  30. #include "console/consoleTypes.h"
  31. #include "platform/profiler.h"
  32. #include "gfx/gfxTransformSaver.h"
  33. #include "lighting/lightManager.h"
  34. #include "lighting/lightInfo.h"
  35. #include "gfx/gfxDrawUtil.h"
  36. #include "gfx/sim/gfxStateBlockData.h"
  37. #include "materials/shaderData.h"
  38. #include "materials/matInstance.h"
  39. #include "renderInstance/renderPassManager.h"
  40. #include "core/resourceManager.h"
  41. #include "core/stream/fileStream.h"
  42. #include "gfx/gfxDebugEvent.h"
  43. #include "math/util/quadTransforms.h"
  44. #include "math/mathUtils.h"
  45. #include "core/volume.h"
  46. #include "core/module.h"
  47. #include "T3D/decal/decalData.h"
  48. #include "console/engineAPI.h"
  49. extern bool gEditingMission;
  50. MODULE_BEGIN( DecalManager )
  51. MODULE_INIT_AFTER( Scene )
  52. MODULE_SHUTDOWN_BEFORE( Scene )
  53. MODULE_INIT
  54. {
  55. gDecalManager = new DecalManager;
  56. gClientSceneGraph->addObjectToScene( gDecalManager );
  57. }
  58. MODULE_SHUTDOWN
  59. {
  60. gClientSceneGraph->removeObjectFromScene( gDecalManager );
  61. SAFE_DELETE( gDecalManager );
  62. }
  63. MODULE_END;
  64. /// A bias applied to the nearPlane for Decal and DecalRoad rendering.
  65. /// Is set by by LevelInfo.
  66. F32 gDecalBias = 0.0015f;
  67. bool DecalManager::smDecalsOn = true;
  68. bool DecalManager::smDebugRender = false;
  69. F32 DecalManager::smDecalLifeTimeScale = 1.0f;
  70. bool DecalManager::smPoolBuffers = true;
  71. const U32 DecalManager::smMaxVerts = 6000;
  72. const U32 DecalManager::smMaxIndices = 10000;
  73. DecalManager *gDecalManager = NULL;
  74. IMPLEMENT_CONOBJECT(DecalManager);
  75. ConsoleDoc(
  76. "@defgroup Decals\n"
  77. "@brief Decals are non-SimObject derived objects that are stored and loaded "
  78. "separately from the normal mission file.\n\n"
  79. "The DecalManager handles all aspects of decal management including loading, "
  80. "creation, saving, and automatically deleting decals that have exceeded their "
  81. "lifeSpan.\n\n"
  82. "The static decals associated with a mission are normally loaded immediately "
  83. "after the mission itself has loaded as shown below.\n"
  84. "@tsexample\n"
  85. "// Load the static mission decals.\n"
  86. "decalManagerLoad( %missionName @ \".decals\" );\n"
  87. "@endtsexample\n"
  88. "@ingroup FX\n"
  89. );
  90. ConsoleDocClass( DecalManager,
  91. "@brief The object that manages all of the decals in the active mission.\n\n"
  92. "@see Decals\n"
  93. "@ingroup Decals\n"
  94. "@ingroup FX\n"
  95. );
  96. namespace {
  97. int QSORT_CALLBACK cmpDecalInstance(const void* p1, const void* p2)
  98. {
  99. const DecalInstance** pd1 = (const DecalInstance**)p1;
  100. const DecalInstance** pd2 = (const DecalInstance**)p2;
  101. return int(((char *)(*pd1)->mDataBlock) - ((char *)(*pd2)->mDataBlock));
  102. }
  103. int QSORT_CALLBACK cmpPointsXY( const void *p1, const void *p2 )
  104. {
  105. const Point3F *pnt1 = (const Point3F*)p1;
  106. const Point3F *pnt2 = (const Point3F*)p2;
  107. if ( pnt1->x < pnt2->x )
  108. return -1;
  109. else if ( pnt1->x > pnt2->x )
  110. return 1;
  111. else if ( pnt1->y < pnt2->y )
  112. return -1;
  113. else if ( pnt1->y > pnt2->y )
  114. return 1;
  115. else
  116. return 0;
  117. }
  118. int QSORT_CALLBACK cmpQuadPointTheta( const void *p1, const void *p2 )
  119. {
  120. const Point4F *pnt1 = (const Point4F*)p1;
  121. const Point4F *pnt2 = (const Point4F*)p2;
  122. if ( mFabs( pnt1->w ) > mFabs( pnt2->w ) )
  123. return 1;
  124. else if ( mFabs( pnt1->w ) < mFabs( pnt2->w ) )
  125. return -1;
  126. else
  127. return 0;
  128. }
  129. static Point3F gSortPoint;
  130. int QSORT_CALLBACK cmpDecalDistance( const void *p1, const void *p2 )
  131. {
  132. const DecalInstance** pd1 = (const DecalInstance**)p1;
  133. const DecalInstance** pd2 = (const DecalInstance**)p2;
  134. F32 dist1 = ( (*pd1)->mPosition - gSortPoint ).lenSquared();
  135. F32 dist2 = ( (*pd2)->mPosition - gSortPoint ).lenSquared();
  136. return mSign( dist1 - dist2 );
  137. }
  138. int QSORT_CALLBACK cmpDecalRenderOrder( const void *p1, const void *p2 )
  139. {
  140. const DecalInstance** pd1 = (const DecalInstance**)p1;
  141. const DecalInstance** pd2 = (const DecalInstance**)p2;
  142. if ( ( (*pd2)->mFlags & SaveDecal ) && !( (*pd1)->mFlags & SaveDecal ) )
  143. return -1;
  144. else if ( !( (*pd2)->mFlags & SaveDecal ) && ( (*pd1)->mFlags & SaveDecal ) )
  145. return 1;
  146. else
  147. {
  148. int priority = (*pd1)->getRenderPriority() - (*pd2)->getRenderPriority();
  149. if ( priority != 0 )
  150. return priority;
  151. if ( (*pd2)->mFlags & SaveDecal )
  152. {
  153. int id = ( (*pd1)->mDataBlock->getMaterial()->getId() - (*pd2)->mDataBlock->getMaterial()->getId() );
  154. if ( id != 0 )
  155. return id;
  156. return (*pd1)->mCreateTime - (*pd2)->mCreateTime;
  157. }
  158. else
  159. return (*pd1)->mCreateTime - (*pd2)->mCreateTime;
  160. }
  161. }
  162. } // namespace {}
  163. // These numbers should be tweaked to get as many dynamically placed decals
  164. // as possible to allocate buffer arrays with the FreeListChunker.
  165. enum
  166. {
  167. SIZE_CLASS_0 = 256,
  168. SIZE_CLASS_1 = 512,
  169. SIZE_CLASS_2 = 1024,
  170. NUM_SIZE_CLASSES = 3
  171. };
  172. //-------------------------------------------------------------------------
  173. // DecalManager
  174. //-------------------------------------------------------------------------
  175. DecalManager::DecalManager()
  176. {
  177. #ifdef DECALMANAGER_DEBUG
  178. VECTOR_SET_ASSOCIATION( mDebugPlanes );
  179. #endif
  180. setGlobalBounds();
  181. mDataFileName = NULL;
  182. mTypeMask |= EnvironmentObjectType;
  183. mDirty = false;
  184. mChunkers[0] = new FreeListChunkerUntyped( SIZE_CLASS_0 * sizeof( U8 ) );
  185. mChunkers[1] = new FreeListChunkerUntyped( SIZE_CLASS_1 * sizeof( U8 ) );
  186. mChunkers[2] = new FreeListChunkerUntyped( SIZE_CLASS_2 * sizeof( U8 ) );
  187. GFXDevice::getDeviceEventSignal().notify(this, &DecalManager::_handleGFXEvent);
  188. }
  189. DecalManager::~DecalManager()
  190. {
  191. GFXDevice::getDeviceEventSignal().remove(this, &DecalManager::_handleGFXEvent);
  192. clearData();
  193. for( U32 i = 0; i < NUM_SIZE_CLASSES; ++ i )
  194. delete mChunkers[ i ];
  195. }
  196. void DecalManager::consoleInit()
  197. {
  198. Con::addVariable( "$pref::Decals::enabled", TypeBool, &smDecalsOn,
  199. "Controls whether decals are rendered.\n"
  200. "@ingroup Decals" );
  201. Con::addVariable( "$pref::Decals::lifeTimeScale", TypeF32, &smDecalLifeTimeScale,
  202. "@brief Lifetime that decals will last after being created in the world.\n"
  203. "Deprecated. Use DecalData::lifeSpan instead.\n"
  204. "@ingroup Decals" );
  205. Con::addVariable( "$Decals::poolBuffers", TypeBool, &smPoolBuffers,
  206. "If true, will merge all PrimitiveBuffers and VertexBuffers into a pair "
  207. "of pools before clearing them at the end of a frame.\n"
  208. "If false, will just clear them at the end of a frame.\n"
  209. "@ingroup Decals" );
  210. Con::addVariable( "$Decals::debugRender", TypeBool, &smDebugRender,
  211. "If true, the decal spheres will be visualized when in the editor.\n\n"
  212. "@ingroup Decals" );
  213. Con::addVariable( "$Decals::sphereDistanceTolerance", TypeF32, &DecalSphere::smDistanceTolerance,
  214. "The distance at which the decal system will start breaking up decal "
  215. "spheres when adding new decals.\n\n"
  216. "@ingroup Decals" );
  217. Con::addVariable( "$Decals::sphereRadiusTolerance", TypeF32, &DecalSphere::smRadiusTolerance,
  218. "The radius beyond which the decal system will start breaking up decal "
  219. "spheres when adding new decals.\n\n"
  220. "@ingroup Decals" );
  221. }
  222. bool DecalManager::_handleGFXEvent(GFXDevice::GFXDeviceEventType event)
  223. {
  224. switch(event)
  225. {
  226. case GFXDevice::deEndOfFrame:
  227. // Return PrimitiveBuffers and VertexBuffers used this frame to the pool.
  228. if ( smPoolBuffers )
  229. {
  230. mPBPool.merge( mPBs );
  231. mPBs.clear();
  232. mVBPool.merge( mVBs );
  233. mVBs.clear();
  234. }
  235. else
  236. {
  237. _freePools();
  238. }
  239. break;
  240. default: ;
  241. }
  242. return true;
  243. }
  244. bool DecalManager::clipDecal( DecalInstance *decal, Vector<Point3F> *edgeVerts, const Point2F *clipDepth )
  245. {
  246. PROFILE_SCOPE( DecalManager_clipDecal );
  247. // Free old verts and indices.
  248. _freeBuffers( decal );
  249. F32 halfSize = decal->mSize * 0.5f;
  250. // Ugly hack for ProjectedShadow!
  251. F32 halfSizeZ = clipDepth ? clipDepth->x : halfSize;
  252. F32 negHalfSize = clipDepth ? clipDepth->y : halfSize;
  253. Point3F decalHalfSize( halfSize, halfSize, halfSize );
  254. Point3F decalHalfSizeZ( halfSizeZ, halfSizeZ, halfSizeZ );
  255. MatrixF projMat( true );
  256. decal->getWorldMatrix( &projMat );
  257. const VectorF &crossVec = decal->mNormal;
  258. const Point3F &decalPos = decal->mPosition;
  259. VectorF newFwd, newRight;
  260. projMat.getColumn( 0, &newRight );
  261. projMat.getColumn( 1, &newFwd );
  262. VectorF objRight( 1.0f, 0, 0 );
  263. VectorF objFwd( 0, 1.0f, 0 );
  264. VectorF objUp( 0, 0, 1.0f );
  265. // See above re: decalHalfSizeZ hack.
  266. mClipper.clear();
  267. mClipper.mPlaneList.setSize(6);
  268. mClipper.mPlaneList[0].set( ( decalPos + ( -newRight * halfSize ) ), -newRight );
  269. mClipper.mPlaneList[1].set( ( decalPos + ( -newFwd * halfSize ) ), -newFwd );
  270. mClipper.mPlaneList[2].set( ( decalPos + ( -crossVec * decalHalfSizeZ ) ), -crossVec );
  271. mClipper.mPlaneList[3].set( ( decalPos + ( newRight * halfSize ) ), newRight );
  272. mClipper.mPlaneList[4].set( ( decalPos + ( newFwd * halfSize ) ), newFwd );
  273. mClipper.mPlaneList[5].set( ( decalPos + ( crossVec * negHalfSize ) ), crossVec );
  274. mClipper.mNormal = decal->mNormal;
  275. const DecalData *decalData = decal->mDataBlock;
  276. mClipper.mNormalTolCosineRadians = mCos( mDegToRad( decalData->clippingAngle ) );
  277. Box3F box( -decalHalfSizeZ, decalHalfSizeZ );
  278. projMat.mul( box );
  279. PROFILE_START( DecalManager_clipDecal_buildPolyList );
  280. getContainer()->buildPolyList( PLC_Decal, box, decalData->clippingMasks, &mClipper );
  281. PROFILE_END();
  282. mClipper.cullUnusedVerts();
  283. mClipper.triangulate();
  284. if ( !decalData->skipVertexNormals )
  285. mClipper.generateNormals();
  286. if ( mClipper.mVertexList.empty() )
  287. return false;
  288. #ifdef DECALMANAGER_DEBUG
  289. mDebugPlanes.clear();
  290. mDebugPlanes.merge( mClipper.mPlaneList );
  291. #endif
  292. decal->mVertCount = mClipper.mVertexList.size();
  293. decal->mIndxCount = mClipper.mIndexList.size();
  294. Vector<Point3F> tmpPoints;
  295. tmpPoints.push_back(( objFwd * decalHalfSize ) + ( objRight * decalHalfSize ));
  296. tmpPoints.push_back(( objFwd * decalHalfSize ) + ( -objRight * decalHalfSize ));
  297. tmpPoints.push_back(( -objFwd * decalHalfSize ) + ( -objRight * decalHalfSize ));
  298. Point3F lowerLeft(( -objFwd * decalHalfSize ) + ( objRight * decalHalfSize ));
  299. projMat.inverse();
  300. _generateWindingOrder( lowerLeft, &tmpPoints );
  301. BiQuadToSqr quadToSquare( Point2F( lowerLeft.x, lowerLeft.y ),
  302. Point2F( tmpPoints[0].x, tmpPoints[0].y ),
  303. Point2F( tmpPoints[1].x, tmpPoints[1].y ),
  304. Point2F( tmpPoints[2].x, tmpPoints[2].y ) );
  305. Point2F uv( 0, 0 );
  306. Point3F vecX(0.0f, 0.0f, 0.0f);
  307. // Allocate memory for vert and index arrays
  308. _allocBuffers( decal );
  309. // Mark this so that the color will be assigned on these verts the next
  310. // time it renders, since we just threw away the previous verts.
  311. decal->mLastAlpha = -1;
  312. Point3F vertPoint( 0, 0, 0 );
  313. for ( U32 i = 0; i < mClipper.mVertexList.size(); i++ )
  314. {
  315. const ClippedPolyList::Vertex &vert = mClipper.mVertexList[i];
  316. vertPoint = vert.point;
  317. // Transform this point to
  318. // object space to look up the
  319. // UV coordinate for this vertex.
  320. projMat.mulP( vertPoint );
  321. // Clamp the point to be within the quad.
  322. vertPoint.x = mClampF( vertPoint.x, -decalHalfSize.x, decalHalfSize.x );
  323. vertPoint.y = mClampF( vertPoint.y, -decalHalfSize.y, decalHalfSize.y );
  324. // Get our UV.
  325. uv = quadToSquare.transform( Point2F( vertPoint.x, vertPoint.y ) );
  326. const RectF &rect = decal->mDataBlock->texRect[decal->mTextureRectIdx];
  327. uv *= rect.extent;
  328. uv += rect.point;
  329. // Set the world space vertex position.
  330. decal->mVerts[i].point = vert.point;
  331. decal->mVerts[i].texCoord.set( uv.x, uv.y );
  332. if ( mClipper.mNormalList.empty() )
  333. continue;
  334. decal->mVerts[i].normal = mClipper.mNormalList[i];
  335. decal->mVerts[i].normal.normalize();
  336. if( mFabs( decal->mVerts[i].normal.z ) > 0.8f )
  337. mCross( decal->mVerts[i].normal, Point3F( 1.0f, 0.0f, 0.0f ), &vecX );
  338. else if ( mFabs( decal->mVerts[i].normal.x ) > 0.8f )
  339. mCross( decal->mVerts[i].normal, Point3F( 0.0f, 1.0f, 0.0f ), &vecX );
  340. else if ( mFabs( decal->mVerts[i].normal.y ) > 0.8f )
  341. mCross( decal->mVerts[i].normal, Point3F( 0.0f, 0.0f, 1.0f ), &vecX );
  342. decal->mVerts[i].tangent = mCross( decal->mVerts[i].normal, vecX );
  343. }
  344. U32 curIdx = 0;
  345. for ( U32 j = 0; j < mClipper.mPolyList.size(); j++ )
  346. {
  347. // Write indices for each Poly
  348. ClippedPolyList::Poly *poly = &mClipper.mPolyList[j];
  349. AssertFatal( poly->vertexCount == 3, "Got non-triangle poly!" );
  350. decal->mIndices[curIdx] = mClipper.mIndexList[poly->vertexStart];
  351. curIdx++;
  352. decal->mIndices[curIdx] = mClipper.mIndexList[poly->vertexStart + 1];
  353. curIdx++;
  354. decal->mIndices[curIdx] = mClipper.mIndexList[poly->vertexStart + 2];
  355. curIdx++;
  356. }
  357. if ( !edgeVerts )
  358. return true;
  359. Point3F tmpHullPt( 0, 0, 0 );
  360. Vector<Point3F> tmpHullPts;
  361. for ( U32 i = 0; i < mClipper.mVertexList.size(); i++ )
  362. {
  363. const ClippedPolyList::Vertex &vert = mClipper.mVertexList[i];
  364. tmpHullPt = vert.point;
  365. projMat.mulP( tmpHullPt );
  366. tmpHullPts.push_back( tmpHullPt );
  367. }
  368. edgeVerts->clear();
  369. U32 verts = _generateConvexHull( tmpHullPts, edgeVerts );
  370. edgeVerts->setSize( verts );
  371. projMat.inverse();
  372. for ( U32 i = 0; i < edgeVerts->size(); i++ )
  373. projMat.mulP( (*edgeVerts)[i] );
  374. return true;
  375. }
  376. DecalInstance* DecalManager::addDecal( const Point3F &pos,
  377. const Point3F &normal,
  378. F32 rotAroundNormal,
  379. DecalData *decalData,
  380. F32 decalScale,
  381. S32 decalTexIndex,
  382. U8 flags )
  383. {
  384. MatrixF mat( true );
  385. MathUtils::getMatrixFromUpVector( normal, &mat );
  386. AngAxisF rot( normal, rotAroundNormal );
  387. MatrixF rotmat;
  388. rot.setMatrix( &rotmat );
  389. mat.mul( rotmat );
  390. Point3F tangent;
  391. mat.getColumn( 1, &tangent );
  392. return addDecal( pos, normal, tangent, decalData, decalScale, decalTexIndex, flags );
  393. }
  394. DecalInstance* DecalManager::addDecal( const Point3F& pos,
  395. const Point3F& normal,
  396. const Point3F& tangent,
  397. DecalData* decalData,
  398. F32 decalScale,
  399. S32 decalTexIndex,
  400. U8 flags )
  401. {
  402. if ( !mData && !_createDataFile() )
  403. return NULL;
  404. // only dirty the manager if this decal should be saved
  405. if ( flags & SaveDecal )
  406. mDirty = true;
  407. return mData->addDecal( pos, normal, tangent, decalData, decalScale, decalTexIndex, flags );
  408. }
  409. void DecalManager::removeDecal( DecalInstance *inst )
  410. {
  411. // If this is a decal we save then we need
  412. // to set the dirty flag.
  413. if ( inst->mFlags & SaveDecal )
  414. mDirty = true;
  415. // Remove the decal from the instance vector.
  416. if( inst->mId != -1 && inst->mId < mDecalInstanceVec.size() )
  417. mDecalInstanceVec[ inst->mId ] = NULL;
  418. // Release its geometry (if it has any).
  419. _freeBuffers( inst );
  420. // Remove it from the decal file.
  421. if ( mData )
  422. mData->removeDecal( inst );
  423. }
  424. DecalInstance* DecalManager::getDecal( S32 id )
  425. {
  426. if( id < 0 || id >= mDecalInstanceVec.size() )
  427. return NULL;
  428. return mDecalInstanceVec[id];
  429. }
  430. void DecalManager::notifyDecalModified( DecalInstance *inst )
  431. {
  432. // If this is a decal we save then we need
  433. // to set the dirty flag.
  434. if ( inst->mFlags & SaveDecal )
  435. mDirty = true;
  436. if ( mData )
  437. mData->notifyDecalModified( inst );
  438. }
  439. DecalInstance* DecalManager::getClosestDecal( const Point3F &pos )
  440. {
  441. if ( !mData )
  442. return NULL;
  443. const Vector<DecalSphere*> &grid = mData->getSphereList();
  444. DecalInstance *inst = NULL;
  445. SphereF worldPickSphere( pos, 0.5f );
  446. SphereF worldInstSphere( Point3F( 0, 0, 0 ), 1.0f );
  447. Vector<DecalInstance*> collectedInsts;
  448. for ( U32 i = 0; i < grid.size(); i++ )
  449. {
  450. DecalSphere *decalSphere = grid[i];
  451. const SphereF &worldSphere = decalSphere->mWorldSphere;
  452. if ( !worldSphere.isIntersecting( worldPickSphere ) &&
  453. !worldSphere.isContained( pos ) )
  454. continue;
  455. const Vector<DecalInstance*> &items = decalSphere->mItems;
  456. for ( U32 n = 0; n < items.size(); n++ )
  457. {
  458. inst = items[n];
  459. if ( !inst )
  460. continue;
  461. worldInstSphere.center = inst->mPosition;
  462. worldInstSphere.radius = inst->mSize;
  463. if ( !worldInstSphere.isContained( inst->mPosition ) )
  464. continue;
  465. collectedInsts.push_back( inst );
  466. }
  467. }
  468. F32 closestDistance = F32_MAX;
  469. F32 currentDist = 0;
  470. U32 closestIndex = 0;
  471. for ( U32 i = 0; i < collectedInsts.size(); i++ )
  472. {
  473. inst = collectedInsts[i];
  474. currentDist = (inst->mPosition - pos).len();
  475. if ( currentDist < closestDistance )
  476. {
  477. closestIndex = i;
  478. closestDistance = currentDist;
  479. worldInstSphere.center = inst->mPosition;
  480. worldInstSphere.radius = inst->mSize;
  481. }
  482. }
  483. if ( !collectedInsts.empty() &&
  484. collectedInsts[closestIndex] &&
  485. closestDistance < 1.0f ||
  486. worldInstSphere.isContained( pos ) )
  487. return collectedInsts[closestIndex];
  488. else
  489. return NULL;
  490. }
  491. DecalInstance* DecalManager::raycast( const Point3F &start, const Point3F &end, bool savedDecalsOnly )
  492. {
  493. if ( !mData )
  494. return NULL;
  495. const Vector<DecalSphere*> &grid = mData->getSphereList();
  496. DecalInstance *inst = NULL;
  497. SphereF worldSphere( Point3F( 0, 0, 0 ), 1.0f );
  498. Vector<DecalInstance*> hitDecals;
  499. for ( U32 i = 0; i < grid.size(); i++ )
  500. {
  501. DecalSphere *decalSphere = grid[i];
  502. if ( !decalSphere->mWorldSphere.intersectsRay( start, end ) )
  503. continue;
  504. const Vector<DecalInstance*> &items = decalSphere->mItems;
  505. for ( U32 n = 0; n < items.size(); n++ )
  506. {
  507. inst = items[n];
  508. if ( !inst )
  509. continue;
  510. if ( savedDecalsOnly && !(inst->mFlags & SaveDecal) )
  511. continue;
  512. worldSphere.center = inst->mPosition;
  513. worldSphere.radius = inst->mSize;
  514. if ( !worldSphere.intersectsRay( start, end ) )
  515. continue;
  516. RayInfo ri;
  517. bool containsPoint = false;
  518. if ( gServerContainer.castRayRendered( start, end, STATIC_COLLISION_TYPEMASK, &ri ) )
  519. {
  520. Point2F poly[4];
  521. poly[0].set( inst->mPosition.x - (inst->mSize / 2), inst->mPosition.y + (inst->mSize / 2));
  522. poly[1].set( inst->mPosition.x - (inst->mSize / 2), inst->mPosition.y - (inst->mSize / 2));
  523. poly[2].set( inst->mPosition.x + (inst->mSize / 2), inst->mPosition.y - (inst->mSize / 2));
  524. poly[3].set( inst->mPosition.x + (inst->mSize / 2), inst->mPosition.y + (inst->mSize / 2));
  525. if ( MathUtils::pointInPolygon( poly, 4, Point2F(ri.point.x, ri.point.y) ) )
  526. containsPoint = true;
  527. }
  528. if( !containsPoint )
  529. continue;
  530. hitDecals.push_back( inst );
  531. }
  532. }
  533. if ( hitDecals.empty() )
  534. return NULL;
  535. gSortPoint = start;
  536. dQsort( hitDecals.address(), hitDecals.size(), sizeof(DecalInstance*), cmpDecalDistance );
  537. return hitDecals[0];
  538. }
  539. U32 DecalManager::_generateConvexHull( const Vector<Point3F> &points, Vector<Point3F> *outPoints )
  540. {
  541. PROFILE_SCOPE( DecalManager_generateConvexHull );
  542. // chainHull_2D(): Andrew's monotone chain 2D convex hull algorithm
  543. // Input: P[] = an array of 2D points
  544. // presorted by increasing x- and y-coordinates
  545. // n = the number of points in P[]
  546. // Output: H[] = an array of the convex hull vertices (max is n)
  547. // Return: the number of points in H[]
  548. //int
  549. if ( points.size() < 3 )
  550. {
  551. outPoints->merge( points );
  552. return outPoints->size();
  553. }
  554. // Sort our input points.
  555. dQsort( points.address(), points.size(), sizeof( Point3F ), cmpPointsXY );
  556. U32 n = points.size();
  557. Vector<Point3F> tmpPoints;
  558. tmpPoints.setSize( n );
  559. // the output array H[] will be used as the stack
  560. S32 bot=0, top=(-1); // indices for bottom and top of the stack
  561. S32 i; // array scan index
  562. S32 toptmp = 0;
  563. // Get the indices of points with min x-coord and min|max y-coord
  564. S32 minmin = 0, minmax;
  565. F32 xmin = points[0].x;
  566. for ( i = 1; i < n; i++ )
  567. if (points[i].x != xmin)
  568. break;
  569. minmax = i - 1;
  570. if ( minmax == n - 1 )
  571. {
  572. // degenerate case: all x-coords == xmin
  573. toptmp = top + 1;
  574. if ( toptmp < n )
  575. tmpPoints[++top] = points[minmin];
  576. if ( points[minmax].y != points[minmin].y ) // a nontrivial segment
  577. {
  578. toptmp = top + 1;
  579. if ( toptmp < n )
  580. tmpPoints[++top] = points[minmax];
  581. }
  582. toptmp = top + 1;
  583. if ( toptmp < n )
  584. tmpPoints[++top] = points[minmin]; // add polygon endpoint
  585. return top+1;
  586. }
  587. // Get the indices of points with max x-coord and min|max y-coord
  588. S32 maxmin, maxmax = n-1;
  589. F32 xmax = points[n-1].x;
  590. for ( i = n - 2; i >= 0; i-- )
  591. if ( points[i].x != xmax )
  592. break;
  593. maxmin = i + 1;
  594. // Compute the lower hull on the stack H
  595. toptmp = top + 1;
  596. if ( toptmp < n )
  597. tmpPoints[++top] = points[minmin]; // push minmin point onto stack
  598. i = minmax;
  599. while ( ++i <= maxmin )
  600. {
  601. // the lower line joins P[minmin] with P[maxmin]
  602. if ( isLeft( points[minmin], points[maxmin], points[i]) >= 0 && i < maxmin )
  603. continue; // ignore P[i] above or on the lower line
  604. while (top > 0) // there are at least 2 points on the stack
  605. {
  606. // test if P[i] is left of the line at the stack top
  607. if ( isLeft( tmpPoints[top-1], tmpPoints[top], points[i]) > 0)
  608. break; // P[i] is a new hull vertex
  609. else
  610. top--; // pop top point off stack
  611. }
  612. toptmp = top + 1;
  613. if ( toptmp < n )
  614. tmpPoints[++top] = points[i]; // push P[i] onto stack
  615. }
  616. // Next, compute the upper hull on the stack H above the bottom hull
  617. if (maxmax != maxmin) // if distinct xmax points
  618. {
  619. toptmp = top + 1;
  620. if ( toptmp < n )
  621. tmpPoints[++top] = points[maxmax]; // push maxmax point onto stack
  622. }
  623. bot = top; // the bottom point of the upper hull stack
  624. i = maxmin;
  625. while (--i >= minmax)
  626. {
  627. // the upper line joins P[maxmax] with P[minmax]
  628. if ( isLeft( points[maxmax], points[minmax], points[i] ) >= 0 && i > minmax )
  629. continue; // ignore P[i] below or on the upper line
  630. while ( top > bot ) // at least 2 points on the upper stack
  631. {
  632. // test if P[i] is left of the line at the stack top
  633. if ( isLeft( tmpPoints[top-1], tmpPoints[top], points[i] ) > 0 )
  634. break; // P[i] is a new hull vertex
  635. else
  636. top--; // pop top point off stack
  637. }
  638. toptmp = top + 1;
  639. if ( toptmp < n )
  640. tmpPoints[++top] = points[i]; // push P[i] onto stack
  641. }
  642. if (minmax != minmin)
  643. {
  644. toptmp = top + 1;
  645. if ( toptmp < n )
  646. tmpPoints[++top] = points[minmin]; // push joining endpoint onto stack
  647. }
  648. outPoints->merge( tmpPoints );
  649. return top + 1;
  650. }
  651. void DecalManager::_generateWindingOrder( const Point3F &cornerPoint, Vector<Point3F> *sortPoints )
  652. {
  653. // This block of code is used to find
  654. // the winding order for the points in our quad.
  655. // First, choose an arbitrary corner point.
  656. // We'll use the "lowerRight" point.
  657. Point3F relPoint( 0, 0, 0 );
  658. // See comment below about radius.
  659. //F32 radius = 0;
  660. F32 theta = 0;
  661. Vector<Point4F> tmpPoints;
  662. for ( U32 i = 0; i < (*sortPoints).size(); i++ )
  663. {
  664. const Point3F &pnt = (*sortPoints)[i];
  665. relPoint = cornerPoint - pnt;
  666. // Get the radius (r^2 = x^2 + y^2).
  667. // This is commented because for a quad
  668. // you typically can't have the same values
  669. // for theta, which is the caveat which would
  670. // require sorting by the radius.
  671. //radius = mSqrt( (relPoint.x * relPoint.x) + (relPoint.y * relPoint.y) );
  672. // Get the theta value for the
  673. // interval -PI, PI.
  674. // This algorithm for determining the
  675. // theta value is defined by
  676. // | arctan( y / x ) if x > 0
  677. // | arctan( y / x ) if x < 0 and y >= 0
  678. // theta = | arctan( y / x ) if x < 0 and y < 0
  679. // | PI / 2 if x = 0 and y > 0
  680. // | -( PI / 2 ) if x = 0 and y < 0
  681. if ( relPoint.x > 0.0f )
  682. theta = mAtan2( relPoint.y, relPoint.x );
  683. else if ( relPoint.x < 0.0f )
  684. {
  685. if ( relPoint.y >= 0.0f )
  686. theta = mAtan2( relPoint.y, relPoint.x ) + M_PI_F;
  687. else if ( relPoint.y < 0.0f )
  688. theta = mAtan2( relPoint.y, relPoint.x ) - M_PI_F;
  689. }
  690. else if ( relPoint.x == 0.0f )
  691. {
  692. if ( relPoint.y > 0.0f )
  693. theta = M_PI_F / 2.0f;
  694. else if ( relPoint.y < 0.0f )
  695. theta = -(M_PI_F / 2.0f);
  696. }
  697. tmpPoints.push_back( Point4F( pnt.x, pnt.y, pnt.z, theta ) );
  698. }
  699. dQsort( tmpPoints.address(), tmpPoints.size(), sizeof( Point4F ), cmpQuadPointTheta );
  700. for ( U32 i = 0; i < tmpPoints.size(); i++ )
  701. {
  702. const Point4F &tmpPoint = tmpPoints[i];
  703. (*sortPoints)[i].set( tmpPoint.x, tmpPoint.y, tmpPoint.z );
  704. }
  705. }
  706. void DecalManager::_allocBuffers( DecalInstance *inst )
  707. {
  708. const S32 sizeClass = _getSizeClass( inst );
  709. void* data;
  710. if ( sizeClass == -1 )
  711. data = dMalloc( sizeof( DecalVertex ) * inst->mVertCount + sizeof( U16 ) * inst->mIndxCount );
  712. else
  713. data = mChunkers[sizeClass]->alloc();
  714. inst->mVerts = reinterpret_cast< DecalVertex* >( data );
  715. data = (U8*)data + sizeof( DecalVertex ) * inst->mVertCount;
  716. inst->mIndices = reinterpret_cast< U16* >( data );
  717. }
  718. void DecalManager::_freeBuffers( DecalInstance *inst )
  719. {
  720. if ( inst->mVerts != NULL )
  721. {
  722. const S32 sizeClass = _getSizeClass( inst );
  723. if ( sizeClass == -1 )
  724. dFree( inst->mVerts );
  725. else
  726. {
  727. // Use FreeListChunker
  728. mChunkers[sizeClass]->free( inst->mVerts );
  729. }
  730. inst->mVerts = NULL;
  731. inst->mVertCount = 0;
  732. inst->mIndices = NULL;
  733. inst->mIndxCount = 0;
  734. }
  735. }
  736. void DecalManager::_freePools()
  737. {
  738. while ( !mVBPool.empty() )
  739. {
  740. delete mVBPool.last();
  741. mVBPool.pop_back();
  742. }
  743. while ( !mVBs.empty() )
  744. {
  745. delete mVBs.last();
  746. mVBs.pop_back();
  747. }
  748. while ( !mPBPool.empty() )
  749. {
  750. delete mPBPool.last();
  751. mPBPool.pop_back();
  752. }
  753. while ( !mPBs.empty() )
  754. {
  755. delete mPBs.last();
  756. mPBs.pop_back();
  757. }
  758. }
  759. S32 DecalManager::_getSizeClass( DecalInstance *inst ) const
  760. {
  761. U32 bytes = inst->mVertCount * sizeof( DecalVertex ) + inst->mIndxCount * sizeof ( U16 );
  762. if ( bytes <= SIZE_CLASS_0 )
  763. return 0;
  764. if ( bytes <= SIZE_CLASS_1 )
  765. return 1;
  766. if ( bytes <= SIZE_CLASS_2 )
  767. return 2;
  768. // Size is outside of the largest chunker.
  769. return -1;
  770. }
  771. void DecalManager::prepRenderImage( SceneRenderState* state )
  772. {
  773. PROFILE_SCOPE( DecalManager_RenderDecals );
  774. if ( !smDecalsOn || !mData )
  775. return;
  776. // Decals only render in the diffuse pass!
  777. // We technically could render them into reflections but prefer to save
  778. // the performance. This would also break the DecalInstance::mLastAlpha
  779. // optimization.
  780. if ( !state->isDiffusePass() )
  781. return;
  782. PROFILE_START( DecalManager_RenderDecals_SphereTreeCull );
  783. const Frustum& rootFrustum = state->getFrustum();
  784. // Populate vector of decal instances to be rendered with all
  785. // decals from visible decal spheres.
  786. SceneManager* sceneManager = state->getSceneManager();
  787. SceneZoneSpaceManager* zoneManager = sceneManager->getZoneManager();
  788. AssertFatal( zoneManager, "DecalManager::prepRenderImage - No zone manager!" );
  789. const Vector<DecalSphere*> &grid = mData->getSphereList();
  790. const bool haveOnlyOutdoorZone = ( zoneManager->getNumActiveZones() == 1 );
  791. mDecalQueue.clear();
  792. for ( U32 i = 0; i < grid.size(); i++ )
  793. {
  794. DecalSphere* decalSphere = grid[i];
  795. const SphereF& worldSphere = decalSphere->mWorldSphere;
  796. // See if this decal sphere can be culled.
  797. const SceneCullingState& cullingState = state->getCullingState();
  798. if( haveOnlyOutdoorZone )
  799. {
  800. U32 outdoorZone = SceneZoneSpaceManager::RootZoneId;
  801. if( cullingState.isCulled( worldSphere, &outdoorZone, 1 ) )
  802. continue;
  803. }
  804. else
  805. {
  806. // Update the zoning state of the sphere, if we need to.
  807. if( decalSphere->mZones.size() == 0 )
  808. decalSphere->updateZoning( zoneManager );
  809. // Skip the sphere if it is not visible in any of its zones.
  810. if( cullingState.isCulled( worldSphere, decalSphere->mZones.address(), decalSphere->mZones.size() ) )
  811. continue;
  812. }
  813. // TODO: If each sphere stored its largest decal instance we
  814. // could do an LOD step on it here and skip adding any of the
  815. // decals in the sphere.
  816. mDecalQueue.merge( decalSphere->mItems );
  817. }
  818. PROFILE_END();
  819. PROFILE_START( DecalManager_RenderDecals_Update );
  820. const U32 &curSimTime = Sim::getCurrentTime();
  821. F32 pixelSize;
  822. U32 delta, diff;
  823. DecalInstance *dinst;
  824. DecalData *ddata;
  825. // Loop through DecalQueue once for preRendering work.
  826. // 1. Update DecalInstance fade (over time)
  827. // 2. Clip geometry if flagged to do so.
  828. // 3. Calculate lod - if decal is far enough away it will not render.
  829. for ( U32 i = 0; i < mDecalQueue.size(); i++ )
  830. {
  831. dinst = mDecalQueue[i];
  832. ddata = dinst->mDataBlock;
  833. // LOD calculation...
  834. pixelSize = dinst->calcPixelSize( state->getViewport().extent.y, state->getCameraPosition(), state->getWorldToScreenScale().y );
  835. if ( pixelSize != F32_MAX && pixelSize < ddata->fadeEndPixelSize )
  836. {
  837. mDecalQueue.erase_fast( i );
  838. i--;
  839. continue;
  840. }
  841. // We will try to render this decal... so do any
  842. // final adjustments to it before rendering.
  843. // Update fade and delete expired.
  844. if ( !( dinst->mFlags & PermanentDecal || dinst->mFlags & CustomDecal ) )
  845. {
  846. delta = ( curSimTime - dinst->mCreateTime );
  847. if ( delta > dinst->mDataBlock->lifeSpan )
  848. {
  849. diff = delta - dinst->mDataBlock->lifeSpan;
  850. dinst->mVisibility = 1.0f - (F32)diff / (F32)dinst->mDataBlock->fadeTime;
  851. if ( dinst->mVisibility <= 0.0f )
  852. {
  853. mDecalQueue.erase_fast( i );
  854. removeDecal( dinst );
  855. i--;
  856. continue;
  857. }
  858. }
  859. }
  860. // Build clipped geometry for this decal if needed.
  861. if ( dinst->mFlags & ClipDecal && !( dinst->mFlags & CustomDecal ) )
  862. {
  863. // Turn off the flag so we don't continually try to clip
  864. // if it fails.
  865. dinst->mFlags = dinst->mFlags & ~ClipDecal;
  866. if ( !(dinst->mFlags & CustomDecal) && !clipDecal( dinst ) )
  867. {
  868. // Clipping failed to get any geometry...
  869. // Remove it from the render queue.
  870. mDecalQueue.erase_fast( i );
  871. i--;
  872. // If the decal is one placed at run-time (not the editor)
  873. // then we should also permanently delete the decal instance.
  874. if ( !(dinst->mFlags & SaveDecal) )
  875. {
  876. removeDecal( dinst );
  877. }
  878. // If this is a decal placed by the editor it will be
  879. // flagged to attempt clipping again the next time it is
  880. // modified. For now we just skip rendering it.
  881. continue;
  882. }
  883. }
  884. // If we get here and the decal still does not have any geometry
  885. // skip rendering it. It must be an editor placed decal that failed
  886. // to clip any geometry but has not yet been flagged to try again.
  887. if ( !dinst->mVerts || dinst->mVertCount == 0 || dinst->mIndxCount == 0 )
  888. {
  889. mDecalQueue.erase_fast( i );
  890. i--;
  891. continue;
  892. }
  893. // Calculate the alpha value for this decal and apply it to the verts.
  894. {
  895. PROFILE_START( DecalManager_RenderDecals_Update_SetAlpha );
  896. F32 alpha = 1.0f;
  897. // Only necessary for decals which fade over time or distance.
  898. if ( !( dinst->mFlags & PermanentDecal ) || dinst->mDataBlock->fadeStartPixelSize >= 0.0f )
  899. {
  900. if ( pixelSize < ddata->fadeStartPixelSize )
  901. {
  902. const F32 range = ddata->fadeStartPixelSize - ddata->fadeEndPixelSize;
  903. alpha = 1.0f - mClampF( ( ddata->fadeStartPixelSize - pixelSize ) / range, 0.0f, 1.0f );
  904. }
  905. alpha *= dinst->mVisibility;
  906. }
  907. // If the alpha value has not changed since last render avoid
  908. // looping through all the verts!
  909. if ( alpha != dinst->mLastAlpha )
  910. {
  911. // calculate the swizzles color once, outside the loop.
  912. GFXVertexColor color;
  913. color.set( 255, 255, 255, (U8)(alpha * 255.0f) );
  914. for ( U32 v = 0; v < dinst->mVertCount; v++ )
  915. dinst->mVerts[v].color = color;
  916. dinst->mLastAlpha = alpha;
  917. }
  918. PROFILE_END();
  919. }
  920. }
  921. PROFILE_END();
  922. if ( mDecalQueue.empty() )
  923. return;
  924. // Sort queued decals...
  925. // 1. Editor decals - in render priority order first, creation time second, and material third.
  926. // 2. Dynamic decals - in render priority order first and creation time second.
  927. //
  928. // With the constraint that decals with different render priority cannot
  929. // be rendered together in the same draw call.
  930. PROFILE_START( DecalManager_RenderDecals_Sort );
  931. dQsort( mDecalQueue.address(), mDecalQueue.size(), sizeof(DecalInstance*), cmpDecalRenderOrder );
  932. PROFILE_END();
  933. PROFILE_SCOPE( DecalManager_RenderDecals_RenderBatch );
  934. RenderPassManager *renderPass = state->getRenderPass();
  935. // Base render instance we use for convenience.
  936. // Data shared by all instances we allocate below can be copied
  937. // from the base instance at the same time.
  938. MeshRenderInst baseRenderInst;
  939. baseRenderInst.clear();
  940. MatrixF *tempMat = renderPass->allocUniqueXform( MatrixF( true ) );
  941. MathUtils::getZBiasProjectionMatrix( gDecalBias, rootFrustum, tempMat );
  942. baseRenderInst.projection = tempMat;
  943. baseRenderInst.objectToWorld = &MatrixF::Identity;
  944. baseRenderInst.worldToCamera = renderPass->allocSharedXform(RenderPassManager::View);
  945. baseRenderInst.type = RenderPassManager::RIT_Decal;
  946. // Make it the sort distance the max distance so that
  947. // it renders after all the other opaque geometry in
  948. // the prepass bin.
  949. baseRenderInst.sortDistSq = F32_MAX;
  950. Vector<DecalBatch> batches;
  951. DecalBatch *currentBatch = NULL;
  952. // Loop through DecalQueue collecting them into render batches.
  953. for ( U32 i = 0; i < mDecalQueue.size(); i++ )
  954. {
  955. DecalInstance *decal = mDecalQueue[i];
  956. DecalData *data = decal->mDataBlock;
  957. Material *mat = data->getMaterial();
  958. if ( currentBatch == NULL )
  959. {
  960. // Start a new batch, beginning with this decal.
  961. batches.increment();
  962. currentBatch = &batches.last();
  963. currentBatch->startDecal = i;
  964. currentBatch->decalCount = 1;
  965. currentBatch->iCount = decal->mIndxCount;
  966. currentBatch->vCount = decal->mVertCount;
  967. currentBatch->mat = mat;
  968. currentBatch->matInst = decal->mDataBlock->getMaterialInstance();
  969. currentBatch->priority = decal->getRenderPriority();
  970. currentBatch->dynamic = !(decal->mFlags & SaveDecal);
  971. continue;
  972. }
  973. if ( currentBatch->iCount + decal->mIndxCount >= smMaxIndices ||
  974. currentBatch->vCount + decal->mVertCount >= smMaxVerts ||
  975. currentBatch->mat != mat ||
  976. currentBatch->priority != decal->getRenderPriority() ||
  977. decal->mCustomTex )
  978. {
  979. // End batch.
  980. currentBatch = NULL;
  981. i--;
  982. continue;
  983. }
  984. // Add on to current batch.
  985. currentBatch->decalCount++;
  986. currentBatch->iCount += decal->mIndxCount;
  987. currentBatch->vCount += decal->mVertCount;
  988. }
  989. // Make sure our primitive and vertex buffer handle storage is
  990. // big enough to take all batches. Doing this now avoids reallocation
  991. // later on which would invalidate all the pointers we already had
  992. // passed into render instances.
  993. //mPBs.reserve( batches.size() );
  994. //mVBs.reserve( batches.size() );
  995. // System memory array of verts and indices so we can fill them incrementally
  996. // and then memcpy to the graphics device buffers in one call.
  997. static DecalVertex vertData[smMaxVerts];
  998. static U16 indexData[smMaxIndices];
  999. // Loop through batches allocating buffers and submitting render instances.
  1000. for ( U32 i = 0; i < batches.size(); i++ )
  1001. {
  1002. DecalBatch &currentBatch = batches[i];
  1003. // Copy data into the system memory arrays, from all decals in this batch...
  1004. DecalVertex *vpPtr = vertData;
  1005. U16 *pbPtr = indexData;
  1006. U32 lastDecal = currentBatch.startDecal + currentBatch.decalCount;
  1007. U32 voffset = 0;
  1008. U32 ioffset = 0;
  1009. // This is an ugly hack for ProjectedShadow!
  1010. GFXTextureObject *customTex = NULL;
  1011. for ( U32 j = currentBatch.startDecal; j < lastDecal; j++ )
  1012. {
  1013. DecalInstance *dinst = mDecalQueue[j];
  1014. for ( U32 k = 0; k < dinst->mIndxCount; k++ )
  1015. {
  1016. *( pbPtr + ioffset + k ) = dinst->mIndices[k] + voffset;
  1017. }
  1018. ioffset += dinst->mIndxCount;
  1019. dMemcpy( vpPtr + voffset, dinst->mVerts, sizeof( DecalVertex ) * dinst->mVertCount );
  1020. voffset += dinst->mVertCount;
  1021. // Ugly hack for ProjectedShadow!
  1022. if ( (dinst->mFlags & CustomDecal) && dinst->mCustomTex != NULL )
  1023. customTex = *dinst->mCustomTex;
  1024. }
  1025. AssertFatal( ioffset == currentBatch.iCount, "bad" );
  1026. AssertFatal( voffset == currentBatch.vCount, "bad" );
  1027. // Get handles to video memory buffers we will be filling...
  1028. GFXVertexBufferHandle<DecalVertex> *vb = NULL;
  1029. if ( mVBPool.empty() )
  1030. {
  1031. // If the Pool is empty allocate a new one.
  1032. vb = new GFXVertexBufferHandle<DecalVertex>;
  1033. vb->set( GFX, smMaxVerts, GFXBufferTypeDynamic );
  1034. }
  1035. else
  1036. {
  1037. // Otherwise grab from the pool.
  1038. vb = mVBPool.last();
  1039. mVBPool.pop_back();
  1040. }
  1041. // Push into our vector of 'in use' buffers.
  1042. mVBs.push_back( vb );
  1043. // Ready to start filling.
  1044. vpPtr = vb->lock();
  1045. // Same deal as above...
  1046. GFXPrimitiveBufferHandle *pb = NULL;
  1047. if ( mPBPool.empty() )
  1048. {
  1049. pb = new GFXPrimitiveBufferHandle;
  1050. pb->set( GFX, smMaxIndices, 0, GFXBufferTypeDynamic );
  1051. }
  1052. else
  1053. {
  1054. pb = mPBPool.last();
  1055. mPBPool.pop_back();
  1056. }
  1057. mPBs.push_back( pb );
  1058. pb->lock( &pbPtr );
  1059. // Memcpy from system to video memory.
  1060. dMemcpy( vpPtr, vertData, sizeof( DecalVertex ) * currentBatch.vCount );
  1061. dMemcpy( pbPtr, indexData, sizeof( U16 ) * currentBatch.iCount );
  1062. pb->unlock();
  1063. vb->unlock();
  1064. // DecalManager must hold handles to these buffers so they remain valid,
  1065. // we don't actually use them elsewhere.
  1066. //mPBs.push_back( pb );
  1067. //mVBs.push_back( vb );
  1068. // Get the best lights for the current camera position
  1069. // if the materail is forward lit and we haven't got them yet.
  1070. if ( currentBatch.matInst->isForwardLit() && !baseRenderInst.lights[0] )
  1071. {
  1072. LightQuery query;
  1073. query.init( rootFrustum.getPosition(),
  1074. rootFrustum.getTransform().getForwardVector(),
  1075. rootFrustum.getFarDist() );
  1076. query.getLights( baseRenderInst.lights, 8 );
  1077. }
  1078. // Submit render inst...
  1079. MeshRenderInst *ri = renderPass->allocInst<MeshRenderInst>();
  1080. *ri = baseRenderInst;
  1081. ri->primBuff = pb;
  1082. ri->vertBuff = vb;
  1083. ri->matInst = currentBatch.matInst;
  1084. ri->prim = renderPass->allocPrim();
  1085. ri->prim->type = GFXTriangleList;
  1086. ri->prim->minIndex = 0;
  1087. ri->prim->startIndex = 0;
  1088. ri->prim->numPrimitives = currentBatch.iCount / 3;
  1089. ri->prim->startVertex = 0;
  1090. ri->prim->numVertices = currentBatch.vCount;
  1091. // Ugly hack for ProjectedShadow!
  1092. if ( customTex )
  1093. ri->miscTex = customTex;
  1094. // The decal bin will contain render instances for both decals and decalRoad's.
  1095. // Dynamic decals render last, then editor decals and roads in priority order.
  1096. // DefaultKey is sorted in descending order.
  1097. ri->defaultKey = currentBatch.dynamic ? 0xFFFFFFFF : (U32)currentBatch.priority;
  1098. ri->defaultKey2 = 1;//(U32)lastDecal->mDataBlock;
  1099. renderPass->addInst( ri );
  1100. }
  1101. #ifdef TORQUE_GATHER_METRICS
  1102. Con::setIntVariable( "$Decal::Batches", batches.size() );
  1103. Con::setIntVariable( "$Decal::Buffers", mPBs.size() + mPBPool.size() );
  1104. Con::setIntVariable( "$Decal::DecalsRendered", mDecalQueue.size() );
  1105. #endif
  1106. if( smDebugRender && gEditingMission )
  1107. {
  1108. ObjectRenderInst* ri = state->getRenderPass()->allocInst< ObjectRenderInst >();
  1109. ri->renderDelegate.bind( this, &DecalManager::_renderDecalSpheres );
  1110. ri->type = RenderPassManager::RIT_Editor;
  1111. ri->defaultKey = 0;
  1112. ri->defaultKey2 = 0;
  1113. state->getRenderPass()->addInst( ri );
  1114. }
  1115. }
  1116. void DecalManager::_renderDecalSpheres( ObjectRenderInst* ri, SceneRenderState* state, BaseMatInstance* overrideMat )
  1117. {
  1118. if( !mData )
  1119. return;
  1120. const Vector<DecalSphere*> &grid = mData->getSphereList();
  1121. GFXDrawUtil *drawUtil = GFX->getDrawUtil();
  1122. ColorI sphereColor( 0, 255, 0, 45 );
  1123. GFXStateBlockDesc desc;
  1124. desc.setBlend( true );
  1125. desc.setZReadWrite( true, false );
  1126. desc.setCullMode( GFXCullNone );
  1127. for ( U32 i = 0; i < grid.size(); i++ )
  1128. {
  1129. DecalSphere *decalSphere = grid[i];
  1130. const SphereF &worldSphere = decalSphere->mWorldSphere;
  1131. if( state->getFrustum().isCulled( worldSphere ) )
  1132. continue;
  1133. drawUtil->drawSphere( desc, worldSphere.radius, worldSphere.center, sphereColor );
  1134. }
  1135. }
  1136. bool DecalManager::_createDataFile()
  1137. {
  1138. AssertFatal( !mData, "DecalManager::tried to create duplicate data file?" );
  1139. // We need to construct a default file name
  1140. char fileName[1024];
  1141. fileName[0] = 0;
  1142. // See if we know our current mission name
  1143. char missionName[1024];
  1144. dStrcpy( missionName, Con::getVariable( "$Client::MissionFile" ) );
  1145. char *dot = dStrstr((const char*)missionName, ".mis");
  1146. if(dot)
  1147. *dot = '\0';
  1148. dSprintf( fileName, sizeof(fileName), "%s.mis.decals", missionName );
  1149. mDataFileName = StringTable->insert( fileName );
  1150. // If the file doesn't exist, create an empty file.
  1151. if( !Torque::FS::IsFile( fileName ) )
  1152. {
  1153. FileStream stream;
  1154. if( stream.open( mDataFileName, Torque::FS::File::Write ) )
  1155. {
  1156. DecalDataFile dataFile;
  1157. dataFile.write( stream );
  1158. }
  1159. }
  1160. mData = ResourceManager::get().load( mDataFileName );
  1161. return (bool)mData;
  1162. }
  1163. void DecalManager::saveDecals( const UTF8* fileName )
  1164. {
  1165. if( !mData )
  1166. return;
  1167. // Create the file.
  1168. FileStream stream;
  1169. if ( !stream.open( fileName, Torque::FS::File::Write ) )
  1170. {
  1171. Con::errorf( "DecalManager::saveDecals - Could not open '%s' for writing!", fileName );
  1172. return;
  1173. }
  1174. // Write the data.
  1175. if( !mData->write( stream ) )
  1176. {
  1177. Con::errorf( "DecalManager::saveDecals - Failed to write '%s'", fileName );
  1178. return;
  1179. }
  1180. mDirty = false;
  1181. }
  1182. bool DecalManager::loadDecals( const UTF8 *fileName )
  1183. {
  1184. if( mData )
  1185. clearData();
  1186. mData = ResourceManager::get().load( fileName );
  1187. mDirty = false;
  1188. return mData != NULL;
  1189. }
  1190. void DecalManager::clearData()
  1191. {
  1192. mClearDataSignal.trigger();
  1193. // Free all geometry buffers.
  1194. if( mData )
  1195. {
  1196. const Vector< DecalSphere* > grid = mData->getSphereList();
  1197. for( U32 i = 0; i < grid.size(); ++ i )
  1198. {
  1199. DecalSphere* sphere = grid[ i ];
  1200. for( U32 n = 0; n < sphere->mItems.size(); ++ n )
  1201. _freeBuffers( sphere->mItems[ n ] );
  1202. }
  1203. }
  1204. mData = NULL;
  1205. mDecalInstanceVec.clear();
  1206. _freePools();
  1207. }
  1208. bool DecalManager::onSceneAdd()
  1209. {
  1210. if( !Parent::onSceneAdd() )
  1211. return false;
  1212. SceneZoneSpaceManager::getZoningChangedSignal().notify( this, &DecalManager::_handleZoningChangedEvent );
  1213. return true;
  1214. }
  1215. void DecalManager::onSceneRemove()
  1216. {
  1217. SceneZoneSpaceManager::getZoningChangedSignal().remove( this, &DecalManager::_handleZoningChangedEvent );
  1218. Parent::onSceneRemove();
  1219. }
  1220. void DecalManager::_handleZoningChangedEvent( SceneZoneSpaceManager* zoneManager )
  1221. {
  1222. if( zoneManager != getSceneManager()->getZoneManager() || !getDecalDataFile() )
  1223. return;
  1224. // Clear the zoning state of all DecalSpheres in the data file.
  1225. const Vector< DecalSphere* > grid = getDecalDataFile()->getSphereList();
  1226. const U32 numSpheres = grid.size();
  1227. for( U32 i = 0; i < numSpheres; ++ i )
  1228. grid[ i ]->mZones.clear();
  1229. }
  1230. DefineEngineFunction( decalManagerSave, void, ( String decalSaveFile ), ( "" ),
  1231. "Saves the decals for the active mission in the entered filename.\n"
  1232. "@param decalSaveFile Filename to save the decals to.\n"
  1233. "@tsexample\n"
  1234. "// Set the filename to save the decals in. If no filename is set, then the\n"
  1235. "// decals will default to <activeMissionName>.mis.decals\n"
  1236. "%fileName = \"./missionDecals.mis.decals\";\n"
  1237. "// Inform the decal manager to save the decals for the active mission.\n"
  1238. "decalManagerSave( %fileName );\n"
  1239. "@endtsexample\n"
  1240. "@ingroup Decals" )
  1241. {
  1242. // If not given a file name, synthesize one.
  1243. if( decalSaveFile.isEmpty() )
  1244. {
  1245. String fileName = String::ToString( "%s.decals", Con::getVariable( "$Client::MissionFile" ) );
  1246. char fullName[ 4096 ];
  1247. Platform::makeFullPathName( fileName, fullName, sizeof( fullName ) );
  1248. decalSaveFile = String( fullName );
  1249. }
  1250. // Write the data.
  1251. gDecalManager->saveDecals( decalSaveFile );
  1252. }
  1253. DefineEngineFunction( decalManagerLoad, bool, ( const char* fileName ),,
  1254. "Clears existing decals and replaces them with decals loaded from the specified file.\n"
  1255. "@param fileName Filename to load the decals from.\n"
  1256. "@return True if the decal manager was able to load the requested file, "
  1257. "false if it could not.\n"
  1258. "@tsexample\n"
  1259. "// Set the filename to load the decals from.\n"
  1260. "%fileName = \"./missionDecals.mis.decals\";\n"
  1261. "// Inform the decal manager to load the decals from the entered filename.\n"
  1262. "decalManagerLoad( %fileName );\n"
  1263. "@endtsexample\n"
  1264. "@ingroup Decals" )
  1265. {
  1266. return gDecalManager->loadDecals( fileName );
  1267. }
  1268. DefineEngineFunction( decalManagerDirty, bool, (),,
  1269. "Returns whether the decal manager has unsaved modifications.\n"
  1270. "@return True if the decal manager has unsaved modifications, false if "
  1271. "everything has been saved.\n"
  1272. "@tsexample\n"
  1273. "// Ask the decal manager if it has unsaved modifications.\n"
  1274. "%hasUnsavedModifications = decalManagerDirty();\n"
  1275. "@endtsexample\n"
  1276. "@ingroup Decals" )
  1277. {
  1278. return gDecalManager->isDirty();
  1279. }
  1280. DefineEngineFunction( decalManagerClear, void, (),,
  1281. "Removes all decals currently loaded in the decal manager.\n"
  1282. "@tsexample\n"
  1283. "// Tell the decal manager to remove all existing decals.\n"
  1284. "decalManagerClear();\n"
  1285. "@endtsexample\n"
  1286. "@ingroup Decals" )
  1287. {
  1288. gDecalManager->clearData();
  1289. }
  1290. DefineEngineFunction( decalManagerAddDecal, S32,
  1291. ( Point3F position, Point3F normal, F32 rot, F32 scale, DecalData* decalData, bool isImmortal), ( false ),
  1292. "Adds a new decal to the decal manager.\n"
  1293. "@param position World position for the decal.\n"
  1294. "@param normal Decal normal vector (if the decal was a tire lying flat on a "
  1295. "surface, this is the vector pointing in the direction of the axle).\n"
  1296. "@param rot Angle (in radians) to rotate this decal around its normal vector.\n"
  1297. "@param scale Scale factor applied to the decal.\n"
  1298. "@param decalData DecalData datablock to use for the new decal.\n"
  1299. "@param isImmortal Whether or not this decal is immortal. If immortal, it "
  1300. "does not expire automatically and must be removed explicitly.\n"
  1301. "@return Returns the ID of the new Decal object or -1 on failure.\n"
  1302. "@tsexample\n"
  1303. "// Specify the decal position\n"
  1304. "%position = \"1.0 1.0 1.0\";\n\n"
  1305. "// Specify the up vector\n"
  1306. "%normal = \"0.0 0.0 1.0\";\n\n"
  1307. "// Add the new decal.\n"
  1308. "%decalObj = decalManagerAddDecal( %position, %normal, 0.5, 0.35, ScorchBigDecal, false );\n"
  1309. "@endtsexample\n"
  1310. "@ingroup Decals" )
  1311. {
  1312. if( !decalData )
  1313. {
  1314. Con::errorf( "decalManagerAddDecal - Invalid Decal DataBlock" );
  1315. return -1;
  1316. }
  1317. U8 flags = 0;
  1318. if( isImmortal )
  1319. flags |= PermanentDecal;
  1320. DecalInstance* inst = gDecalManager->addDecal( position, normal, rot, decalData, scale, -1, flags );
  1321. if( !inst )
  1322. {
  1323. Con::errorf( "decalManagerAddDecal - Unable to create decal instance." );
  1324. return -1;
  1325. }
  1326. // Add the decal to the instance vector.
  1327. inst->mId = gDecalManager->mDecalInstanceVec.size();
  1328. gDecalManager->mDecalInstanceVec.push_back( inst );
  1329. return inst->mId;
  1330. }
  1331. DefineEngineFunction( decalManagerRemoveDecal, bool, ( S32 decalID ),,
  1332. "Remove specified decal from the scene.\n"
  1333. "@param decalID ID of the decal to remove.\n"
  1334. "@return Returns true if successful, false if decal ID not found.\n"
  1335. "@tsexample\n"
  1336. "// Specify a decal ID to be removed\n"
  1337. "%decalID = 1;\n\n"
  1338. "// Tell the decal manager to remove the specified decal ID.\n"
  1339. "decalManagerRemoveDecal( %decalId )\n"
  1340. "@endtsexample\n"
  1341. "@ingroup Decals" )
  1342. {
  1343. DecalInstance *inst = gDecalManager->getDecal( decalID );
  1344. if( !inst )
  1345. return false;
  1346. gDecalManager->removeDecal(inst);
  1347. return true;
  1348. }