reflectionManager.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 "scene/reflectionManager.h"
  24. #include "platform/profiler.h"
  25. #include "platform/platformTimer.h"
  26. #include "console/consoleTypes.h"
  27. #include "core/tAlgorithm.h"
  28. #include "math/mMathFn.h"
  29. #include "T3D/gameBase/gameConnection.h"
  30. #include "ts/tsShapeInstance.h"
  31. #include "gui/3d/guiTSControl.h"
  32. #include "scene/sceneManager.h"
  33. #include "gfx/gfxDebugEvent.h"
  34. #include "gfx/gfxStringEnumTranslate.h"
  35. #include "gfx/screenshot.h"
  36. #include "core/module.h"
  37. #include "scene/reflectionMatHook.h"
  38. #include "console/engineAPI.h"
  39. MODULE_BEGIN( ReflectionManager )
  40. MODULE_INIT
  41. {
  42. ManagedSingleton< ReflectionManager >::createSingleton();
  43. ReflectionManager::initConsole();
  44. }
  45. MODULE_SHUTDOWN
  46. {
  47. ManagedSingleton< ReflectionManager >::deleteSingleton();
  48. }
  49. MODULE_END;
  50. GFX_ImplementTextureProfile( ReflectRenderTargetProfile,
  51. GFXTextureProfile::DiffuseMap,
  52. GFXTextureProfile::PreserveSize | GFXTextureProfile::NoMipmap | GFXTextureProfile::RenderTarget | GFXTextureProfile::Pooled,
  53. GFXTextureProfile::NONE );
  54. GFX_ImplementTextureProfile( RefractTextureProfile,
  55. GFXTextureProfile::DiffuseMap,
  56. GFXTextureProfile::PreserveSize |
  57. GFXTextureProfile::RenderTarget |
  58. GFXTextureProfile::Pooled,
  59. GFXTextureProfile::NONE );
  60. static S32 QSORT_CALLBACK compareReflectors( const void *a, const void *b )
  61. {
  62. const ReflectorBase *A = *((ReflectorBase**)a);
  63. const ReflectorBase *B = *((ReflectorBase**)b);
  64. F32 dif = B->score - A->score;
  65. return (S32)mFloor( dif );
  66. }
  67. U32 ReflectionManager::smFrameReflectionMS = 10;
  68. F32 ReflectionManager::smRefractTexScale = 0.5f;
  69. ReflectionManager::ReflectionManager()
  70. : mUpdateRefract( true ),
  71. mReflectFormat( GFXFormatR8G8B8A8 ),
  72. mLastUpdateMs( 0 )
  73. {
  74. mTimer = PlatformTimer::create();
  75. GFXDevice::getDeviceEventSignal().notify( this, &ReflectionManager::_handleDeviceEvent );
  76. }
  77. void ReflectionManager::initConsole()
  78. {
  79. Con::addVariable( "$pref::Reflect::refractTexScale", TypeF32, &ReflectionManager::smRefractTexScale, "RefractTex has dimensions equal to the active render target scaled in both x and y by this float.\n"
  80. "@ingroup Rendering");
  81. Con::addVariable( "$pref::Reflect::frameLimitMS", TypeS32, &ReflectionManager::smFrameReflectionMS, "ReflectionManager tries not to spend more than this amount of time updating reflections per frame.\n"
  82. "@ingroup Rendering");
  83. }
  84. ReflectionManager::~ReflectionManager()
  85. {
  86. SAFE_DELETE( mTimer );
  87. AssertFatal( mReflectors.size() == 0, "ReflectionManager, some reflectors were left nregistered!" );
  88. GFXDevice::getDeviceEventSignal().remove( this, &ReflectionManager::_handleDeviceEvent );
  89. }
  90. void ReflectionManager::registerReflector( ReflectorBase *reflector )
  91. {
  92. mReflectors.push_back_unique( reflector );
  93. }
  94. void ReflectionManager::unregisterReflector( ReflectorBase *reflector )
  95. {
  96. mReflectors.remove( reflector );
  97. }
  98. void ReflectionManager::update( F32 timeSlice,
  99. const Point2I &resolution,
  100. const CameraQuery &query )
  101. {
  102. GFXDEBUGEVENT_SCOPE( UpdateReflections, ColorI::WHITE );
  103. if ( mReflectors.empty() )
  104. return;
  105. PROFILE_SCOPE( ReflectionManager_Update );
  106. // Calculate our target time from the slice.
  107. U32 targetMs = timeSlice * smFrameReflectionMS;
  108. // Setup a culler for testing the
  109. // visibility of reflectors.
  110. Frustum culler;
  111. culler.set( false,
  112. query.fov,
  113. (F32)resolution.x / (F32)resolution.y,
  114. query.nearPlane,
  115. query.farPlane,
  116. query.cameraMatrix );
  117. // Manipulate the frustum for tiled screenshots
  118. const bool screenShotMode = gScreenShot && gScreenShot->isPending();
  119. if ( screenShotMode )
  120. gScreenShot->tileFrustum( culler );
  121. // We use the frame time and not real time
  122. // here as this may be called multiple times
  123. // within a frame.
  124. U32 startOfUpdateMs = Platform::getVirtualMilliseconds();
  125. // Save this for interested parties.
  126. mLastUpdateMs = startOfUpdateMs;
  127. ReflectParams refparams;
  128. refparams.query = &query;
  129. refparams.viewportExtent = resolution;
  130. refparams.culler = culler;
  131. refparams.startOfUpdateMs = startOfUpdateMs;
  132. // Update the reflection score.
  133. ReflectorList::iterator reflectorIter = mReflectors.begin();
  134. for ( ; reflectorIter != mReflectors.end(); reflectorIter++ )
  135. (*reflectorIter)->calcScore( refparams );
  136. // Sort them by the score.
  137. dQsort( mReflectors.address(), mReflectors.size(), sizeof(ReflectorBase*), compareReflectors );
  138. // Update as many reflections as we can
  139. // within the target time limit.
  140. mTimer->getElapsedMs();
  141. mTimer->reset();
  142. U32 numUpdated = 0;
  143. reflectorIter = mReflectors.begin();
  144. for ( ; reflectorIter != mReflectors.end(); reflectorIter++ )
  145. {
  146. // We're sorted by score... so once we reach
  147. // a zero score we have nothing more to update.
  148. if ( (*reflectorIter)->score <= 0.0f && !screenShotMode )
  149. break;
  150. (*reflectorIter)->updateReflection( refparams );
  151. (*reflectorIter)->lastUpdateMs = startOfUpdateMs;
  152. numUpdated++;
  153. // If we run out of update time then stop.
  154. if ( mTimer->getElapsedMs() > targetMs && !screenShotMode && (*reflectorIter)->score < 1000.0f )
  155. break;
  156. }
  157. // Set metric/debug related script variables...
  158. U32 numVisible = 0;
  159. U32 numOccluded = 0;
  160. reflectorIter = mReflectors.begin();
  161. for ( ; reflectorIter != mReflectors.end(); reflectorIter++ )
  162. {
  163. ReflectorBase *pReflector = (*reflectorIter);
  164. if ( pReflector->isOccluded() )
  165. numOccluded++;
  166. else
  167. numVisible++;
  168. }
  169. #ifdef TORQUE_GATHER_METRICS
  170. U32 numEnabled = mReflectors.size();
  171. U32 totalElapsed = mTimer->getElapsedMs();
  172. const GFXTextureProfileStats &stats = ReflectRenderTargetProfile.getStats();
  173. F32 mb = ( stats.activeBytes / 1024.0f ) / 1024.0f;
  174. char temp[256];
  175. dSprintf( temp, 256, "%s %d %0.2f\n",
  176. ReflectRenderTargetProfile.getName().c_str(),
  177. stats.activeCount,
  178. mb );
  179. Con::setVariable( "$Reflect::textureStats", temp );
  180. Con::setIntVariable( "$Reflect::renderTargetsAllocated", stats.allocatedTextures );
  181. Con::setIntVariable( "$Reflect::poolSize", stats.activeCount );
  182. Con::setIntVariable( "$Reflect::numObjects", numEnabled );
  183. Con::setIntVariable( "$Reflect::numVisible", numVisible );
  184. Con::setIntVariable( "$Reflect::numOccluded", numOccluded );
  185. Con::setIntVariable( "$Reflect::numUpdated", numUpdated );
  186. Con::setIntVariable( "$Reflect::elapsed", totalElapsed );
  187. #endif
  188. }
  189. GFXTexHandle ReflectionManager::allocRenderTarget( const Point2I &size )
  190. {
  191. return GFXTexHandle( size.x, size.y, mReflectFormat,
  192. &ReflectRenderTargetProfile,
  193. avar("%s() - mReflectTex (line %d)", __FUNCTION__, __LINE__) );
  194. }
  195. GFXTextureObject* ReflectionManager::getRefractTex( bool forceUpdate )
  196. {
  197. GFXTarget *target = GFX->getActiveRenderTarget();
  198. GFXFormat targetFormat = target->getFormat();
  199. const Point2I &targetSize = target->getSize();
  200. #if defined(TORQUE_OS_XENON)
  201. // On the Xbox360, it needs to do a resolveTo from the active target, so this
  202. // may as well be the full size of the active target
  203. const U32 desWidth = targetSize.x;
  204. const U32 desHeight = targetSize.y;
  205. #else
  206. const U32 desWidth = mFloor( (F32)targetSize.x * smRefractTexScale );
  207. const U32 desHeight = mFloor( ( F32)targetSize.y * smRefractTexScale );
  208. #endif
  209. if ( mRefractTex.isNull() ||
  210. mRefractTex->getWidth() != desWidth ||
  211. mRefractTex->getHeight() != desHeight ||
  212. mRefractTex->getFormat() != targetFormat )
  213. {
  214. mRefractTex.set( desWidth, desHeight, targetFormat, &RefractTextureProfile, "mRefractTex" );
  215. mUpdateRefract = true;
  216. }
  217. if ( forceUpdate || mUpdateRefract )
  218. {
  219. target->resolveTo( mRefractTex );
  220. mUpdateRefract = false;
  221. }
  222. return mRefractTex;
  223. }
  224. BaseMatInstance* ReflectionManager::getReflectionMaterial( BaseMatInstance *inMat ) const
  225. {
  226. // See if we have an existing material hook.
  227. ReflectionMaterialHook *hook = static_cast<ReflectionMaterialHook*>( inMat->getHook( ReflectionMaterialHook::Type ) );
  228. if ( !hook )
  229. {
  230. // Create a hook and initialize it using the incoming material.
  231. hook = new ReflectionMaterialHook;
  232. hook->init( inMat );
  233. inMat->addHook( hook );
  234. }
  235. return hook->getReflectMat();
  236. }
  237. bool ReflectionManager::_handleDeviceEvent( GFXDevice::GFXDeviceEventType evt )
  238. {
  239. switch( evt )
  240. {
  241. case GFXDevice::deStartOfFrame:
  242. case GFXDevice::deStartOfField:
  243. mUpdateRefract = true;
  244. break;
  245. case GFXDevice::deDestroy:
  246. mRefractTex = NULL;
  247. break;
  248. default:
  249. break;
  250. }
  251. return true;
  252. }
  253. DefineEngineFunction( setReflectFormat, void, ( GFXFormat format ),,
  254. "Set the reflection texture format.\n"
  255. "@ingroup GFX\n" )
  256. {
  257. REFLECTMGR->setReflectFormat( format );
  258. }