imposterCapture.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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 "util/imposterCapture.h"
  24. #include "gfx/bitmap/gBitmap.h"
  25. #include "core/color.h"
  26. #include "renderInstance/renderPassManager.h"
  27. #include "renderInstance/renderMeshMgr.h"
  28. #include "materials/materialManager.h"
  29. #include "materials/materialFeatureTypes.h"
  30. #include "materials/customMaterialDefinition.h"
  31. #include "ts/tsShapeInstance.h"
  32. #include "scene/sceneManager.h"
  33. #include "scene/sceneRenderState.h"
  34. #include "lighting/lightInfo.h"
  35. #include "gfx/gfxTransformSaver.h"
  36. #include "gfx/gfxDebugEvent.h"
  37. #include "core/stream/fileStream.h"
  38. /// A material hook used to hold imposter generation
  39. /// rendering materials for an object.
  40. class ImposterCaptureMaterialHook : public MatInstanceHook
  41. {
  42. public:
  43. ImposterCaptureMaterialHook();
  44. // MatInstanceHook
  45. virtual ~ImposterCaptureMaterialHook();
  46. virtual const MatInstanceHookType& getType() const { return Type; }
  47. /// The material hook type.
  48. static const MatInstanceHookType Type;
  49. void init( BaseMatInstance *mat );
  50. static BaseMatInstance* getDiffuseInst( BaseMatInstance *inMat )
  51. { return _getOrCreateHook( inMat )->mDiffuseMatInst; }
  52. static BaseMatInstance* getNormalsInst( BaseMatInstance *inMat )
  53. { return _getOrCreateHook( inMat )->mNormalsMatInst; }
  54. protected:
  55. static void _overrideFeatures( ProcessedMaterial *mat,
  56. U32 stageNum,
  57. MaterialFeatureData &fd,
  58. const FeatureSet &features );
  59. static ImposterCaptureMaterialHook* _getOrCreateHook( BaseMatInstance *inMat );
  60. ///
  61. BaseMatInstance *mDiffuseMatInst;
  62. ///
  63. BaseMatInstance *mNormalsMatInst;
  64. };
  65. const MatInstanceHookType ImposterCaptureMaterialHook::Type( "ImposterCapture" );
  66. ImposterCaptureMaterialHook::ImposterCaptureMaterialHook()
  67. : mDiffuseMatInst( NULL ),
  68. mNormalsMatInst( NULL )
  69. {
  70. }
  71. ImposterCaptureMaterialHook::~ImposterCaptureMaterialHook()
  72. {
  73. SAFE_DELETE( mDiffuseMatInst );
  74. SAFE_DELETE( mNormalsMatInst );
  75. }
  76. void ImposterCaptureMaterialHook::init( BaseMatInstance *inMat )
  77. {
  78. // We cannot capture impostors on custom materials
  79. // as we don't know how to get just diffuse and just
  80. // normals rendering.
  81. if ( dynamic_cast<CustomMaterial*>( inMat->getMaterial() ) )
  82. return;
  83. // Tweak the feature data to include just what we need.
  84. FeatureSet features;
  85. features.addFeature( MFT_VertTransform );
  86. features.addFeature( MFT_DiffuseMap );
  87. features.addFeature( MFT_OverlayMap );
  88. features.addFeature( MFT_DetailMap );
  89. features.addFeature( MFT_DiffuseColor );
  90. features.addFeature( MFT_AlphaTest );
  91. features.addFeature( MFT_IsTranslucent );
  92. const String &matName = inMat->getMaterial()->getName();
  93. mDiffuseMatInst = MATMGR->createMatInstance( matName );
  94. mDiffuseMatInst->getFeaturesDelegate().bind( &ImposterCaptureMaterialHook::_overrideFeatures );
  95. mDiffuseMatInst->init( features, inMat->getVertexFormat() );
  96. features.addFeature( MFT_IsDXTnm );
  97. features.addFeature( MFT_NormalMap );
  98. features.addFeature( MFT_NormalsOut );
  99. mNormalsMatInst = MATMGR->createMatInstance( matName );
  100. mNormalsMatInst->getFeaturesDelegate().bind( &ImposterCaptureMaterialHook::_overrideFeatures );
  101. mNormalsMatInst->init( features, inMat->getVertexFormat() );
  102. }
  103. void ImposterCaptureMaterialHook::_overrideFeatures( ProcessedMaterial *mat,
  104. U32 stageNum,
  105. MaterialFeatureData &fd,
  106. const FeatureSet &features )
  107. {
  108. if ( features.hasFeature( MFT_NormalsOut) )
  109. fd.features.addFeature( MFT_NormalsOut );
  110. fd.features.addFeature( MFT_ForwardShading );
  111. }
  112. ImposterCaptureMaterialHook* ImposterCaptureMaterialHook::_getOrCreateHook( BaseMatInstance *inMat )
  113. {
  114. ImposterCaptureMaterialHook *hook = inMat->getHook<ImposterCaptureMaterialHook>();
  115. if ( !hook )
  116. {
  117. // Create a hook and initialize it using the incoming material.
  118. hook = new ImposterCaptureMaterialHook;
  119. hook->init( inMat );
  120. inMat->addHook( hook );
  121. }
  122. return hook;
  123. }
  124. ImposterCapture::ImposterCapture()
  125. : mShapeInstance( NULL ),
  126. mDl( 0 ),
  127. mDim( 0 ),
  128. mRadius( 0.0f ),
  129. mCenter( Point3F( 0, 0, 0 ) ),
  130. mRenderPass( NULL ),
  131. mMeshRenderBin( NULL ),
  132. mBlackBmp( NULL ),
  133. mWhiteBmp( NULL ),
  134. mState( NULL ),
  135. mRenderTarget( NULL )
  136. {
  137. }
  138. ImposterCapture::~ImposterCapture()
  139. {
  140. AssertFatal( !mShapeInstance, "ImposterCapture destructor - TSShapeInstance hasn't been cleared!" );
  141. }
  142. void ImposterCapture::_colorAverageFilter( U32 dimensions, const U8 *inBmpBits, U8 *outBmpBits )
  143. {
  144. ColorF color;
  145. U32 count = 0;
  146. U32 index, index2;
  147. for ( S32 y = 0; y < dimensions; y++ )
  148. {
  149. for( S32 x = 0; x < dimensions; x++ )
  150. {
  151. // We only blend on transparent pixels.
  152. index = ( ( y * dimensions ) + x ) * 4;
  153. if ( inBmpBits[index+3] > 84 )
  154. {
  155. outBmpBits[index+0] = inBmpBits[index+0];
  156. outBmpBits[index+1] = inBmpBits[index+1];
  157. outBmpBits[index+2] = inBmpBits[index+2];
  158. outBmpBits[index+3] = inBmpBits[index+3]; //hack
  159. continue;
  160. }
  161. color.set(0,0,0);
  162. count = 0;
  163. for ( S32 fy = y-6; fy <= y+6; fy++ )
  164. {
  165. for ( S32 fx = x-6; fx <= x+6; fx++ )
  166. {
  167. if ( fy >= 0 && fy < (dimensions-1) &&
  168. fx >= 0 && fx < (dimensions-1) )
  169. {
  170. index2 = ( ( fy * dimensions ) + fx ) * 4;
  171. if ( inBmpBits[index2+3] > 84 )
  172. {
  173. color.red += inBmpBits[index2+0];
  174. color.green += inBmpBits[index2+1];
  175. color.blue += inBmpBits[index2+2];
  176. ++count;
  177. }
  178. }
  179. }
  180. }
  181. outBmpBits[index+0] = (U8)( (F32)color.red / (F32)count );
  182. outBmpBits[index+1] = (U8)( (F32)color.green / (F32)count );
  183. outBmpBits[index+2] = (U8)( (F32)color.blue / (F32)count );
  184. outBmpBits[index+3] = 0;
  185. }
  186. }
  187. }
  188. void ImposterCapture::_renderToTexture( GFXTexHandle texHandle, GBitmap *outBitmap, const ColorI &color )
  189. {
  190. GFXDEBUGEVENT_SCOPE( ImposterCapture_RenderToTexture, ColorI::RED );
  191. PROFILE_SCOPE( ImposterCapture_RenderToTexture );
  192. mRenderTarget->attachTexture( GFXTextureTarget::Color0, texHandle );
  193. mRenderTarget->attachTexture( GFXTextureTarget::DepthStencil, GFXTextureTarget::sDefaultDepthStencil );
  194. GFX->setActiveRenderTarget( mRenderTarget );
  195. GFX->clear( GFXClearZBuffer | GFXClearStencil | GFXClearTarget, color, 1.0f, 0 );
  196. mShapeInstance->render( mRData, mDl, 1.0f );
  197. mState->getRenderPass()->renderPass( mState );
  198. mRenderTarget->resolve();
  199. texHandle->copyToBmp( outBitmap );
  200. }
  201. void ImposterCapture::_separateAlpha( GBitmap *imposterOut )
  202. {
  203. PROFILE_START(TSShapeInstance_snapshot_sb_separate);
  204. // TODO: Remove all this when we get rid of the 'render on black/white'.
  205. // now separate the color and alpha channels
  206. GBitmap *bmp = new GBitmap;
  207. bmp->allocateBitmap(mDim, mDim, false, GFXFormatR8G8B8A8);
  208. U8 * wbmp = (U8*)mWhiteBmp->getBits(0);
  209. U8 * bbmp = (U8*)mBlackBmp->getBits(0);
  210. U8 * dst = (U8*)bmp->getBits(0);
  211. const U32 pixCount = mDim * mDim;
  212. // simpler, probably faster...
  213. for ( U32 i=0; i < pixCount; i++ )
  214. {
  215. // Shape on black background is alpha * color, shape on white
  216. // background is alpha * color + (1-alpha) * 255 we want 255 *
  217. // alpha, or 255 - (white - black).
  218. //
  219. // JMQ: or more verbosely:
  220. // cB = alpha * color + (0 * (1 - alpha))
  221. // cB = alpha * color
  222. // cW = alpha * color + (255 * (1 - alpha))
  223. // cW = cB + (255 * (1 - alpha))
  224. // solving for alpha
  225. // cW - cB = 255 * (1 - alpha)
  226. // (cW - cB)/255 = (1 - alpha)
  227. // alpha = 1 - (cW - cB)/255
  228. // since we want alpha*255, multiply through by 255
  229. // alpha * 255 = 255 - cW - cB
  230. U32 alpha = 255 - (wbmp[i*3+0] - bbmp[i*3+0]);
  231. alpha += 255 - (wbmp[i*3+1] - bbmp[i*3+1]);
  232. alpha += 255 - (wbmp[i*3+2] - bbmp[i*3+2]);
  233. if ( alpha != 0 )
  234. {
  235. F32 floatAlpha = ((F32)alpha)/(3.0f*255.0f);
  236. dst[i*4+0] = (U8)(bbmp[i*3+0] / floatAlpha);
  237. dst[i*4+1] = (U8)(bbmp[i*3+1] / floatAlpha);
  238. dst[i*4+2] = (U8)(bbmp[i*3+2] / floatAlpha);
  239. // Before we assign the alpha we "fizzle" the value
  240. // if its greater than 84. This causes the imposter
  241. // to dissolve instead of popping into view.
  242. alpha /= 3;
  243. dst[i*4+3] = (U8)alpha;
  244. }
  245. else
  246. {
  247. dst[i*4+0] = dst[i*4+1] = dst[i*4+2] = dst[i*4+3] = 0;
  248. }
  249. }
  250. PROFILE_END(); // TSShapeInstance_snapshot_sb_separate
  251. PROFILE_START(TSShapeInstance_snapshot_sb_filter);
  252. // We now run a special kernel filter over the image that
  253. // averages color into the transparent areas. This should
  254. // in essence give us a border around the edges of the
  255. // imposter silhouette which fixes the artifacts around the
  256. // alpha test billboards.
  257. U8* dst2 = (U8*)imposterOut->getBits(0);
  258. _colorAverageFilter( mDim, dst, dst2 );
  259. if ( 0 )
  260. {
  261. FileStream fs;
  262. if ( fs.open( "./imposterout.png", Torque::FS::File::Write ) )
  263. imposterOut->writeBitmap( "png", fs );
  264. fs.close();
  265. if ( fs.open( "./temp.png", Torque::FS::File::Write ) )
  266. bmp->writeBitmap( "png", fs );
  267. fs.close();
  268. }
  269. PROFILE_END(); // TSShapeInstance_snapshot_sb_filter
  270. delete bmp;
  271. }
  272. void ImposterCapture::_convertDXT5nm( GBitmap *normalsOut )
  273. {
  274. PROFILE_SCOPE(ImposterCapture_ConvertDXT5nm);
  275. U8 *bits = (U8*)normalsOut->getBits(0);
  276. const U32 pixCount = mDim * mDim;
  277. U8 x, y, z;
  278. // Encoding in object space DXT5 which moves
  279. // one of the coords to the alpha channel for
  280. // improved precision.... in our case z.
  281. for ( U32 i=0; i < pixCount; i++ )
  282. {
  283. x = bits[i*4+0];
  284. y = bits[i*4+1];
  285. z = bits[i*4+2];
  286. bits[i*4+0] = x;
  287. bits[i*4+1] = y;
  288. bits[i*4+2] = 0;
  289. bits[i*4+3] = z;
  290. }
  291. }
  292. void ImposterCapture::begin( TSShapeInstance *shapeInst,
  293. S32 dl,
  294. S32 dim,
  295. F32 radius,
  296. const Point3F &center )
  297. {
  298. mShapeInstance = shapeInst;
  299. mDl = dl;
  300. mDim = dim;
  301. mRadius = radius;
  302. mCenter = center;
  303. mBlackTex.set( mDim, mDim, GFXFormatR8G8B8A8, &GFXDefaultRenderTargetProfile, avar( "%s() - (line %d)", __FUNCTION__, __LINE__ ) );
  304. mWhiteTex.set( mDim, mDim, GFXFormatR8G8B8A8, &GFXDefaultRenderTargetProfile, avar( "%s() - (line %d)", __FUNCTION__, __LINE__ ) );
  305. mNormalTex.set( mDim, mDim, GFXFormatR8G8B8A8, &GFXDefaultRenderTargetProfile, avar( "%s() - (line %d)", __FUNCTION__, __LINE__ ) );
  306. // copy the black render target data into a bitmap
  307. mBlackBmp = new GBitmap;
  308. mBlackBmp->allocateBitmap(mDim, mDim, false, GFXFormatR8G8B8);
  309. // copy the white target data into a bitmap
  310. mWhiteBmp = new GBitmap;
  311. mWhiteBmp->allocateBitmap(mDim, mDim, false, GFXFormatR8G8B8);
  312. // Setup viewport and frustrum to do orthographic projection.
  313. RectI viewport( 0, 0, mDim, mDim );
  314. GFX->setViewport( viewport );
  315. GFX->setOrtho( -mRadius, mRadius, -mRadius, mRadius, 1, 20.0f * mRadius );
  316. // Position camera looking out the X axis.
  317. MatrixF cameraMatrix( true );
  318. cameraMatrix.setColumn( 0, Point3F( 0, 0, 1 ) );
  319. cameraMatrix.setColumn( 1, Point3F( 1, 0, 0 ) );
  320. cameraMatrix.setColumn( 2, Point3F( 0, 1, 0 ) );
  321. // setup scene state required for TS mesh render...this is messy and inefficient;
  322. // should have a mode where most of this is done just once (and then
  323. // only the camera matrix changes between snapshots).
  324. // note that we use getFrustum here, but we set up an ortho projection above.
  325. // it doesn't seem like the scene state object pays attention to whether the projection is
  326. // ortho or not. this could become a problem if some code downstream tries to
  327. // reconstruct the projection matrix using the dimensions and doesn't
  328. // realize it should be ortho. at the moment no code is doing that.
  329. F32 left, right, top, bottom, nearPlane, farPlane;
  330. bool isOrtho;
  331. GFX->getFrustum( &left, &right, &bottom, &top, &nearPlane, &farPlane, &isOrtho );
  332. Frustum frust( isOrtho, left, right, top, bottom, nearPlane, farPlane, cameraMatrix );
  333. // Set up render pass.
  334. mRenderPass = new RenderPassManager();
  335. mRenderPass->assignName( "DiffuseRenderPass" );
  336. mMeshRenderBin = new RenderMeshMgr();
  337. mRenderPass->addManager( mMeshRenderBin );
  338. // Set up scene state.
  339. mState = new SceneRenderState(
  340. gClientSceneGraph,
  341. SPT_Diffuse,
  342. SceneCameraState( viewport, frust, GFX->getWorldMatrix(),GFX->getProjectionMatrix() ),
  343. mRenderPass,
  344. false
  345. );
  346. // Set up our TS render state.
  347. mRData.setSceneState( mState );
  348. mRData.setCubemap( NULL );
  349. mRData.setFadeOverride( 1.0f );
  350. // set gfx up for render to texture
  351. GFX->pushActiveRenderTarget();
  352. mRenderTarget = GFX->allocRenderToTextureTarget();
  353. }
  354. void ImposterCapture::capture( const MatrixF &rotMatrix,
  355. GBitmap **imposterOut,
  356. GBitmap **normalMapOut )
  357. {
  358. GFXTransformSaver saver;
  359. // this version of the snapshot function renders the shape to a black texture, then to white, then reads bitmaps
  360. // back for both renders and combines them, restoring the alpha and color values. this is based on the
  361. // TGE implementation. it is not fast due to the copy and software combination operations. the generated bitmaps
  362. // are upside-down (which is how TGE generated them...)
  363. (*imposterOut) = new GBitmap( mDim, mDim, false, GFXFormatR8G8B8A8 );
  364. (*normalMapOut) = new GBitmap( mDim, mDim, false, GFXFormatR8G8B8A8 );
  365. // The object to world transform.
  366. MatrixF centerMat( true );
  367. centerMat.setPosition( -mCenter );
  368. MatrixF objMatrix( rotMatrix );
  369. objMatrix.mul( centerMat );
  370. GFX->setWorldMatrix( objMatrix );
  371. // The view transform.
  372. MatrixF view( EulerF( M_PI_F / 2.0f, 0, M_PI_F ), Point3F( 0, 0, -10.0f * mRadius ) );
  373. mRenderPass->assignSharedXform( RenderPassManager::View, view );
  374. mRenderPass->assignSharedXform( RenderPassManager::Projection, GFX->getProjectionMatrix() );
  375. // Render the diffuse pass.
  376. mRenderPass->clear();
  377. mMeshRenderBin->getMatOverrideDelegate().bind( ImposterCaptureMaterialHook::getDiffuseInst );
  378. _renderToTexture( mBlackTex, mBlackBmp, ColorI(0, 0, 0, 0) );
  379. _renderToTexture( mWhiteTex, mWhiteBmp, ColorI(255, 255, 255, 255) );
  380. // Now render the normals.
  381. mRenderPass->clear();
  382. mMeshRenderBin->getMatOverrideDelegate().bind( ImposterCaptureMaterialHook::getNormalsInst );
  383. _renderToTexture( mNormalTex, *normalMapOut, ColorI(0, 0, 0, 0) );
  384. _separateAlpha( *imposterOut );
  385. _convertDXT5nm( *normalMapOut );
  386. if ( 0 )
  387. {
  388. // Render out the bitmaps for debug purposes.
  389. FileStream fs;
  390. if ( fs.open( "./blackbmp.png", Torque::FS::File::Write ) )
  391. mBlackBmp->writeBitmap( "png", fs );
  392. fs.close();
  393. if ( fs.open( "./whitebmp.png", Torque::FS::File::Write ) )
  394. mWhiteBmp->writeBitmap( "png", fs );
  395. fs.close();
  396. if ( fs.open( "./normalbmp.png", Torque::FS::File::Write ) )
  397. (*normalMapOut)->writeBitmap( "png", fs );
  398. fs.close();
  399. if ( fs.open( "./finalimposter.png", Torque::FS::File::Write ) )
  400. (*imposterOut)->writeBitmap( "png", fs );
  401. fs.close();
  402. }
  403. }
  404. void ImposterCapture::end()
  405. {
  406. GFX->popActiveRenderTarget();
  407. mBlackTex.free();
  408. mWhiteTex.free();
  409. mNormalTex.free();
  410. mShapeInstance = NULL;
  411. mRenderTarget = NULL;
  412. mMeshRenderBin = NULL; // Deleted by mRenderPass
  413. SAFE_DELETE( mState );
  414. SAFE_DELETE( mRenderPass );
  415. SAFE_DELETE( mBlackBmp );
  416. SAFE_DELETE( mWhiteBmp );
  417. }