cloudLayer.cpp 15 KB

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