reflectionManager.cpp 11 KB

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