terrRender.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 "terrain/terrRender.h"
  24. #include "terrain/terrData.h"
  25. #include "terrain/terrCell.h"
  26. #include "terrain/terrMaterial.h"
  27. #include "terrain/terrCellMaterial.h"
  28. #include "materials/shaderData.h"
  29. #include "platform/profiler.h"
  30. #include "scene/sceneRenderState.h"
  31. #include "math/util/frustum.h"
  32. #include "renderInstance/renderPassManager.h"
  33. #include "renderInstance/renderTerrainMgr.h"
  34. #include "lighting/lightInfo.h"
  35. #include "lighting/lightManager.h"
  36. #include "materials/matInstance.h"
  37. #include "materials/materialManager.h"
  38. #include "materials/matTextureTarget.h"
  39. #include "shaderGen/conditionerFeature.h"
  40. #include "gfx/gfxDrawUtil.h"
  41. #include "gfx/gfxTransformSaver.h"
  42. #include "gfx/bitmap/gBitmap.h"
  43. #include "gfx/bitmap/ddsFile.h"
  44. #include "gfx/bitmap/ddsUtils.h"
  45. #include "terrain/terrMaterial.h"
  46. #include "gfx/gfxDebugEvent.h"
  47. #include "gfx/gfxCardProfile.h"
  48. #include "core/stream/fileStream.h"
  49. bool TerrainBlock::smDebugRender = false;
  50. GFX_ImplementTextureProfile( TerrainLayerTexProfile,
  51. GFXTextureProfile::DiffuseMap,
  52. GFXTextureProfile::PreserveSize |
  53. GFXTextureProfile::Dynamic,
  54. GFXTextureProfile::NONE );
  55. void TerrainBlock::_onFlushMaterials()
  56. {
  57. if ( mCell )
  58. mCell->deleteMaterials();
  59. SAFE_DELETE( mBaseMaterial );
  60. }
  61. void TerrainBlock::_updateMaterials()
  62. {
  63. mBaseTextures.setSize( mFile->mMaterials.size() );
  64. mMaxDetailDistance = 0.0f;
  65. for ( U32 i=0; i < mFile->mMaterials.size(); i++ )
  66. {
  67. TerrainMaterial *mat = mFile->mMaterials[i];
  68. if( !mat->getDiffuseMap().isEmpty() )
  69. mBaseTextures[i].set( mat->getDiffuseMap(),
  70. &GFXDefaultStaticDiffuseProfile,
  71. "TerrainBlock::_updateMaterials() - DiffuseMap" );
  72. else
  73. mBaseTextures[ i ] = GFXTexHandle();
  74. // Find the maximum detail distance.
  75. if ( mat->getDetailMap().isNotEmpty() &&
  76. mat->getDetailDistance() > mMaxDetailDistance )
  77. mMaxDetailDistance = mat->getDetailDistance();
  78. if ( mat->getMacroMap().isNotEmpty() &&
  79. mat->getMacroDistance() > mMaxDetailDistance )
  80. mMaxDetailDistance = mat->getMacroDistance();
  81. }
  82. if ( mCell )
  83. mCell->deleteMaterials();
  84. }
  85. void TerrainBlock::_updateLayerTexture()
  86. {
  87. const U32 layerSize = mFile->mSize;
  88. const Vector<U8> &layerMap = mFile->mLayerMap;
  89. const U32 pixelCount = layerMap.size();
  90. if ( mLayerTex.isNull() ||
  91. mLayerTex.getWidth() != layerSize ||
  92. mLayerTex.getHeight() != layerSize )
  93. mLayerTex.set( layerSize, layerSize, GFXFormatR8G8B8A8, &TerrainLayerTexProfile, "" );
  94. AssertFatal( mLayerTex.getWidth() == layerSize &&
  95. mLayerTex.getHeight() == layerSize,
  96. "TerrainBlock::_updateLayerTexture - The texture size doesn't match the requested size!" );
  97. // Update the layer texture.
  98. GFXLockedRect *lock = mLayerTex.lock();
  99. for ( U32 i=0; i < pixelCount; i++ )
  100. {
  101. lock->bits[0] = layerMap[i];
  102. if ( i + 1 >= pixelCount )
  103. lock->bits[1] = lock->bits[0];
  104. else
  105. lock->bits[1] = layerMap[i+1];
  106. if ( i + layerSize >= pixelCount )
  107. lock->bits[2] = lock->bits[0];
  108. else
  109. lock->bits[2] = layerMap[i + layerSize];
  110. if ( i + layerSize + 1 >= pixelCount )
  111. lock->bits[3] = lock->bits[0];
  112. else
  113. lock->bits[3] = layerMap[i + layerSize + 1];
  114. lock->bits += 4;
  115. }
  116. mLayerTex.unlock();
  117. //mLayerTex->dumpToDisk( "png", "./layerTex.png" );
  118. }
  119. bool TerrainBlock::_initBaseShader()
  120. {
  121. ShaderData *shaderData = NULL;
  122. if ( !Sim::findObject( "TerrainBlendShader", shaderData ) || !shaderData )
  123. return false;
  124. mBaseShader = shaderData->getShader();
  125. mBaseShaderConsts = mBaseShader->allocConstBuffer();
  126. mBaseTexScaleConst = mBaseShader->getShaderConstHandle( "$texScale" );
  127. mBaseTexIdConst = mBaseShader->getShaderConstHandle( "$texId" );
  128. mBaseLayerSizeConst = mBaseShader->getShaderConstHandle( "$layerSize" );
  129. mBaseTarget = GFX->allocRenderToTextureTarget();
  130. GFXStateBlockDesc desc;
  131. desc.samplersDefined = true;
  132. desc.samplers[0] = GFXSamplerStateDesc::getClampPoint();
  133. desc.samplers[1] = GFXSamplerStateDesc::getWrapLinear();
  134. desc.zDefined = true;
  135. desc.zWriteEnable = false;
  136. desc.zEnable = false;
  137. desc.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  138. desc.cullDefined = true;
  139. desc.cullMode = GFXCullNone;
  140. mBaseShaderSB = GFX->createStateBlock( desc );
  141. return true;
  142. }
  143. void TerrainBlock::_updateBaseTexture( bool writeToCache )
  144. {
  145. if ( !mBaseShader && !_initBaseShader() )
  146. return;
  147. // This can sometimes occur outside a begin/end scene.
  148. const bool sceneBegun = GFX->canCurrentlyRender();
  149. if ( !sceneBegun )
  150. GFX->beginScene();
  151. GFXDEBUGEVENT_SCOPE( TerrainBlock_UpdateBaseTexture, ColorI::GREEN );
  152. PROFILE_SCOPE( TerrainBlock_UpdateBaseTexture );
  153. GFXTransformSaver saver;
  154. const U32 maxTextureSize = GFX->getCardProfiler()->queryProfile( "maxTextureSize", 1024 );
  155. U32 baseTexSize = getNextPow2( mBaseTexSize );
  156. baseTexSize = getMin( maxTextureSize, baseTexSize );
  157. Point2I destSize( baseTexSize, baseTexSize );
  158. // Setup geometry
  159. GFXVertexBufferHandle<GFXVertexPT> vb;
  160. {
  161. F32 copyOffsetX = 2.0f * GFX->getFillConventionOffset() / (F32)destSize.x;
  162. F32 copyOffsetY = 2.0f * GFX->getFillConventionOffset() / (F32)destSize.y;
  163. const bool needsYFlip = GFX->getAdapterType() == OpenGL;
  164. GFXVertexPT points[4];
  165. points[0].point = Point3F( -1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 );
  166. points[0].texCoord = Point2F( 0.0, needsYFlip ? 0.0f : 1.0f );
  167. points[1].point = Point3F( -1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 );
  168. points[1].texCoord = Point2F( 0.0, needsYFlip ? 1.0f : 0.0f );
  169. points[2].point = Point3F( 1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 );
  170. points[2].texCoord = Point2F( 1.0, needsYFlip ? 1.0f : 0.0f );
  171. points[3].point = Point3F( 1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 );
  172. points[3].texCoord = Point2F( 1.0, needsYFlip ? 0.0f : 1.0f );
  173. vb.set( GFX, 4, GFXBufferTypeVolatile );
  174. GFXVertexPT *ptr = vb.lock();
  175. if(ptr)
  176. {
  177. dMemcpy( ptr, points, sizeof(GFXVertexPT) * 4 );
  178. vb.unlock();
  179. }
  180. }
  181. GFXTexHandle blendTex;
  182. // If the base texture is already a valid render target then
  183. // use it to render to else we create one.
  184. if ( mBaseTex.isValid() &&
  185. mBaseTex->isRenderTarget() &&
  186. mBaseTex->getFormat() == GFXFormatR8G8B8A8 &&
  187. mBaseTex->getWidth() == destSize.x &&
  188. mBaseTex->getHeight() == destSize.y )
  189. blendTex = mBaseTex;
  190. else
  191. blendTex.set( destSize.x, destSize.y, GFXFormatR8G8B8A8, &GFXDefaultRenderTargetProfile, "" );
  192. GFX->pushActiveRenderTarget();
  193. // Set our shader stuff
  194. GFX->setShader( mBaseShader );
  195. GFX->setShaderConstBuffer( mBaseShaderConsts );
  196. GFX->setStateBlock( mBaseShaderSB );
  197. GFX->setVertexBuffer( vb );
  198. mBaseTarget->attachTexture( GFXTextureTarget::Color0, blendTex );
  199. GFX->setActiveRenderTarget( mBaseTarget );
  200. GFX->setTexture( 0, mLayerTex );
  201. mBaseShaderConsts->setSafe( mBaseLayerSizeConst, (F32)mLayerTex->getWidth() );
  202. for ( U32 i=0; i < mBaseTextures.size(); i++ )
  203. {
  204. GFXTextureObject *tex = mBaseTextures[i];
  205. if ( !tex )
  206. continue;
  207. GFX->setTexture( 1, tex );
  208. F32 baseSize = mFile->mMaterials[i]->getDiffuseSize();
  209. F32 scale = 1.0f;
  210. if ( !mIsZero( baseSize ) )
  211. scale = getWorldBlockSize() / baseSize;
  212. // A mistake early in development means that texture
  213. // coords are not flipped correctly. To compensate
  214. // we flip the y scale here.
  215. mBaseShaderConsts->setSafe( mBaseTexScaleConst, Point2F( scale, -scale ) );
  216. mBaseShaderConsts->setSafe( mBaseTexIdConst, (F32)i );
  217. GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
  218. }
  219. mBaseTarget->resolve();
  220. GFX->setShader( NULL );
  221. //GFX->setStateBlock( NULL ); // WHY NOT?
  222. GFX->setShaderConstBuffer( NULL );
  223. GFX->setVertexBuffer( NULL );
  224. GFX->popActiveRenderTarget();
  225. // End it if we begun it... Yeehaw!
  226. if ( !sceneBegun )
  227. GFX->endScene();
  228. /// Do we cache this sucker?
  229. if ( writeToCache )
  230. {
  231. String cachePath = _getBaseTexCacheFileName();
  232. FileStream fs;
  233. if ( fs.open( _getBaseTexCacheFileName(), Torque::FS::File::Write ) )
  234. {
  235. // Read back the render target, dxt compress it, and write it to disk.
  236. GBitmap blendBmp( destSize.x, destSize.y, false, GFXFormatR8G8B8A8 );
  237. blendTex.copyToBmp( &blendBmp );
  238. /*
  239. // Test code for dumping uncompressed bitmap to disk.
  240. {
  241. FileStream fs;
  242. if ( fs.open( "./basetex.png", Torque::FS::File::Write ) )
  243. {
  244. blendBmp.writeBitmap( "png", fs );
  245. fs.close();
  246. }
  247. }
  248. */
  249. blendBmp.extrudeMipLevels();
  250. DDSFile *blendDDS = DDSFile::createDDSFileFromGBitmap( &blendBmp );
  251. DDSUtil::squishDDS( blendDDS, GFXFormatDXT1 );
  252. // Write result to file stream
  253. blendDDS->write( fs );
  254. delete blendDDS;
  255. }
  256. fs.close();
  257. }
  258. else
  259. {
  260. // We didn't cache the result, so set the base texture
  261. // to the render target we updated. This should be good
  262. // for realtime painting cases.
  263. mBaseTex = blendTex;
  264. }
  265. }
  266. void TerrainBlock::_renderBlock( SceneRenderState *state )
  267. {
  268. PROFILE_SCOPE( TerrainBlock_RenderBlock );
  269. // Prevent rendering shadows if feature is disabled
  270. if ( !mCastShadows && state->isShadowPass() )
  271. return;
  272. MatrixF worldViewXfm = state->getWorldViewMatrix();
  273. worldViewXfm.mul( getRenderTransform() );
  274. MatrixF worldViewProjXfm = state->getProjectionMatrix();
  275. worldViewProjXfm.mul( worldViewXfm );
  276. const MatrixF &objectXfm = getRenderWorldTransform();
  277. Point3F objCamPos = state->getDiffuseCameraPosition();
  278. objectXfm.mulP( objCamPos );
  279. // Get the shadow material.
  280. if ( !mDefaultMatInst )
  281. mDefaultMatInst = TerrainCellMaterial::getShadowMat();
  282. // Make sure we have a base material.
  283. if ( !mBaseMaterial )
  284. {
  285. mBaseMaterial = new TerrainCellMaterial();
  286. mBaseMaterial->init( this, 0, false, false, true );
  287. }
  288. // Did the detail layers change?
  289. if ( mDetailsDirty )
  290. {
  291. _updateMaterials();
  292. mDetailsDirty = false;
  293. }
  294. // If the layer texture has been cleared or is
  295. // dirty then update it.
  296. if ( mLayerTex.isNull() || mLayerTexDirty )
  297. _updateLayerTexture();
  298. // If the layer texture is dirty or we lost the base
  299. // texture then regenerate it.
  300. if ( mLayerTexDirty || mBaseTex.isNull() )
  301. {
  302. _updateBaseTexture( false );
  303. mLayerTexDirty = false;
  304. }
  305. static Vector<TerrCell*> renderCells;
  306. renderCells.clear();
  307. mCell->cullCells( state,
  308. objCamPos,
  309. &renderCells );
  310. RenderPassManager *renderPass = state->getRenderPass();
  311. MatrixF *riObjectToWorldXfm = renderPass->allocUniqueXform( getRenderTransform() );
  312. const bool isColorDrawPass = state->isDiffusePass() || state->isReflectPass();
  313. // This is here for shadows mostly... it allows the
  314. // proper shadow material to be generated.
  315. BaseMatInstance *defaultMatInst = state->getOverrideMaterial( mDefaultMatInst );
  316. // Only pass and use the light manager if this is not a shadow pass.
  317. LightManager *lm = NULL;
  318. if ( isColorDrawPass )
  319. lm = LIGHTMGR;
  320. for ( U32 i=0; i < renderCells.size(); i++ )
  321. {
  322. TerrCell *cell = renderCells[i];
  323. // Ok this cell is fit to render.
  324. TerrainRenderInst *inst = renderPass->allocInst<TerrainRenderInst>();
  325. // Setup lights for this cell.
  326. if ( lm )
  327. {
  328. SphereF bounds = cell->getSphereBounds();
  329. getRenderTransform().mulP( bounds.center );
  330. LightQuery query;
  331. query.init( bounds );
  332. query.getLights( inst->lights, 8 );
  333. }
  334. GFXVertexBufferHandleBase vertBuff;
  335. GFXPrimitiveBufferHandle primBuff;
  336. cell->getRenderPrimitive( &inst->prim, &vertBuff, &primBuff );
  337. inst->mat = defaultMatInst;
  338. inst->vertBuff = vertBuff.getPointer();
  339. if ( primBuff.isValid() )
  340. {
  341. // Use the cell's custom primitive buffer
  342. inst->primBuff = primBuff.getPointer();
  343. }
  344. else
  345. {
  346. // Use the standard primitive buffer for this cell
  347. inst->primBuff = mPrimBuffer.getPointer();
  348. }
  349. inst->objectToWorldXfm = riObjectToWorldXfm;
  350. // If we're not drawing to the shadow map then we need
  351. // to include the normal rendering materials.
  352. if ( isColorDrawPass )
  353. {
  354. const SphereF &bounds = cell->getSphereBounds();
  355. F32 sqDist = ( bounds.center - objCamPos ).lenSquared();
  356. F32 radiusSq = mSquared( ( mMaxDetailDistance + bounds.radius ) * smDetailScale );
  357. // If this cell is near enough to get detail textures then
  358. // use the full detail mapping material. Else we use the
  359. // simple base only material.
  360. if ( !state->isReflectPass() && sqDist < radiusSq )
  361. inst->cellMat = cell->getMaterial();
  362. else if ( state->isReflectPass() )
  363. inst->cellMat = mBaseMaterial->getReflectMat();
  364. else
  365. inst->cellMat = mBaseMaterial;
  366. }
  367. inst->defaultKey = (U32)cell->getMaterials();
  368. // Submit it for rendering.
  369. renderPass->addInst( inst );
  370. }
  371. // Trigger the debug rendering.
  372. if ( state->isDiffusePass() &&
  373. !renderCells.empty() &&
  374. smDebugRender )
  375. {
  376. // Store the render cells for later.
  377. mDebugCells = renderCells;
  378. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  379. ri->renderDelegate.bind( this, &TerrainBlock::_renderDebug );
  380. ri->type = RenderPassManager::RIT_Editor;
  381. state->getRenderPass()->addInst( ri );
  382. }
  383. }
  384. void TerrainBlock::_renderDebug( ObjectRenderInst *ri,
  385. SceneRenderState *state,
  386. BaseMatInstance *overrideMat )
  387. {
  388. GFXTransformSaver saver;
  389. GFX->multWorld( getRenderTransform() );
  390. for ( U32 i=0; i < mDebugCells.size(); i++ )
  391. mDebugCells[i]->renderBounds();
  392. mDebugCells.clear();
  393. }