cloudLayer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 "platform/profiler.h"
  24. #include "console/consoleTypes.h"
  25. #include "cloudLayer.h"
  26. #include "gfx/gfxTransformSaver.h"
  27. #include "gfx/gfxTextureManager.h"
  28. #include "core/stream/fileStream.h"
  29. #include "core/stream/bitStream.h"
  30. #include "scene/sceneRenderState.h"
  31. #include "renderInstance/renderPassManager.h"
  32. #include "gfx/primBuilder.h"
  33. #include "materials/materialManager.h"
  34. #include "materials/customMaterialDefinition.h"
  35. #include "materials/shaderData.h"
  36. #include "lighting/lightInfo.h"
  37. #include "math/mathIO.h"
  38. ConsoleDocClass( CloudLayer,
  39. "@brief A layer of clouds which change shape over time and are affected by scene lighting.\n\n"
  40. "%CloudLayer always renders overhead, following the camera. It is intended "
  41. "as part of the background of your level, rendering in front of Sky/Sun "
  42. "type objects and behind everything else.\n\n"
  43. "The illusion of clouds forming and changing over time is controlled by the "
  44. "normal/opacity texture and the three sets of texture animation parameters. "
  45. "The texture is sampled three times. The first sample defines overall cloud "
  46. "density, where clouds are likely to form and their general size and shape. "
  47. "The second two samples control how it changes over time; they are "
  48. "combined and used as modifiers to the first sample.\n\n"
  49. "%CloudLayer is affected by scene lighting and is designed to be used in "
  50. "scenes with dynamic lighting or time of day changes.\n\n"
  51. "@ingroup Atmosphere"
  52. );
  53. GFXImplementVertexFormat( GFXCloudVertex )
  54. {
  55. addElement( "POSITION", GFXDeclType_Float3 );
  56. addElement( "NORMAL", GFXDeclType_Float3 );
  57. addElement( "BINORMAL", GFXDeclType_Float3 );
  58. addElement( "TANGENT", GFXDeclType_Float3 );
  59. addElement( "TEXCOORD", GFXDeclType_Float2, 0 );
  60. }
  61. U32 CloudLayer::smVertStride = 50;
  62. U32 CloudLayer::smStrideMinusOne = smVertStride - 1;
  63. U32 CloudLayer::smVertCount = smVertStride * smVertStride;
  64. U32 CloudLayer::smTriangleCount = smStrideMinusOne * smStrideMinusOne * 2;
  65. CloudLayer::CloudLayer()
  66. : mLastTime( 0 ),
  67. mBaseColor( 0.9f, 0.9f, 0.9f, 1.0f ),
  68. mExposure( 1.0f ),
  69. mCoverage( 0.5f ),
  70. mWindSpeed( 1.0f )
  71. {
  72. mTypeMask |= EnvironmentObjectType | StaticObjectType;
  73. mNetFlags.set(Ghostable | ScopeAlways);
  74. mModelViewProjSC =
  75. mAmbientColorSC =
  76. mSunColorSC =
  77. mSunVecSC =
  78. mTexScaleSC =
  79. mBaseColorSC =
  80. mCoverageSC =
  81. mExposureSC =
  82. mEyePosWorldSC = 0;
  83. mTexOffsetSC[0] = mTexOffsetSC[1] = mTexOffsetSC[2] = 0;
  84. mTexScale[0] = 1.0;
  85. mTexScale[1] = 1.0;
  86. mTexScale[2] = 1.0;
  87. mTexDirection[0].set( 1.0f, 0.0f );
  88. mTexDirection[1].set( 0.0f, 1.0f );
  89. mTexDirection[2].set( 0.5f, 0.0f );
  90. mTexSpeed[0] = 0.005f;
  91. mTexSpeed[1] = 0.005f;
  92. mTexSpeed[2] = 0.005f;
  93. mTexOffset[0] = mTexOffset[1] = mTexOffset[2] = Point2F::Zero;
  94. mHeight = 4.0f;
  95. }
  96. IMPLEMENT_CO_NETOBJECT_V1( CloudLayer );
  97. // ConsoleObject...
  98. bool CloudLayer::onAdd()
  99. {
  100. if ( !Parent::onAdd() )
  101. return false;
  102. setGlobalBounds();
  103. resetWorldBox();
  104. addToScene();
  105. if ( isClientObject() )
  106. {
  107. _initTexture();
  108. _initBuffers();
  109. // Find ShaderData
  110. ShaderData *shaderData;
  111. mShader = Sim::findObject( "CloudLayerShader", shaderData ) ?
  112. shaderData->getShader() : NULL;
  113. if ( !mShader )
  114. {
  115. Con::errorf( "CloudLayer::onAdd - could not find CloudLayerShader" );
  116. return false;
  117. }
  118. // Create ShaderConstBuffer and Handles
  119. mShaderConsts = mShader->allocConstBuffer();
  120. mModelViewProjSC = mShader->getShaderConstHandle( "$modelView" );
  121. mEyePosWorldSC = mShader->getShaderConstHandle( "$eyePosWorld" );
  122. mSunVecSC = mShader->getShaderConstHandle( "$sunVec" );
  123. mTexOffsetSC[0] = mShader->getShaderConstHandle( "$texOffset0" );
  124. mTexOffsetSC[1] = mShader->getShaderConstHandle( "$texOffset1" );
  125. mTexOffsetSC[2] = mShader->getShaderConstHandle( "$texOffset2" );
  126. mTexScaleSC = mShader->getShaderConstHandle( "$texScale" );
  127. mAmbientColorSC = mShader->getShaderConstHandle( "$ambientColor" );
  128. mSunColorSC = mShader->getShaderConstHandle( "$sunColor" );
  129. mCoverageSC = mShader->getShaderConstHandle( "$cloudCoverage" );
  130. mExposureSC = mShader->getShaderConstHandle( "$cloudExposure" );
  131. mBaseColorSC = mShader->getShaderConstHandle( "$cloudBaseColor" );
  132. mNormalHeightMapSC = mShader->getShaderConstHandle( "$normalHeightMap" );
  133. // Create StateBlocks
  134. GFXStateBlockDesc desc;
  135. desc.setCullMode( GFXCullNone );
  136. desc.setBlend( true );
  137. desc.setZReadWrite( true, false );
  138. desc.samplersDefined = true;
  139. desc.samplers[0].addressModeU = GFXAddressWrap;
  140. desc.samplers[0].addressModeV = GFXAddressWrap;
  141. desc.samplers[0].addressModeW = GFXAddressWrap;
  142. desc.samplers[0].magFilter = GFXTextureFilterLinear;
  143. desc.samplers[0].minFilter = GFXTextureFilterLinear;
  144. desc.samplers[0].mipFilter = GFXTextureFilterLinear;
  145. desc.samplers[0].textureColorOp = GFXTOPModulate;
  146. mStateblock = GFX->createStateBlock( desc );
  147. }
  148. return true;
  149. }
  150. void CloudLayer::onRemove()
  151. {
  152. removeFromScene();
  153. Parent::onRemove();
  154. }
  155. void CloudLayer::initPersistFields()
  156. {
  157. addGroup( "CloudLayer" );
  158. addField( "texture", TypeImageFilename, Offset( mTextureName, CloudLayer ),
  159. "An RGBA texture which should contain normals and opacity (density)." );
  160. addArray( "Textures", TEX_COUNT );
  161. addField( "texScale", TypeF32, Offset( mTexScale, CloudLayer ), TEX_COUNT,
  162. "Controls the texture repeat of this slot." );
  163. addField( "texDirection", TypePoint2F, Offset( mTexDirection, CloudLayer ), TEX_COUNT,
  164. "Controls the direction this slot scrolls." );
  165. addField( "texSpeed", TypeF32, Offset( mTexSpeed, CloudLayer ), TEX_COUNT,
  166. "Controls the speed this slot scrolls." );
  167. endArray( "Textures" );
  168. addField( "baseColor", TypeColorF, Offset( mBaseColor, CloudLayer ),
  169. "Base cloud color before lighting." );
  170. addField( "exposure", TypeF32, Offset( mExposure, CloudLayer ),
  171. "Brightness scale so CloudLayer can be overblown if desired." );
  172. addField( "coverage", TypeF32, Offset( mCoverage, CloudLayer ),
  173. "Fraction of sky covered by clouds 0-1." );
  174. addField( "windSpeed", TypeF32, Offset( mWindSpeed, CloudLayer ),
  175. "Overall scalar to texture scroll speed." );
  176. addField( "height", TypeF32, Offset( mHeight, CloudLayer ),
  177. "Abstract number which controls the curvature and height of the dome mesh." );
  178. endGroup( "CloudLayer" );
  179. Parent::initPersistFields();
  180. }
  181. void CloudLayer::inspectPostApply()
  182. {
  183. Parent::inspectPostApply();
  184. setMaskBits( CloudLayerMask );
  185. }
  186. // NetObject...
  187. U32 CloudLayer::packUpdate( NetConnection *conn, U32 mask, BitStream *stream )
  188. {
  189. U32 retMask = Parent::packUpdate( conn, mask, stream );
  190. stream->write( mTextureName );
  191. for ( U32 i = 0; i < TEX_COUNT; i++ )
  192. {
  193. stream->write( mTexScale[i] );
  194. stream->write( mTexSpeed[i] );
  195. mathWrite( *stream, mTexDirection[i] );
  196. }
  197. stream->write( mBaseColor );
  198. stream->write( mCoverage );
  199. stream->write( mExposure );
  200. stream->write( mWindSpeed );
  201. stream->write( mHeight );
  202. return retMask;
  203. }
  204. void CloudLayer::unpackUpdate( NetConnection *conn, BitStream *stream )
  205. {
  206. Parent::unpackUpdate( conn, stream );
  207. String oldTextureName = mTextureName;
  208. stream->read( &mTextureName );
  209. for ( U32 i = 0; i < TEX_COUNT; i++ )
  210. {
  211. stream->read( &mTexScale[i] );
  212. stream->read( &mTexSpeed[i] );
  213. mathRead( *stream, &mTexDirection[i] );
  214. }
  215. stream->read( &mBaseColor );
  216. F32 oldCoverage = mCoverage;
  217. stream->read( &mCoverage );
  218. stream->read( &mExposure );
  219. stream->read( &mWindSpeed );
  220. F32 oldHeight = mHeight;
  221. stream->read( &mHeight );
  222. if ( isProperlyAdded() )
  223. {
  224. if ( ( oldTextureName != mTextureName ) || ( ( oldCoverage == 0.0f ) != ( mCoverage == 0.0f ) ) )
  225. _initTexture();
  226. if ( oldHeight != mHeight )
  227. _initBuffers();
  228. }
  229. }
  230. // SceneObject...
  231. void CloudLayer::prepRenderImage( SceneRenderState *state )
  232. {
  233. PROFILE_SCOPE( CloudLayer_prepRenderImage );
  234. if ( mCoverage <= 0.0f )
  235. return;
  236. if ( state->isDiffusePass() )
  237. {
  238. // Scroll textures...
  239. U32 time = Sim::getCurrentTime();
  240. F32 delta = (F32)( time - mLastTime ) / 1000.0f;
  241. mLastTime = time;
  242. for ( U32 i = 0; i < 3; i++ )
  243. {
  244. mTexOffset[i] += mTexDirection[i] * mTexSpeed[i] * delta * mWindSpeed;
  245. }
  246. }
  247. // This should be sufficient for most objects that don't manage zones, and
  248. // don't need to return a specialized RenderImage...
  249. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  250. ri->renderDelegate.bind( this, &CloudLayer::renderObject );
  251. ri->type = RenderPassManager::RIT_Sky;
  252. ri->defaultKey = 0;
  253. ri->defaultKey2 = 0;
  254. state->getRenderPass()->addInst( ri );
  255. }
  256. void CloudLayer::renderObject( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *mi )
  257. {
  258. GFXTransformSaver saver;
  259. const Point3F &camPos = state->getCameraPosition();
  260. MatrixF xfm(true);
  261. xfm.setPosition(camPos);
  262. GFX->multWorld(xfm);
  263. if ( state->isReflectPass() )
  264. GFX->setProjectionMatrix( state->getSceneManager()->getNonClipProjection() );
  265. GFX->setShader( mShader );
  266. GFX->setShaderConstBuffer( mShaderConsts );
  267. GFX->setStateBlock( mStateblock );
  268. // Set all the shader consts...
  269. MatrixF xform(GFX->getProjectionMatrix());
  270. xform *= GFX->getViewMatrix();
  271. xform *= GFX->getWorldMatrix();
  272. mShaderConsts->setSafe( mModelViewProjSC, xform );
  273. mShaderConsts->setSafe( mEyePosWorldSC, camPos );
  274. LightInfo *lightinfo = LIGHTMGR->getSpecialLight(LightManager::slSunLightType);
  275. const ColorF &sunlight = state->getAmbientLightColor();
  276. Point3F ambientColor( sunlight.red, sunlight.green, sunlight.blue );
  277. mShaderConsts->setSafe( mAmbientColorSC, ambientColor );
  278. const ColorF &sunColor = lightinfo->getColor();
  279. Point3F data( sunColor.red, sunColor.green, sunColor.blue );
  280. mShaderConsts->setSafe( mSunColorSC, data );
  281. mShaderConsts->setSafe( mSunVecSC, lightinfo->getDirection() );
  282. for ( U32 i = 0; i < TEX_COUNT; i++ )
  283. mShaderConsts->setSafe( mTexOffsetSC[i], mTexOffset[i] );
  284. Point3F scale( mTexScale[0], mTexScale[1], mTexScale[2] );
  285. mShaderConsts->setSafe( mTexScaleSC, scale );
  286. Point3F color;
  287. color.set( mBaseColor.red, mBaseColor.green, mBaseColor.blue );
  288. mShaderConsts->setSafe( mBaseColorSC, color );
  289. mShaderConsts->setSafe( mCoverageSC, mCoverage );
  290. mShaderConsts->setSafe( mExposureSC, mExposure );
  291. GFX->setTexture( mNormalHeightMapSC->getSamplerRegister(), mTexture );
  292. GFX->setVertexBuffer( mVB );
  293. GFX->setPrimitiveBuffer( mPB );
  294. GFX->drawIndexedPrimitive( GFXTriangleList, 0, 0, smVertCount, 0, smTriangleCount );
  295. }
  296. // CloudLayer Internal Methods....
  297. void CloudLayer::_initTexture()
  298. {
  299. if ( mCoverage <= 0.0f )
  300. {
  301. mTexture = NULL;
  302. return;
  303. }
  304. if ( mTextureName.isNotEmpty() )
  305. mTexture.set( mTextureName, &GFXDefaultStaticDiffuseProfile, "CloudLayer" );
  306. if ( mTexture.isNull() )
  307. mTexture.set( GFXTextureManager::getWarningTexturePath(), &GFXDefaultStaticDiffuseProfile, "CloudLayer" );
  308. }
  309. void CloudLayer::_initBuffers()
  310. {
  311. // Vertex Buffer...
  312. Point3F vertScale( 16.0f, 16.0f, mHeight );
  313. F32 zOffset = -( mCos( mSqrt( 1.0f ) ) + 0.01f );
  314. mVB.set( GFX, smVertCount, GFXBufferTypeStatic );
  315. GFXCloudVertex *pVert = mVB.lock();
  316. if(!pVert) return;
  317. for ( U32 y = 0; y < smVertStride; y++ )
  318. {
  319. F32 v = ( (F32)y / (F32)smStrideMinusOne - 0.5f ) * 2.0f;
  320. for ( U32 x = 0; x < smVertStride; x++ )
  321. {
  322. F32 u = ( (F32)x / (F32)smStrideMinusOne - 0.5f ) * 2.0f;
  323. F32 sx = u;
  324. F32 sy = v;
  325. F32 sz = mCos( mSqrt( sx*sx + sy*sy ) ) + zOffset;
  326. //F32 sz = 1.0f;
  327. pVert->point.set( sx, sy, sz );
  328. pVert->point *= vertScale;
  329. // The vert to our right.
  330. Point3F rpnt;
  331. F32 ru = ( (F32)( x + 1 ) / (F32)smStrideMinusOne - 0.5f ) * 2.0f;
  332. F32 rv = v;
  333. rpnt.x = ru;
  334. rpnt.y = rv;
  335. rpnt.z = mCos( mSqrt( rpnt.x*rpnt.x + rpnt.y*rpnt.y ) ) + zOffset;
  336. rpnt *= vertScale;
  337. // The vert to our front.
  338. Point3F fpnt;
  339. F32 fu = u;
  340. F32 fv = ( (F32)( y + 1 ) / (F32)smStrideMinusOne - 0.5f ) * 2.0f;
  341. fpnt.x = fu;
  342. fpnt.y = fv;
  343. fpnt.z = mCos( mSqrt( fpnt.x*fpnt.x + fpnt.y*fpnt.y ) ) + zOffset;
  344. fpnt *= vertScale;
  345. Point3F fvec = fpnt - pVert->point;
  346. fvec.normalize();
  347. Point3F rvec = rpnt - pVert->point;
  348. rvec.normalize();
  349. pVert->normal = mCross( fvec, rvec );
  350. pVert->normal.normalize();
  351. pVert->binormal = fvec;
  352. pVert->tangent = rvec;
  353. pVert->texCoord.set( u, v );
  354. pVert++;
  355. }
  356. }
  357. mVB.unlock();
  358. // Primitive Buffer...
  359. mPB.set( GFX, smTriangleCount * 3, smTriangleCount, GFXBufferTypeStatic );
  360. U16 *pIdx = NULL;
  361. mPB.lock(&pIdx);
  362. U32 curIdx = 0;
  363. for ( U32 y = 0; y < smStrideMinusOne; y++ )
  364. {
  365. for ( U32 x = 0; x < smStrideMinusOne; x++ )
  366. {
  367. U32 offset = x + y * smVertStride;
  368. pIdx[curIdx] = offset;
  369. curIdx++;
  370. pIdx[curIdx] = offset + 1;
  371. curIdx++;
  372. pIdx[curIdx] = offset + smVertStride + 1;
  373. curIdx++;
  374. pIdx[curIdx] = offset;
  375. curIdx++;
  376. pIdx[curIdx] = offset + smVertStride + 1;
  377. curIdx++;
  378. pIdx[curIdx] = offset + smVertStride;
  379. curIdx++;
  380. }
  381. }
  382. mPB.unlock();
  383. }