terrRender.cpp 16 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 "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, GFXBlendOne );
  138. desc.cullDefined = true;
  139. desc.cullMode = GFXCullNone;
  140. desc.colorWriteAlpha = false;
  141. mBaseShaderSB = GFX->createStateBlock( desc );
  142. return true;
  143. }
  144. void TerrainBlock::_updateBaseTexture( bool writeToCache )
  145. {
  146. if ( !mBaseShader && !_initBaseShader() )
  147. return;
  148. // This can sometimes occur outside a begin/end scene.
  149. const bool sceneBegun = GFX->canCurrentlyRender();
  150. if ( !sceneBegun )
  151. GFX->beginScene();
  152. GFXDEBUGEVENT_SCOPE( TerrainBlock_UpdateBaseTexture, ColorI::GREEN );
  153. PROFILE_SCOPE( TerrainBlock_UpdateBaseTexture );
  154. GFXTransformSaver saver;
  155. const U32 maxTextureSize = GFX->getCardProfiler()->queryProfile( "maxTextureSize", 1024 );
  156. U32 baseTexSize = getNextPow2( mBaseTexSize );
  157. baseTexSize = getMin( maxTextureSize, baseTexSize );
  158. Point2I destSize( baseTexSize, baseTexSize );
  159. // Setup geometry
  160. GFXVertexBufferHandle<GFXVertexPT> vb;
  161. {
  162. F32 copyOffsetX = 2.0f * GFX->getFillConventionOffset() / (F32)destSize.x;
  163. F32 copyOffsetY = 2.0f * GFX->getFillConventionOffset() / (F32)destSize.y;
  164. const bool needsYFlip = GFX->getAdapterType() == OpenGL;
  165. GFXVertexPT points[4];
  166. points[0].point = Point3F( -1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 );
  167. points[0].texCoord = Point2F( 0.0, needsYFlip ? 0.0f : 1.0f );
  168. points[1].point = Point3F( -1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 );
  169. points[1].texCoord = Point2F( 0.0, needsYFlip ? 1.0f : 0.0f );
  170. points[2].point = Point3F( 1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 );
  171. points[2].texCoord = Point2F( 1.0, needsYFlip ? 1.0f : 0.0f );
  172. points[3].point = Point3F( 1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 );
  173. points[3].texCoord = Point2F( 1.0, needsYFlip ? 0.0f : 1.0f );
  174. vb.set( GFX, 4, GFXBufferTypeVolatile );
  175. GFXVertexPT *ptr = vb.lock();
  176. if(ptr)
  177. {
  178. dMemcpy( ptr, points, sizeof(GFXVertexPT) * 4 );
  179. vb.unlock();
  180. }
  181. }
  182. GFXTexHandle blendTex;
  183. // If the base texture is already a valid render target then
  184. // use it to render to else we create one.
  185. if ( mBaseTex.isValid() &&
  186. mBaseTex->isRenderTarget() &&
  187. mBaseTex->getFormat() == GFXFormatR8G8B8A8 &&
  188. mBaseTex->getWidth() == destSize.x &&
  189. mBaseTex->getHeight() == destSize.y )
  190. blendTex = mBaseTex;
  191. else
  192. blendTex.set( destSize.x, destSize.y, GFXFormatR8G8B8A8, &GFXDefaultRenderTargetProfile, "" );
  193. GFX->pushActiveRenderTarget();
  194. // Set our shader stuff
  195. GFX->setShader( mBaseShader );
  196. GFX->setShaderConstBuffer( mBaseShaderConsts );
  197. GFX->setStateBlock( mBaseShaderSB );
  198. GFX->setVertexBuffer( vb );
  199. mBaseTarget->attachTexture( GFXTextureTarget::Color0, blendTex );
  200. GFX->setActiveRenderTarget( mBaseTarget );
  201. GFX->clear( GFXClearTarget, ColorI(0,0,0,255), 1.0f, 0 );
  202. GFX->setTexture( 0, mLayerTex );
  203. mBaseShaderConsts->setSafe( mBaseLayerSizeConst, (F32)mLayerTex->getWidth() );
  204. for ( U32 i=0; i < mBaseTextures.size(); i++ )
  205. {
  206. GFXTextureObject *tex = mBaseTextures[i];
  207. if ( !tex )
  208. continue;
  209. GFX->setTexture( 1, tex );
  210. F32 baseSize = mFile->mMaterials[i]->getDiffuseSize();
  211. F32 scale = 1.0f;
  212. if ( !mIsZero( baseSize ) )
  213. scale = getWorldBlockSize() / baseSize;
  214. // A mistake early in development means that texture
  215. // coords are not flipped correctly. To compensate
  216. // we flip the y scale here.
  217. mBaseShaderConsts->setSafe( mBaseTexScaleConst, Point2F( scale, -scale ) );
  218. mBaseShaderConsts->setSafe( mBaseTexIdConst, (F32)i );
  219. GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
  220. }
  221. mBaseTarget->resolve();
  222. GFX->setShader( NULL );
  223. //GFX->setStateBlock( NULL ); // WHY NOT?
  224. GFX->setShaderConstBuffer( NULL );
  225. GFX->setVertexBuffer( NULL );
  226. GFX->popActiveRenderTarget();
  227. // End it if we begun it... Yeehaw!
  228. if ( !sceneBegun )
  229. GFX->endScene();
  230. /// Do we cache this sucker?
  231. if ( writeToCache )
  232. {
  233. String cachePath = _getBaseTexCacheFileName();
  234. FileStream fs;
  235. if ( fs.open( _getBaseTexCacheFileName(), Torque::FS::File::Write ) )
  236. {
  237. // Read back the render target, dxt compress it, and write it to disk.
  238. GBitmap blendBmp( destSize.x, destSize.y, false, GFXFormatR8G8B8A8 );
  239. blendTex.copyToBmp( &blendBmp );
  240. /*
  241. // Test code for dumping uncompressed bitmap to disk.
  242. {
  243. FileStream fs;
  244. if ( fs.open( "./basetex.png", Torque::FS::File::Write ) )
  245. {
  246. blendBmp.writeBitmap( "png", fs );
  247. fs.close();
  248. }
  249. }
  250. */
  251. blendBmp.extrudeMipLevels();
  252. DDSFile *blendDDS = DDSFile::createDDSFileFromGBitmap( &blendBmp );
  253. DDSUtil::squishDDS( blendDDS, GFXFormatDXT1 );
  254. // Write result to file stream
  255. blendDDS->write( fs );
  256. delete blendDDS;
  257. }
  258. fs.close();
  259. }
  260. else
  261. {
  262. // We didn't cache the result, so set the base texture
  263. // to the render target we updated. This should be good
  264. // for realtime painting cases.
  265. mBaseTex = blendTex;
  266. }
  267. }
  268. void TerrainBlock::_renderBlock( SceneRenderState *state )
  269. {
  270. PROFILE_SCOPE( TerrainBlock_RenderBlock );
  271. // Prevent rendering shadows if feature is disabled
  272. if ( !mCastShadows && state->isShadowPass() )
  273. return;
  274. MatrixF worldViewXfm = state->getWorldViewMatrix();
  275. worldViewXfm.mul( getRenderTransform() );
  276. MatrixF worldViewProjXfm = state->getProjectionMatrix();
  277. worldViewProjXfm.mul( worldViewXfm );
  278. const MatrixF &objectXfm = getRenderWorldTransform();
  279. Point3F objCamPos = state->getDiffuseCameraPosition();
  280. objectXfm.mulP( objCamPos );
  281. // Get the shadow material.
  282. if ( !mDefaultMatInst )
  283. mDefaultMatInst = TerrainCellMaterial::getShadowMat();
  284. // Make sure we have a base material.
  285. if ( !mBaseMaterial )
  286. {
  287. mBaseMaterial = new TerrainCellMaterial();
  288. mBaseMaterial->init( this, 0, false, false, true );
  289. }
  290. // Did the detail layers change?
  291. if ( mDetailsDirty )
  292. {
  293. _updateMaterials();
  294. mDetailsDirty = false;
  295. }
  296. // If the layer texture has been cleared or is
  297. // dirty then update it.
  298. if ( mLayerTex.isNull() || mLayerTexDirty )
  299. _updateLayerTexture();
  300. // If the layer texture is dirty or we lost the base
  301. // texture then regenerate it.
  302. if ( mLayerTexDirty || mBaseTex.isNull() )
  303. {
  304. _updateBaseTexture( false );
  305. mLayerTexDirty = false;
  306. }
  307. static Vector<TerrCell*> renderCells;
  308. renderCells.clear();
  309. mCell->cullCells( state,
  310. objCamPos,
  311. &renderCells );
  312. RenderPassManager *renderPass = state->getRenderPass();
  313. MatrixF *riObjectToWorldXfm = renderPass->allocUniqueXform( getRenderTransform() );
  314. const bool isColorDrawPass = state->isDiffusePass() || state->isReflectPass();
  315. // This is here for shadows mostly... it allows the
  316. // proper shadow material to be generated.
  317. BaseMatInstance *defaultMatInst = state->getOverrideMaterial( mDefaultMatInst );
  318. // Only pass and use the light manager if this is not a shadow pass.
  319. LightManager *lm = NULL;
  320. if ( isColorDrawPass )
  321. lm = LIGHTMGR;
  322. for ( U32 i=0; i < renderCells.size(); i++ )
  323. {
  324. TerrCell *cell = renderCells[i];
  325. // Ok this cell is fit to render.
  326. TerrainRenderInst *inst = renderPass->allocInst<TerrainRenderInst>();
  327. // Setup lights for this cell.
  328. if ( lm )
  329. {
  330. SphereF bounds = cell->getSphereBounds();
  331. getRenderTransform().mulP( bounds.center );
  332. LightQuery query;
  333. query.init( bounds );
  334. query.getLights( inst->lights, 8 );
  335. }
  336. GFXVertexBufferHandleBase vertBuff;
  337. GFXPrimitiveBufferHandle primBuff;
  338. cell->getRenderPrimitive( &inst->prim, &vertBuff, &primBuff );
  339. inst->mat = defaultMatInst;
  340. inst->vertBuff = vertBuff.getPointer();
  341. if ( primBuff.isValid() )
  342. {
  343. // Use the cell's custom primitive buffer
  344. inst->primBuff = primBuff.getPointer();
  345. }
  346. else
  347. {
  348. // Use the standard primitive buffer for this cell
  349. inst->primBuff = mPrimBuffer.getPointer();
  350. }
  351. inst->objectToWorldXfm = riObjectToWorldXfm;
  352. // If we're not drawing to the shadow map then we need
  353. // to include the normal rendering materials.
  354. if ( isColorDrawPass )
  355. {
  356. const SphereF &bounds = cell->getSphereBounds();
  357. F32 sqDist = ( bounds.center - objCamPos ).lenSquared();
  358. F32 radiusSq = mSquared( ( mMaxDetailDistance + bounds.radius ) * smDetailScale );
  359. // If this cell is near enough to get detail textures then
  360. // use the full detail mapping material. Else we use the
  361. // simple base only material.
  362. if ( !state->isReflectPass() && sqDist < radiusSq )
  363. inst->cellMat = cell->getMaterial();
  364. else if ( state->isReflectPass() )
  365. inst->cellMat = mBaseMaterial->getReflectMat();
  366. else
  367. inst->cellMat = mBaseMaterial;
  368. }
  369. inst->defaultKey = (U32)cell->getMaterials();
  370. // Submit it for rendering.
  371. renderPass->addInst( inst );
  372. }
  373. // Trigger the debug rendering.
  374. if ( state->isDiffusePass() &&
  375. !renderCells.empty() &&
  376. smDebugRender )
  377. {
  378. // Store the render cells for later.
  379. mDebugCells = renderCells;
  380. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  381. ri->renderDelegate.bind( this, &TerrainBlock::_renderDebug );
  382. ri->type = RenderPassManager::RIT_Editor;
  383. state->getRenderPass()->addInst( ri );
  384. }
  385. }
  386. void TerrainBlock::_renderDebug( ObjectRenderInst *ri,
  387. SceneRenderState *state,
  388. BaseMatInstance *overrideMat )
  389. {
  390. GFXTransformSaver saver;
  391. GFX->multWorld( getRenderTransform() );
  392. for ( U32 i=0; i < mDebugCells.size(); i++ )
  393. mDebugCells[i]->renderBounds();
  394. mDebugCells.clear();
  395. }