renderParticleMgr.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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 "renderInstance/renderParticleMgr.h"
  24. #include "renderInstance/renderPrePassMgr.h"
  25. #include "scene/sceneManager.h"
  26. #include "scene/sceneObject.h"
  27. #include "scene/sceneRenderState.h"
  28. #include "gfx/gfxPrimitiveBuffer.h"
  29. #include "gfx/gfxTransformSaver.h"
  30. #include "gfx/gfxDebugEvent.h"
  31. #include "materials/shaderData.h"
  32. #include "materials/sceneData.h"
  33. #include "materials/matInstance.h"
  34. #include "gfx/util/screenspace.h"
  35. #include "gfx/gfxDrawUtil.h"
  36. #include "collision/clippedPolyList.h"
  37. static const Point4F cubePoints[9] =
  38. {
  39. Point4F(-0.5, -0.5, -0.5, 1.0f), Point4F(-0.5, -0.5, 0.5, 1.0f), Point4F(-0.5, 0.5, -0.5, 1.0f), Point4F(-0.5, 0.5, 0.5, 1.0f),
  40. Point4F( 0.5, -0.5, -0.5, 1.0f), Point4F( 0.5, -0.5, 0.5, 1.0f), Point4F( 0.5, 0.5, -0.5, 1.0f), Point4F( 0.5, 0.5, 0.5, 1.0f)
  41. };
  42. GFXImplementVertexFormat( CompositeQuadVert )
  43. {
  44. addElement( "COLOR", GFXDeclType_Color );
  45. }
  46. IMPLEMENT_CONOBJECT(RenderParticleMgr);
  47. ConsoleDocClass( RenderParticleMgr,
  48. "@brief A render bin which renders particle geometry.\n\n"
  49. "This render bin gathers particle render instances, sorts, and renders them. "
  50. "It is currently used by ParticleEmitter and LightFlareData.\n\n"
  51. "@ingroup RenderBin\n" );
  52. const RenderInstType RenderParticleMgr::RIT_Particles("ParticleSystem");
  53. // TODO: Replace these once they are supported via options
  54. const bool RenderToParticleTarget = true;
  55. const bool RenderToSingleTarget = true;
  56. RenderParticleMgr::RenderParticleMgr()
  57. : Parent( RenderParticleMgr::RIT_Particles,
  58. 1.0f,
  59. 1.0f,
  60. GFXFormatR8G8B8A8,
  61. Point2I( Parent::DefaultTargetSize, Parent::DefaultTargetSize),
  62. RenderToParticleTarget ? Parent::DefaultTargetChainLength : 0 ),
  63. mParticleShader( NULL )
  64. {
  65. // Render particles at 1/4 resolution
  66. mTargetSizeType = WindowSizeScaled;
  67. mTargetScale.set(0.5f, 0.5f);
  68. // We use the target chain like a texture pool, not like a swap chain
  69. if(!RenderToSingleTarget)
  70. setTargetChainLength(5);
  71. else
  72. mOffscreenSystems.setSize(1);
  73. notifyType( RenderPassManager::RIT_Particle );
  74. LightManager::smActivateSignal.notify( this, &RenderParticleMgr::_onLMActivate );
  75. }
  76. RenderParticleMgr::~RenderParticleMgr()
  77. {
  78. LightManager::smActivateSignal.remove( this, &RenderParticleMgr::_onLMActivate );
  79. }
  80. void RenderParticleMgr::setTargetChainLength( const U32 chainLength )
  81. {
  82. Parent::setTargetChainLength(chainLength);
  83. if(!RenderToSingleTarget)
  84. mOffscreenSystems.setSize(chainLength);
  85. }
  86. void RenderParticleMgr::addElement( RenderInst *inst )
  87. {
  88. ParticleRenderInst *pri = reinterpret_cast<ParticleRenderInst *>(inst);
  89. // If this system isn't waiting for an offscreen draw, skip it
  90. if( pri->systemState != PSS_AwaitingOffscreenDraw )
  91. return;
  92. // If offscreen rendering isn't enabled, set to high-res, and skip
  93. if(!mOffscreenRenderEnabled)
  94. {
  95. pri->systemState = PSS_AwaitingHighResDraw;
  96. return;
  97. }
  98. // Assign a target index
  99. RectF screenRect;
  100. S32 chainIndex = -1;
  101. if(RenderToSingleTarget)
  102. {
  103. pri->targetIndex = 0;
  104. screenRect.point.set(-1.0f, -1.0f);
  105. screenRect.extent.set(2.0f, 2.0f);
  106. mElementList.setSize(1);
  107. }
  108. else
  109. {
  110. // If we can't fit this into the offscreen systems, skip it, it will render
  111. // high resolution
  112. //
  113. // TODO: Improve this once we are grouping systems
  114. if( mTargetChainIdx == OffscreenPoolSize )
  115. return;
  116. // Transform bounding box into screen space
  117. const static PlaneF planes[] = {
  118. PlaneF(Point3F( 1.0f, 0.0f, 0.0f), Point3F(-1.0f, 0.0f, 0.0f)),
  119. PlaneF(Point3F(-1.0f, 0.0f, 0.0f), Point3F( 1.0f, 0.0f, 0.0f)),
  120. PlaneF(Point3F( 0.0f, 1.0f, 0.0f), Point3F( 0.0f, -1.0f, 0.0f)),
  121. PlaneF(Point3F( 0.0f, -1.0f, 0.0f), Point3F( 0.0f, 1.0f, 0.0f)),
  122. PlaneF(Point3F( 0.0f, 0.0f, 0.0f), Point3F( 0.0f, 0.0f, 1.0f)),
  123. PlaneF(Point3F( 0.0f, 0.0f, 1.0f), Point3F( 0.0f, 0.0f, -1.0f)),
  124. };
  125. const static dsize_t numPlanes = sizeof(planes) / sizeof(PlaneF);
  126. // Set up a clipper
  127. ClippedPolyList screenClipper;
  128. screenClipper.setBaseTransform(MatrixF::Identity);
  129. screenClipper.setTransform(&MatrixF::Identity, Point3F::One);
  130. TORQUE_UNUSED(numPlanes);
  131. Point4F tempPt(0.0f, 0.0f, 0.0f, 1.0f);
  132. pri->bbModelViewProj->mul(tempPt);
  133. tempPt = tempPt / tempPt.w;
  134. for(S32 i = 0; i < 1; i++)
  135. {
  136. screenClipper.mPlaneList.push_back(planes[i]);
  137. screenClipper.mPlaneList.last() += tempPt.asPoint3F();
  138. }
  139. Box3F screenSpaceBoundingBox;
  140. screenSpaceBoundingBox.minExtents = Point3F::Zero;
  141. screenSpaceBoundingBox.maxExtents = Point3F::Zero;
  142. for(S32 i = 0; i < 8; i++)
  143. {
  144. tempPt = cubePoints[i];
  145. pri->bbModelViewProj->mul(tempPt);
  146. tempPt = tempPt / tempPt.w;
  147. screenSpaceBoundingBox.maxExtents.setMax(tempPt.asPoint3F());
  148. screenSpaceBoundingBox.minExtents.setMin(tempPt.asPoint3F());
  149. }
  150. screenClipper.addBox(screenSpaceBoundingBox);
  151. screenClipper.cullUnusedVerts();
  152. //screenClipper.triangulate();
  153. // Empty vertex list? Skip!
  154. if(screenClipper.mVertexList.empty())
  155. {
  156. pri->systemState = PSS_AwaitingHighResDraw;
  157. return;
  158. }
  159. Point2F minExtents(0.0f, 0.0f), maxExtents(0.0f, 0.0f);
  160. for(ClippedPolyList::VertexList::const_iterator itr = screenClipper.mVertexList.begin();
  161. itr != screenClipper.mVertexList.end(); itr++)
  162. {
  163. minExtents.x = getMin(minExtents.x, (*itr).point.x);
  164. minExtents.y = getMin(minExtents.y, (*itr).point.y);
  165. maxExtents.x = getMax(maxExtents.x, (*itr).point.x);
  166. maxExtents.y = getMax(maxExtents.y, (*itr).point.y);
  167. }
  168. screenRect.set( minExtents, maxExtents - minExtents );
  169. // Check the size of the system on screen. If it is small, it won't
  170. // be eating fillrate anyway, so just draw it high-resolution.
  171. // The value it checks against is one I found from experimentation,
  172. // not anything really meaningful.
  173. if( screenRect.extent.x < 0.35f || screenRect.extent.y < 0.35f )
  174. {
  175. pri->systemState = PSS_AwaitingHighResDraw;
  176. return;
  177. }
  178. pri->targetIndex = mTargetChainIdx;
  179. chainIndex = mTargetChainIdx;
  180. mTargetChainIdx++;
  181. // TODO: Rewrite this...
  182. mElementList.increment();
  183. }
  184. // Set up system entry
  185. OffscreenSystemEntry &systemEntry = mOffscreenSystems[pri->targetIndex];
  186. systemEntry.screenRect = screenRect;
  187. systemEntry.targetChainIdx = chainIndex;
  188. systemEntry.pInstances.push_back(pri);
  189. // TODO: Rewrite this block
  190. // Assign proper values to sort element
  191. MainSortElem& elem = mElementList.last();
  192. elem.inst = reinterpret_cast<RenderInst *>(&systemEntry);
  193. elem.key = *((U32*)&inst->sortDistSq);
  194. elem.key2 = inst->defaultKey;
  195. // TODO: [re]move this block
  196. systemEntry.clipMatrix.identity();
  197. if(!RenderToSingleTarget)
  198. {
  199. // Construct crop matrix
  200. Point3F scale( getMax(2.0f / systemEntry.screenRect.extent.x, 1.0f),
  201. getMax(2.0f / systemEntry.screenRect.extent.y, 1.0f),
  202. 1.0f);
  203. Point3F offset((systemEntry.screenRect.point.x + systemEntry.screenRect.extent.x * 0.5f) * scale.x,
  204. (systemEntry.screenRect.point.y + systemEntry.screenRect.extent.y * 0.5f) * scale.y,
  205. 0.0f);
  206. //systemEntry.clipMatrix.scale(scale);
  207. //systemEntry.clipMatrix.setPosition(-offset);
  208. }
  209. // The translucent mgr will also pick up particles, and will call this class
  210. // to composiste the particle systems back into the main scene
  211. }
  212. void RenderParticleMgr::sort()
  213. {
  214. Parent::sort();
  215. }
  216. void RenderParticleMgr::clear()
  217. {
  218. Parent::clear();
  219. // Reset pool index
  220. if(!RenderToSingleTarget)
  221. mTargetChainIdx = 0;
  222. for(Vector<OffscreenSystemEntry>::iterator itr = mOffscreenSystems.begin();
  223. itr != mOffscreenSystems.end(); itr++)
  224. {
  225. (*itr).drawnThisFrame = false;
  226. (*itr).pInstances.clear();
  227. }
  228. }
  229. void RenderParticleMgr::render( SceneRenderState *state )
  230. {
  231. PROFILE_SCOPE(RenderParticleMgr_render);
  232. // Early out if nothing to draw
  233. if( !mElementList.size() ||
  234. (!mParticleShader && !_initShader()) )
  235. return;
  236. GFXDEBUGEVENT_SCOPE(RenderParticleMgr_Render, ColorI::RED);
  237. GFXTransformSaver saver;
  238. // Iterate render instances
  239. for( Vector<MainSortElem>::const_iterator itr = mElementList.begin();
  240. itr != mElementList.end(); itr++ )
  241. {
  242. OffscreenSystemEntry &systemEntry = *reinterpret_cast<OffscreenSystemEntry *>(itr->inst);
  243. // Setup target
  244. // NOTE: If you are using this on the Xbox360 with Basic Lighting,
  245. // you are going to have to mess with either the render order, or
  246. // you are going to have to make this a 'preserve' draw
  247. if(!RenderToSingleTarget)
  248. mTargetChainIdx = systemEntry.targetChainIdx;
  249. _onPreRender(state);
  250. // Clear offscreen target
  251. GFX->clear(GFXClearTarget, ColorI::ZERO, 1.0f, 0);
  252. // Draw offscreen systems
  253. for( Vector<ParticleRenderInst *>::const_iterator itr2 = systemEntry.pInstances.begin();
  254. itr2 != systemEntry.pInstances.end(); itr2++ )
  255. {
  256. ParticleRenderInst *ri = *itr2;
  257. // Sanity check
  258. if(ri->systemState == PSS_AwaitingOffscreenDraw)
  259. {
  260. // If this is not a diffuse path, flag the system appropriately, and skip
  261. // the offscreen processing.
  262. if( !state->isDiffusePass() )
  263. {
  264. if(state->isReflectPass())
  265. ri->systemState = PSS_AwaitingHighResDraw;
  266. else
  267. ri->systemState = PSS_DrawComplete;
  268. continue;
  269. }
  270. // Draw system offscreen
  271. renderInstance(ri, state);
  272. }
  273. }
  274. // Cleanup
  275. _onPostRender();
  276. }
  277. }
  278. void RenderParticleMgr::_initGFXResources()
  279. {
  280. // Screen quad
  281. U16 *prims = NULL;
  282. mScreenQuadPrimBuff.set(GFX, 4, 2, GFXBufferTypeStatic);
  283. mScreenQuadPrimBuff.lock(&prims);
  284. (*prims++) = 0;
  285. (*prims++) = 1;
  286. (*prims++) = 2;
  287. (*prims++) = 3;
  288. mScreenQuadPrimBuff.unlock();
  289. mScreenQuadVertBuff.set(GFX, 4, GFXBufferTypeStatic);
  290. CompositeQuadVert *verts = mScreenQuadVertBuff.lock();
  291. (*verts++).uvCoord.set(0, 0, 0, 0);
  292. (*verts++).uvCoord.set(0, 255, 0, 0);
  293. (*verts++).uvCoord.set(255, 0, 0, 0);
  294. (*verts++).uvCoord.set(255, 255, 0, 0);
  295. mScreenQuadVertBuff.unlock();
  296. // Stencil setup state block
  297. GFXStateBlockDesc d;
  298. d.setCullMode(GFXCullNone);
  299. d.setColorWrites(false, false, false, false);
  300. d.setBlend(false);
  301. d.setZReadWrite(false, false);
  302. d.stencilDefined = true;
  303. d.stencilEnable = true;
  304. d.stencilMask = RenderParticleMgr::ParticleSystemStencilMask;
  305. d.stencilWriteMask = RenderParticleMgr::ParticleSystemStencilMask;
  306. d.stencilFunc = GFXCmpAlways;
  307. d.stencilPassOp = GFXStencilOpZero;
  308. mStencilClearSB = GFX->createStateBlock(d);
  309. }
  310. void RenderParticleMgr::renderInstance(ParticleRenderInst *ri, SceneRenderState *state)
  311. {
  312. // Draw system path, or draw composite path
  313. if(ri->systemState == PSS_DrawComplete)
  314. return;
  315. if(ri->systemState != PSS_AwaitingCompositeDraw)
  316. {
  317. // Set proper stateblock, and update state
  318. if(ri->systemState == PSS_AwaitingOffscreenDraw)
  319. {
  320. GFX->setStateBlock( _getOffscreenStateBlock(ri) );
  321. ri->systemState = PSS_AwaitingCompositeDraw;
  322. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mModelViewProjSC,
  323. *ri->modelViewProj * mOffscreenSystems[ri->targetIndex].clipMatrix );
  324. }
  325. else
  326. {
  327. if(ri->systemState == PSS_AwaitingMixedResDraw)
  328. GFX->setStateBlock( _getMixedResStateBlock( ri ) );
  329. else
  330. GFX->setStateBlock( _getHighResStateBlock( ri ) );
  331. ri->systemState = PSS_DrawComplete;
  332. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mModelViewProjSC, *ri->modelViewProj );
  333. }
  334. renderParticle(ri, state);
  335. }
  336. else if(ri->systemState == PSS_AwaitingCompositeDraw)
  337. {
  338. OffscreenSystemEntry &systemEntry = mOffscreenSystems[ri->targetIndex];
  339. // If this system has already been composited this frame, skip it
  340. if(systemEntry.drawnThisFrame)
  341. return;
  342. // Non-target render, composite the particle system back into the scene
  343. GFX->setVertexBuffer(mScreenQuadVertBuff);
  344. GFX->setPrimitiveBuffer(mScreenQuadPrimBuff);
  345. // Set up shader constants
  346. mParticleCompositeShaderConsts.mShaderConsts->setSafe( mParticleCompositeShaderConsts.mScreenRect, *((Point4F *)&systemEntry.screenRect) );
  347. // Set offscreen texture
  348. Point4F rtParams;
  349. GFXTextureObject *particleSource = mNamedTarget.getTexture();
  350. GFX->setTexture( 0, particleSource );
  351. if(particleSource)
  352. {
  353. ScreenSpace::RenderTargetParameters(particleSource->getSize(), mNamedTarget.getViewport(), rtParams);
  354. mParticleCompositeShaderConsts.mShaderConsts->setSafe( mParticleCompositeShaderConsts.mOffscreenTargetParamsSC, rtParams );
  355. }
  356. // And edges
  357. GFXTextureObject *texObject = mEdgeTarget ? mEdgeTarget->getTexture() : NULL;
  358. GFX->setTexture( 1, texObject );
  359. if(texObject)
  360. {
  361. ScreenSpace::RenderTargetParameters(texObject->getSize(), mEdgeTarget->getViewport(), rtParams);
  362. mParticleCompositeShaderConsts.mShaderConsts->setSafe( mParticleCompositeShaderConsts.mEdgeTargetParamsSC, rtParams );
  363. }
  364. else
  365. {
  366. AssertWarn(false, "No edge texture target defined, if you want to use mixed particle"
  367. "rendering, then make sure that the EdgeDetectPostEffect is enabled.");
  368. ri->systemState == PSS_AwaitingHighResDraw;
  369. return;
  370. }
  371. // Set shader and constant buffer
  372. GFX->setShader( mParticleCompositeShader );
  373. GFX->setShaderConstBuffer( mParticleCompositeShaderConsts.mShaderConsts );
  374. // Draw to stencil buffer only to clear the stencil values
  375. GFX->setStateBlock( mStencilClearSB );
  376. GFX->drawIndexedPrimitive( GFXTriangleStrip, 0, 0, 4, 0, 2 );
  377. // composite particle system back into the scene
  378. GFX->setStateBlock( _getCompositeStateBlock(ri) );
  379. GFX->drawIndexedPrimitive( GFXTriangleStrip, 0, 0, 4, 0, 2 );
  380. // Re-draw the particle systems in high-res, but only to the stenciled
  381. // areas which were enabled via the edge buffer
  382. for( Vector<ParticleRenderInst *>::const_iterator itr = systemEntry.pInstances.begin();
  383. itr != systemEntry.pInstances.end(); itr++ )
  384. {
  385. ParticleRenderInst *pri = *itr;
  386. if(pri->systemState == PSS_AwaitingCompositeDraw)
  387. {
  388. pri->systemState = PSS_AwaitingMixedResDraw;
  389. renderInstance(pri, state);
  390. }
  391. }
  392. // Mark this system as having been composited this frame
  393. systemEntry.drawnThisFrame = true;
  394. }
  395. }
  396. void RenderParticleMgr::renderParticle(ParticleRenderInst* ri, SceneRenderState* state)
  397. {
  398. // We want to turn everything into variation on a pre-multiplied alpha blend
  399. F32 alphaFactor = 0.0f, alphaScale = 1.0f;
  400. switch(ri->blendStyle)
  401. {
  402. // SrcAlpha, InvSrcAlpha
  403. case ParticleRenderInst::BlendNormal:
  404. alphaFactor = 1.0f;
  405. break;
  406. // SrcAlpha, One
  407. case ParticleRenderInst::BlendAdditive:
  408. alphaFactor = 1.0f;
  409. alphaScale = 0.0f;
  410. break;
  411. // SrcColor, One
  412. case ParticleRenderInst::BlendGreyscale:
  413. alphaFactor = -1.0f;
  414. alphaScale = 0.0f;
  415. break;
  416. }
  417. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mAlphaFactorSC, alphaFactor );
  418. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mAlphaScaleSC, alphaScale );
  419. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mFSModelViewProjSC, *ri->modelViewProj );
  420. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mOneOverFarSC, 1.0f / state->getFarPlane() );
  421. if ( mParticleShaderConsts.mOneOverSoftnessSC->isValid() )
  422. {
  423. F32 oneOverSoftness = 1.0f;
  424. if ( ri->softnessDistance > 0.0f )
  425. oneOverSoftness = 1.0f / ( ri->softnessDistance / state->getFarPlane() );
  426. mParticleShaderConsts.mShaderConsts->set( mParticleShaderConsts.mOneOverSoftnessSC, oneOverSoftness );
  427. }
  428. GFX->setShader( mParticleShader );
  429. GFX->setShaderConstBuffer( mParticleShaderConsts.mShaderConsts );
  430. GFX->setTexture( 0, ri->diffuseTex );
  431. // Set up the prepass texture.
  432. if ( mParticleShaderConsts.mPrePassTargetParamsSC->isValid() )
  433. {
  434. GFXTextureObject *texObject = mPrepassTarget ? mPrepassTarget->getTexture(0) : NULL;
  435. GFX->setTexture( 1, texObject );
  436. Point4F rtParams( 0.0f, 0.0f, 1.0f, 1.0f );
  437. if ( texObject )
  438. ScreenSpace::RenderTargetParameters(texObject->getSize(), mPrepassTarget->getViewport(), rtParams);
  439. mParticleShaderConsts.mShaderConsts->set( mParticleShaderConsts.mPrePassTargetParamsSC, rtParams );
  440. }
  441. GFX->setPrimitiveBuffer( *ri->primBuff );
  442. GFX->setVertexBuffer( *ri->vertBuff );
  443. GFX->drawIndexedPrimitive( GFXTriangleList, 0, 0, ri->count * 4, 0, ri->count * 2 );
  444. }
  445. bool RenderParticleMgr::_initShader()
  446. {
  447. ShaderData *shaderData = NULL;
  448. bool ret = true;
  449. // Need depth from pre-pass, so get the macros
  450. Vector<GFXShaderMacro> macros;
  451. if ( mPrepassTarget )
  452. mPrepassTarget->getShaderMacros( &macros );
  453. // Create particle shader
  454. if ( !Sim::findObject( "ParticlesShaderData", shaderData ) || !shaderData )
  455. Con::warnf( "RenderParticleMgr::_initShader - failed to locate shader ParticlesShaderData!" );
  456. if( shaderData )
  457. mParticleShader = shaderData->getShader( macros );
  458. ret &= (mParticleShader != NULL);
  459. if ( mParticleShader )
  460. {
  461. mParticleShaderConsts.mShaderConsts = mParticleShader->allocConstBuffer();
  462. mParticleShaderConsts.mModelViewProjSC = mParticleShader->getShaderConstHandle( "$modelViewProj" );
  463. mParticleShaderConsts.mOneOverFarSC = mParticleShader->getShaderConstHandle( "$oneOverFar" );
  464. mParticleShaderConsts.mOneOverSoftnessSC = mParticleShader->getShaderConstHandle( "$oneOverSoftness" );
  465. mParticleShaderConsts.mAlphaFactorSC = mParticleShader->getShaderConstHandle( "$alphaFactor" );
  466. mParticleShaderConsts.mAlphaScaleSC = mParticleShader->getShaderConstHandle( "$alphaScale" );
  467. mParticleShaderConsts.mFSModelViewProjSC = mParticleShader->getShaderConstHandle( "$fsModelViewProj" );
  468. mParticleShaderConsts.mPrePassTargetParamsSC = mParticleShader->getShaderConstHandle( "$prePassTargetParams" );
  469. }
  470. shaderData = NULL;
  471. // Create off screen particle composite shader
  472. if ( !Sim::findObject( "OffscreenParticleCompositeShaderData", shaderData ) || !shaderData )
  473. Con::warnf( "RenderParticleMgr::_initShader - failed to locate shader OffscreenParticleCompositeShaderData!" );
  474. if( shaderData )
  475. mParticleCompositeShader = shaderData->getShader( macros );
  476. ret &= (mParticleCompositeShader != NULL);
  477. if ( mParticleCompositeShader )
  478. {
  479. mParticleCompositeShaderConsts.mShaderConsts = mParticleCompositeShader->allocConstBuffer();
  480. mParticleCompositeShaderConsts.mScreenRect = mParticleCompositeShader->getShaderConstHandle( "$screenRect" );
  481. mParticleCompositeShaderConsts.mEdgeTargetParamsSC = mParticleCompositeShader->getShaderConstHandle( "$edgeTargetParams" );
  482. mParticleCompositeShaderConsts.mOffscreenTargetParamsSC = mParticleCompositeShader->getShaderConstHandle( "$offscreenTargetParams" );
  483. }
  484. return ret;
  485. }
  486. void RenderParticleMgr::_onLMActivate( const char*, bool activate )
  487. {
  488. RenderPassManager *rpm = getRenderPass();
  489. if ( !rpm )
  490. return;
  491. // Hunt for the pre-pass manager/target
  492. RenderPrePassMgr *prePassBin = NULL;
  493. for( U32 i = 0; i < rpm->getManagerCount(); i++ )
  494. {
  495. RenderBinManager *bin = rpm->getManager(i);
  496. if( bin->getRenderInstType() == RenderPrePassMgr::RIT_PrePass )
  497. {
  498. prePassBin = (RenderPrePassMgr*)bin;
  499. break;
  500. }
  501. }
  502. // If we found the prepass bin, set this bin to render very shortly afterwards
  503. // and re-add this render-manager. If there is no pre-pass bin, or it doesn't
  504. // have a depth-texture, we can't render offscreen.
  505. mOffscreenRenderEnabled = prePassBin && (prePassBin->getTargetChainLength() > 0);
  506. if(mOffscreenRenderEnabled)
  507. {
  508. rpm->removeManager(this);
  509. setRenderOrder( prePassBin->getRenderOrder() + 0.011f );
  510. rpm->addManager(this);
  511. }
  512. // Find the targets we use
  513. mPrepassTarget = NamedTexTarget::find( "prepass" );
  514. mEdgeTarget = NamedTexTarget::find( "edge" );
  515. // Setup the shader
  516. if ( activate )
  517. _initShader();
  518. if ( mScreenQuadVertBuff.isNull() )
  519. _initGFXResources();
  520. }
  521. GFXStateBlockRef RenderParticleMgr::_getOffscreenStateBlock(ParticleRenderInst *ri)
  522. {
  523. const U8 blendStyle = ri->blendStyle;
  524. if ( mOffscreenBlocks[blendStyle].isValid() )
  525. return mOffscreenBlocks[blendStyle];
  526. GFXStateBlockDesc d;
  527. d.setCullMode(GFXCullNone);
  528. d.setZReadWrite(false, false); // No zreads or writes, all z-testing is done in the pixel shader
  529. // Draw everything either subtractive, or using a variation on premultiplied
  530. // alpha
  531. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  532. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  533. else
  534. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  535. // Offscreen target, we need to add alpha.
  536. d.separateAlphaBlendDefined = true;
  537. d.separateAlphaBlendEnable = true;
  538. d.separateAlphaBlendSrc = GFXBlendOne;
  539. d.separateAlphaBlendDest = GFXBlendInvSrcAlpha;
  540. d.samplersDefined = true;
  541. // Diffuse texture sampler
  542. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  543. d.samplers[0].alphaOp = GFXTOPModulate;
  544. d.samplers[0].alphaArg1 = GFXTATexture;
  545. d.samplers[0].alphaArg2 = GFXTADiffuse;
  546. // Prepass sampler
  547. d.samplers[1] = GFXSamplerStateDesc::getClampPoint();
  548. mOffscreenBlocks[blendStyle] = GFX->createStateBlock(d);
  549. return mOffscreenBlocks[blendStyle];
  550. }
  551. GFXStateBlockRef RenderParticleMgr::_getHighResStateBlock(ParticleRenderInst *ri)
  552. {
  553. const U8 blendStyle = ri->blendStyle;
  554. if ( mHighResBlocks[blendStyle].isValid() )
  555. return mHighResBlocks[blendStyle];
  556. GFXStateBlockDesc d;
  557. d.setZReadWrite(true, false);
  558. d.setCullMode(GFXCullNone);
  559. // Draw everything either subtractive, or using a variation on premultiplied
  560. // alpha
  561. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  562. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  563. else
  564. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  565. d.samplersDefined = true;
  566. // Diffuse texture sampler
  567. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  568. d.samplers[0].alphaOp = GFXTOPModulate;
  569. d.samplers[0].alphaArg1 = GFXTATexture;
  570. d.samplers[0].alphaArg2 = GFXTADiffuse;
  571. // Prepass sampler
  572. d.samplers[1] = GFXSamplerStateDesc::getClampPoint();
  573. mHighResBlocks[blendStyle] = GFX->createStateBlock(d);
  574. return mHighResBlocks[blendStyle];
  575. }
  576. GFXStateBlockRef RenderParticleMgr::_getMixedResStateBlock(ParticleRenderInst *ri)
  577. {
  578. const U8 blendStyle = ri->blendStyle;
  579. if ( mMixedResBlocks[blendStyle].isValid() )
  580. return mMixedResBlocks[blendStyle];
  581. GFXStateBlockDesc d;
  582. d.setZReadWrite(true, false);
  583. d.setCullMode(GFXCullNone);
  584. /*
  585. // Old blend styles...
  586. switch (blendStyle)
  587. {
  588. case ParticleRenderInst::BlendNormal:
  589. d.blendSrc = GFXBlendSrcAlpha;
  590. d.blendDest = GFXBlendInvSrcAlpha;
  591. break;
  592. case ParticleRenderInst::BlendSubtractive:
  593. d.blendSrc = GFXBlendZero;
  594. d.blendDest = GFXBlendInvSrcColor;
  595. break;
  596. case ParticleRenderInst::BlendPremultAlpha:
  597. d.blendSrc = GFXBlendOne;
  598. d.blendDest = GFXBlendInvSrcAlpha;
  599. break;
  600. // Default to additive blend mode
  601. case ParticleRenderInst::BlendAdditive:
  602. case ParticleRenderInst::BlendUndefined:
  603. default:
  604. d.blendSrc = GFXBlendSrcAlpha;
  605. d.blendDest = GFXBlendOne;
  606. break;
  607. }
  608. */
  609. // Draw everything either subtractive, or using a variation on premultiplied
  610. // alpha
  611. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  612. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  613. else
  614. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  615. // Draw to anything but the stencil ref value (the edges)
  616. d.stencilDefined = true;
  617. d.stencilEnable = true;
  618. d.stencilRef = RenderParticleMgr::HighResStencilRef;
  619. d.stencilMask = RenderParticleMgr::ParticleSystemStencilMask;
  620. d.stencilPassOp = GFXStencilOpKeep;
  621. d.stencilFailOp = GFXStencilOpKeep;
  622. d.stencilZFailOp = GFXStencilOpKeep;
  623. d.stencilFunc = GFXCmpNotEqual;
  624. d.samplersDefined = true;
  625. // Diffuse texture sampler
  626. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  627. d.samplers[0].alphaOp = GFXTOPModulate;
  628. d.samplers[0].alphaArg1 = GFXTATexture;
  629. d.samplers[0].alphaArg2 = GFXTADiffuse;
  630. // Prepass sampler
  631. d.samplers[1] = GFXSamplerStateDesc::getClampPoint();
  632. mMixedResBlocks[blendStyle] = GFX->createStateBlock(d);
  633. return mMixedResBlocks[blendStyle];
  634. }
  635. GFXStateBlockRef RenderParticleMgr::_getCompositeStateBlock(ParticleRenderInst *ri)
  636. {
  637. const U8 blendStyle = ri->blendStyle;
  638. if ( mBackbufferBlocks[blendStyle].isValid() )
  639. return mBackbufferBlocks[blendStyle];
  640. GFXStateBlockDesc d;
  641. // This is a billboard
  642. d.setCullMode(GFXCullNone);
  643. d.setZReadWrite(false, false);
  644. // When we re-composite the particles, it is always either a pre-mult alpha
  645. // blend, or a subtractive blend!
  646. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  647. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  648. else
  649. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  650. // All areas which are not along the edges of geometry where the particle system
  651. // is being drawn get assigned a stencil ref value as the system is composited
  652. // back into the scene. The high-res stateblock uses this value as a mask, and
  653. // draws only in areas which are NOT this ref value. This causes high resolution
  654. // draws to ONLY the edge areas.
  655. d.stencilDefined = true;
  656. d.stencilEnable = true;
  657. d.stencilRef = RenderParticleMgr::HighResStencilRef;
  658. d.stencilWriteMask = RenderParticleMgr::ParticleSystemStencilMask;
  659. d.stencilMask = RenderParticleMgr::ParticleSystemStencilMask;
  660. d.stencilPassOp = GFXStencilOpReplace;
  661. d.stencilFunc = GFXCmpGreater;
  662. // Diffuse texture sampler and
  663. d.samplersDefined = true;
  664. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  665. d.samplers[1] = GFXSamplerStateDesc::getClampLinear();
  666. mBackbufferBlocks[blendStyle] = GFX->createStateBlock(d);
  667. return mBackbufferBlocks[blendStyle];
  668. }
  669. bool RenderParticleMgr::_handleGFXEvent( GFXDevice::GFXDeviceEventType event )
  670. {
  671. if(RenderToSingleTarget)
  672. return Parent::_handleGFXEvent( event );
  673. // Do nothing. This render manager uses its target chain as a pool of targets.
  674. return true;
  675. }