renderParticleMgr.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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/renderDeferredMgr.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 [] = {
  282. 0, 1, 2, 3,
  283. };
  284. mScreenQuadPrimBuff.immutable(GFX, 4, 2, prims);
  285. mScreenQuadVertBuff.set(GFX, 4, GFXBufferTypeStatic);
  286. CompositeQuadVert *verts = mScreenQuadVertBuff.lock();
  287. (*verts++).uvCoord.set(0, 0, 0, 0);
  288. (*verts++).uvCoord.set(0, 255, 0, 0);
  289. (*verts++).uvCoord.set(255, 0, 0, 0);
  290. (*verts++).uvCoord.set(255, 255, 0, 0);
  291. mScreenQuadVertBuff.unlock();
  292. // Stencil setup state block
  293. GFXStateBlockDesc d;
  294. d.setCullMode(GFXCullNone);
  295. d.setColorWrites(false, false, false, false);
  296. d.setBlend(false);
  297. d.setZReadWrite(false, false);
  298. d.stencilDefined = true;
  299. d.stencilEnable = true;
  300. d.stencilMask = RenderParticleMgr::ParticleSystemStencilMask;
  301. d.stencilWriteMask = RenderParticleMgr::ParticleSystemStencilMask;
  302. d.stencilFunc = GFXCmpAlways;
  303. d.stencilPassOp = GFXStencilOpZero;
  304. mStencilClearSB = GFX->createStateBlock(d);
  305. }
  306. void RenderParticleMgr::renderInstance(ParticleRenderInst *ri, SceneRenderState *state)
  307. {
  308. // Draw system path, or draw composite path
  309. if(ri->systemState == PSS_DrawComplete)
  310. return;
  311. if(ri->systemState != PSS_AwaitingCompositeDraw)
  312. {
  313. // Set proper stateblock, and update state
  314. if(ri->systemState == PSS_AwaitingOffscreenDraw)
  315. {
  316. GFX->setStateBlock( _getOffscreenStateBlock(ri) );
  317. ri->systemState = PSS_AwaitingCompositeDraw;
  318. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mModelViewProjSC,
  319. *ri->modelViewProj * mOffscreenSystems[ri->targetIndex].clipMatrix );
  320. }
  321. else
  322. {
  323. if(ri->systemState == PSS_AwaitingMixedResDraw)
  324. GFX->setStateBlock( _getMixedResStateBlock( ri ) );
  325. else
  326. GFX->setStateBlock( _getHighResStateBlock( ri ) );
  327. ri->systemState = PSS_DrawComplete;
  328. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mModelViewProjSC, *ri->modelViewProj );
  329. }
  330. renderParticle(ri, state);
  331. }
  332. else if(ri->systemState == PSS_AwaitingCompositeDraw)
  333. {
  334. OffscreenSystemEntry &systemEntry = mOffscreenSystems[ri->targetIndex];
  335. // If this system has already been composited this frame, skip it
  336. if(systemEntry.drawnThisFrame)
  337. return;
  338. // Non-target render, composite the particle system back into the scene
  339. GFX->setVertexBuffer(mScreenQuadVertBuff);
  340. GFX->setPrimitiveBuffer(mScreenQuadPrimBuff);
  341. // Set up shader constants
  342. mParticleCompositeShaderConsts.mShaderConsts->setSafe( mParticleCompositeShaderConsts.mScreenRect, *((Point4F *)&systemEntry.screenRect) );
  343. // Set offscreen texture
  344. Point4F rtParams;
  345. GFXTextureObject *particleSource = mNamedTarget.getTexture();
  346. GFX->setTexture( mParticleCompositeShaderConsts.mSamplerColorSource->getSamplerRegister(), particleSource );
  347. if(particleSource)
  348. {
  349. ScreenSpace::RenderTargetParameters(particleSource->getSize(), mNamedTarget.getViewport(), rtParams);
  350. mParticleCompositeShaderConsts.mShaderConsts->setSafe( mParticleCompositeShaderConsts.mOffscreenTargetParamsSC, rtParams );
  351. }
  352. // And edges
  353. GFXTextureObject *texObject = mEdgeTarget ? mEdgeTarget->getTexture() : NULL;
  354. GFX->setTexture( mParticleCompositeShaderConsts.mSamplerEdgeSource->getSamplerRegister(), texObject );
  355. if(texObject)
  356. {
  357. ScreenSpace::RenderTargetParameters(texObject->getSize(), mEdgeTarget->getViewport(), rtParams);
  358. mParticleCompositeShaderConsts.mShaderConsts->setSafe( mParticleCompositeShaderConsts.mEdgeTargetParamsSC, rtParams );
  359. }
  360. else
  361. {
  362. AssertFatal(false, "No edge texture target defined, if you want to use mixed particle"
  363. "rendering, then make sure that the EdgeDetectPostEffect is enabled.");
  364. ri->systemState = PSS_AwaitingHighResDraw;
  365. return;
  366. }
  367. // Set shader and constant buffer
  368. GFX->setShader( mParticleCompositeShader );
  369. GFX->setShaderConstBuffer( mParticleCompositeShaderConsts.mShaderConsts );
  370. // Draw to stencil buffer only to clear the stencil values
  371. GFX->setStateBlock( mStencilClearSB );
  372. GFX->drawIndexedPrimitive( GFXTriangleStrip, 0, 0, 4, 0, 2 );
  373. // composite particle system back into the scene
  374. GFX->setStateBlock( _getCompositeStateBlock(ri) );
  375. GFX->drawIndexedPrimitive( GFXTriangleStrip, 0, 0, 4, 0, 2 );
  376. // Re-draw the particle systems in high-res, but only to the stenciled
  377. // areas which were enabled via the edge buffer
  378. for( Vector<ParticleRenderInst *>::const_iterator itr = systemEntry.pInstances.begin();
  379. itr != systemEntry.pInstances.end(); itr++ )
  380. {
  381. ParticleRenderInst *pri = *itr;
  382. if(pri->systemState == PSS_AwaitingCompositeDraw)
  383. {
  384. pri->systemState = PSS_AwaitingMixedResDraw;
  385. renderInstance(pri, state);
  386. }
  387. }
  388. // Mark this system as having been composited this frame
  389. systemEntry.drawnThisFrame = true;
  390. }
  391. }
  392. void RenderParticleMgr::renderParticle(ParticleRenderInst* ri, SceneRenderState* state)
  393. {
  394. // We want to turn everything into variation on a pre-multiplied alpha blend
  395. F32 alphaFactor = 0.0f, alphaScale = 1.0f;
  396. switch(ri->blendStyle)
  397. {
  398. // SrcAlpha, InvSrcAlpha
  399. case ParticleRenderInst::BlendNormal:
  400. alphaFactor = 1.0f;
  401. break;
  402. // SrcAlpha, One
  403. case ParticleRenderInst::BlendAdditive:
  404. alphaFactor = 1.0f;
  405. alphaScale = 0.0f;
  406. break;
  407. // SrcColor, One
  408. case ParticleRenderInst::BlendGreyscale:
  409. alphaFactor = -1.0f;
  410. alphaScale = 0.0f;
  411. break;
  412. }
  413. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mAlphaFactorSC, alphaFactor );
  414. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mAlphaScaleSC, alphaScale );
  415. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mFSModelViewProjSC, *ri->modelViewProj );
  416. mParticleShaderConsts.mShaderConsts->setSafe( mParticleShaderConsts.mOneOverFarSC, 1.0f / state->getFarPlane() );
  417. if ( mParticleShaderConsts.mOneOverSoftnessSC->isValid() )
  418. {
  419. F32 oneOverSoftness = 1.0f;
  420. if ( ri->softnessDistance > 0.0f )
  421. oneOverSoftness = 1.0f / ( ri->softnessDistance / state->getFarPlane() );
  422. mParticleShaderConsts.mShaderConsts->set( mParticleShaderConsts.mOneOverSoftnessSC, oneOverSoftness );
  423. }
  424. GFX->setShader( mParticleShader );
  425. GFX->setShaderConstBuffer( mParticleShaderConsts.mShaderConsts );
  426. GFX->setTexture( mParticleShaderConsts.mSamplerDiffuse->getSamplerRegister(), ri->diffuseTex );
  427. // Set up the deferred texture.
  428. if ( mParticleShaderConsts.mDeferredTargetParamsSC->isValid() )
  429. {
  430. GFXTextureObject *texObject = mDeferredTarget ? mDeferredTarget->getTexture(0) : NULL;
  431. GFX->setTexture( mParticleShaderConsts.mSamplerDeferredTex->getSamplerRegister(), texObject );
  432. Point4F rtParams( 0.0f, 0.0f, 1.0f, 1.0f );
  433. if ( texObject )
  434. ScreenSpace::RenderTargetParameters(texObject->getSize(), mDeferredTarget->getViewport(), rtParams);
  435. mParticleShaderConsts.mShaderConsts->set( mParticleShaderConsts.mDeferredTargetParamsSC, rtParams );
  436. }
  437. GFX->setPrimitiveBuffer( *ri->primBuff );
  438. GFX->setVertexBuffer( *ri->vertBuff );
  439. GFX->drawIndexedPrimitive( GFXTriangleList, 0, 0, ri->count * 4, 0, ri->count * 2 );
  440. }
  441. bool RenderParticleMgr::_initShader()
  442. {
  443. ShaderData *shaderData = NULL;
  444. bool ret = true;
  445. // Need depth from pre-pass, so get the macros
  446. Vector<GFXShaderMacro> macros;
  447. if ( mDeferredTarget )
  448. mDeferredTarget->getShaderMacros( &macros );
  449. // Create particle shader
  450. if ( !Sim::findObject( "ParticlesShaderData", shaderData ) || !shaderData )
  451. Con::warnf( "RenderParticleMgr::_initShader - failed to locate shader ParticlesShaderData!" );
  452. if( shaderData )
  453. mParticleShader = shaderData->getShader( macros );
  454. ret &= (mParticleShader != NULL);
  455. if ( mParticleShader )
  456. {
  457. mParticleShaderConsts.mShaderConsts = mParticleShader->allocConstBuffer();
  458. mParticleShaderConsts.mModelViewProjSC = mParticleShader->getShaderConstHandle( "$modelViewProj" );
  459. mParticleShaderConsts.mOneOverFarSC = mParticleShader->getShaderConstHandle( "$oneOverFar" );
  460. mParticleShaderConsts.mOneOverSoftnessSC = mParticleShader->getShaderConstHandle( "$oneOverSoftness" );
  461. mParticleShaderConsts.mAlphaFactorSC = mParticleShader->getShaderConstHandle( "$alphaFactor" );
  462. mParticleShaderConsts.mAlphaScaleSC = mParticleShader->getShaderConstHandle( "$alphaScale" );
  463. mParticleShaderConsts.mFSModelViewProjSC = mParticleShader->getShaderConstHandle( "$fsModelViewProj" );
  464. mParticleShaderConsts.mDeferredTargetParamsSC = mParticleShader->getShaderConstHandle( "$deferredTargetParams" );
  465. //samplers
  466. mParticleShaderConsts.mSamplerDiffuse = mParticleShader->getShaderConstHandle("$diffuseMap");
  467. mParticleShaderConsts.mSamplerDeferredTex = mParticleShader->getShaderConstHandle("$deferredTex");
  468. mParticleShaderConsts.mSamplerParaboloidLightMap = mParticleShader->getShaderConstHandle("$paraboloidLightMap");
  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.mSamplerColorSource = mParticleCompositeShader->getShaderConstHandle( "$colorSource" );
  482. mParticleCompositeShaderConsts.mSamplerEdgeSource = mParticleCompositeShader->getShaderConstHandle( "$edgeSource" );
  483. mParticleCompositeShaderConsts.mEdgeTargetParamsSC = mParticleCompositeShader->getShaderConstHandle( "$edgeTargetParams" );
  484. mParticleCompositeShaderConsts.mOffscreenTargetParamsSC = mParticleCompositeShader->getShaderConstHandle( "$offscreenTargetParams" );
  485. }
  486. return ret;
  487. }
  488. void RenderParticleMgr::_onLMActivate( const char*, bool activate )
  489. {
  490. if ( activate )
  491. {
  492. RenderPassManager *rpm = getRenderPass();
  493. if ( !rpm )
  494. return;
  495. // Hunt for the pre-pass manager/target
  496. RenderDeferredMgr *deferredBin = NULL;
  497. for( U32 i = 0; i < rpm->getManagerCount(); i++ )
  498. {
  499. RenderBinManager *bin = rpm->getManager(i);
  500. if( bin->getRenderInstType() == RenderDeferredMgr::RIT_Deferred )
  501. {
  502. deferredBin = (RenderDeferredMgr*)bin;
  503. break;
  504. }
  505. }
  506. // If we found the deferred bin, set this bin to render very shortly afterwards
  507. // and re-add this render-manager. If there is no pre-pass bin, or it doesn't
  508. // have a depth-texture, we can't render offscreen.
  509. mOffscreenRenderEnabled = deferredBin && (deferredBin->getTargetChainLength() > 0);
  510. if(mOffscreenRenderEnabled)
  511. {
  512. rpm->removeManager(this);
  513. setRenderOrder( deferredBin->getRenderOrder() + 0.011f );
  514. rpm->addManager(this);
  515. }
  516. // Find the targets we use
  517. mDeferredTarget = NamedTexTarget::find( "deferred" );
  518. mEdgeTarget = NamedTexTarget::find( "edge" );
  519. // Setup the shader
  520. _initShader();
  521. if ( mScreenQuadVertBuff.isNull() )
  522. _initGFXResources();
  523. }
  524. else
  525. {
  526. mStencilClearSB = NULL;
  527. mScreenQuadPrimBuff = NULL;
  528. mScreenQuadVertBuff = NULL;
  529. }
  530. }
  531. GFXStateBlockRef RenderParticleMgr::_getOffscreenStateBlock(ParticleRenderInst *ri)
  532. {
  533. const U8 blendStyle = ri->blendStyle;
  534. if ( mOffscreenBlocks[blendStyle].isValid() )
  535. return mOffscreenBlocks[blendStyle];
  536. GFXStateBlockDesc d;
  537. d.setCullMode(GFXCullNone);
  538. d.setZReadWrite(false, false); // No zreads or writes, all z-testing is done in the pixel shader
  539. // Draw everything either subtractive, or using a variation on premultiplied
  540. // alpha
  541. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  542. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  543. else
  544. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  545. // Offscreen target, we need to add alpha.
  546. d.separateAlphaBlendDefined = true;
  547. d.separateAlphaBlendEnable = true;
  548. d.separateAlphaBlendSrc = GFXBlendOne;
  549. d.separateAlphaBlendDest = GFXBlendInvSrcAlpha;
  550. d.samplersDefined = true;
  551. // Diffuse texture sampler
  552. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  553. // Deferred sampler
  554. d.samplers[1] = GFXSamplerStateDesc::getClampPoint();
  555. mOffscreenBlocks[blendStyle] = GFX->createStateBlock(d);
  556. return mOffscreenBlocks[blendStyle];
  557. }
  558. GFXStateBlockRef RenderParticleMgr::_getHighResStateBlock(ParticleRenderInst *ri)
  559. {
  560. const U8 blendStyle = ri->blendStyle;
  561. if ( mHighResBlocks[blendStyle].isValid() )
  562. return mHighResBlocks[blendStyle];
  563. GFXStateBlockDesc d;
  564. d.setZReadWrite(true, false);
  565. d.setCullMode(GFXCullNone);
  566. // Draw everything either subtractive, or using a variation on premultiplied
  567. // alpha
  568. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  569. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  570. else
  571. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  572. d.samplersDefined = true;
  573. // Diffuse texture sampler
  574. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  575. // Deferred sampler
  576. d.samplers[1] = GFXSamplerStateDesc::getClampPoint();
  577. mHighResBlocks[blendStyle] = GFX->createStateBlock(d);
  578. return mHighResBlocks[blendStyle];
  579. }
  580. GFXStateBlockRef RenderParticleMgr::_getMixedResStateBlock(ParticleRenderInst *ri)
  581. {
  582. const U8 blendStyle = ri->blendStyle;
  583. if ( mMixedResBlocks[blendStyle].isValid() )
  584. return mMixedResBlocks[blendStyle];
  585. GFXStateBlockDesc d;
  586. d.setZReadWrite(true, false);
  587. d.setCullMode(GFXCullNone);
  588. /*
  589. // Old blend styles...
  590. switch (blendStyle)
  591. {
  592. case ParticleRenderInst::BlendNormal:
  593. d.blendSrc = GFXBlendSrcAlpha;
  594. d.blendDest = GFXBlendInvSrcAlpha;
  595. break;
  596. case ParticleRenderInst::BlendSubtractive:
  597. d.blendSrc = GFXBlendZero;
  598. d.blendDest = GFXBlendInvSrcColor;
  599. break;
  600. case ParticleRenderInst::BlendPremultAlpha:
  601. d.blendSrc = GFXBlendOne;
  602. d.blendDest = GFXBlendInvSrcAlpha;
  603. break;
  604. // Default to additive blend mode
  605. case ParticleRenderInst::BlendAdditive:
  606. case ParticleRenderInst::BlendUndefined:
  607. default:
  608. d.blendSrc = GFXBlendSrcAlpha;
  609. d.blendDest = GFXBlendOne;
  610. break;
  611. }
  612. */
  613. // Draw everything either subtractive, or using a variation on premultiplied
  614. // alpha
  615. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  616. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  617. else
  618. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  619. // Draw to anything but the stencil ref value (the edges)
  620. d.stencilDefined = true;
  621. d.stencilEnable = true;
  622. d.stencilRef = RenderParticleMgr::HighResStencilRef;
  623. d.stencilMask = RenderParticleMgr::ParticleSystemStencilMask;
  624. d.stencilPassOp = GFXStencilOpKeep;
  625. d.stencilFailOp = GFXStencilOpKeep;
  626. d.stencilZFailOp = GFXStencilOpKeep;
  627. d.stencilFunc = GFXCmpNotEqual;
  628. d.samplersDefined = true;
  629. // Diffuse texture sampler
  630. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  631. // Deferred sampler
  632. d.samplers[1] = GFXSamplerStateDesc::getClampPoint();
  633. mMixedResBlocks[blendStyle] = GFX->createStateBlock(d);
  634. return mMixedResBlocks[blendStyle];
  635. }
  636. GFXStateBlockRef RenderParticleMgr::_getCompositeStateBlock(ParticleRenderInst *ri)
  637. {
  638. const U8 blendStyle = ri->blendStyle;
  639. if ( mBackbufferBlocks[blendStyle].isValid() )
  640. return mBackbufferBlocks[blendStyle];
  641. GFXStateBlockDesc d;
  642. // This is a billboard
  643. d.setCullMode(GFXCullNone);
  644. d.setZReadWrite(false, false);
  645. // When we re-composite the particles, it is always either a pre-mult alpha
  646. // blend, or a subtractive blend!
  647. if(blendStyle == ParticleRenderInst::BlendSubtractive)
  648. d.setBlend(true, GFXBlendZero, GFXBlendInvSrcColor);
  649. else
  650. d.setBlend(true, GFXBlendOne, GFXBlendInvSrcAlpha);
  651. // All areas which are not along the edges of geometry where the particle system
  652. // is being drawn get assigned a stencil ref value as the system is composited
  653. // back into the scene. The high-res stateblock uses this value as a mask, and
  654. // draws only in areas which are NOT this ref value. This causes high resolution
  655. // draws to ONLY the edge areas.
  656. d.stencilDefined = true;
  657. d.stencilEnable = true;
  658. d.stencilRef = RenderParticleMgr::HighResStencilRef;
  659. d.stencilWriteMask = RenderParticleMgr::ParticleSystemStencilMask;
  660. d.stencilMask = RenderParticleMgr::ParticleSystemStencilMask;
  661. d.stencilPassOp = GFXStencilOpReplace;
  662. d.stencilFunc = GFXCmpGreater;
  663. // Diffuse texture sampler and
  664. d.samplersDefined = true;
  665. d.samplers[0] = GFXSamplerStateDesc::getClampLinear();
  666. d.samplers[1] = GFXSamplerStateDesc::getClampLinear();
  667. mBackbufferBlocks[blendStyle] = GFX->createStateBlock(d);
  668. return mBackbufferBlocks[blendStyle];
  669. }
  670. bool RenderParticleMgr::_handleGFXEvent( GFXDevice::GFXDeviceEventType event )
  671. {
  672. if(RenderToSingleTarget)
  673. return Parent::_handleGFXEvent( event );
  674. // Do nothing. This render manager uses its target chain as a pool of targets.
  675. return true;
  676. }