reflectionManager.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. // jamesu - normally we just need a frustum which covers the current ports, however for SBS mode
  113. // we need something which covers both viewports.
  114. S32 stereoTarget = GFX->getCurrentStereoTarget();
  115. if (stereoTarget != -1)
  116. {
  117. // In this case we're rendering in stereo using a specific eye
  118. MathUtils::makeFovPortFrustum(&culler, false, query.nearPlane, query.farPlane, query.fovPort[stereoTarget], query.headMatrix);
  119. }
  120. else if (GFX->getCurrentRenderStyle() == GFXDevice::RS_StereoSideBySide)
  121. {
  122. // Calculate an ideal culling size here, we'll just assume double fov based on the first fovport based on
  123. // the head position.
  124. FovPort port = query.fovPort[0];
  125. F32 upSize = query.nearPlane * port.upTan;
  126. F32 downSize = query.nearPlane * port.downTan;
  127. F32 top = upSize;
  128. F32 bottom = -downSize;
  129. F32 fovInRadians = mAtan2((top - bottom) / 2.0f, query.nearPlane) * 3.0f;
  130. culler.set(false,
  131. fovInRadians,
  132. (F32)(query.stereoViewports[0].extent.x + query.stereoViewports[1].extent.x) / (F32)query.stereoViewports[0].extent.y,
  133. query.nearPlane,
  134. query.farPlane,
  135. query.headMatrix);
  136. }
  137. else
  138. {
  139. // Normal culling
  140. culler.set(false,
  141. query.fov,
  142. (F32)resolution.x / (F32)resolution.y,
  143. query.nearPlane,
  144. query.farPlane,
  145. query.cameraMatrix);
  146. }
  147. // Manipulate the frustum for tiled screenshots
  148. const bool screenShotMode = gScreenShot && gScreenShot->isPending();
  149. if ( screenShotMode )
  150. gScreenShot->tileFrustum( culler );
  151. // We use the frame time and not real time
  152. // here as this may be called multiple times
  153. // within a frame.
  154. U32 startOfUpdateMs = Platform::getVirtualMilliseconds();
  155. // Save this for interested parties.
  156. mLastUpdateMs = startOfUpdateMs;
  157. ReflectParams refparams;
  158. refparams.query = &query;
  159. refparams.viewportExtent = resolution;
  160. refparams.culler = culler;
  161. refparams.startOfUpdateMs = startOfUpdateMs;
  162. refparams.eyeId = stereoTarget;
  163. // Update the reflection score.
  164. ReflectorList::iterator reflectorIter = mReflectors.begin();
  165. for ( ; reflectorIter != mReflectors.end(); reflectorIter++ )
  166. (*reflectorIter)->calcScore( refparams );
  167. // Sort them by the score.
  168. dQsort( mReflectors.address(), mReflectors.size(), sizeof(ReflectorBase*), compareReflectors );
  169. // Update as many reflections as we can
  170. // within the target time limit.
  171. mTimer->getElapsedMs();
  172. mTimer->reset();
  173. U32 numUpdated = 0;
  174. reflectorIter = mReflectors.begin();
  175. for ( ; reflectorIter != mReflectors.end(); reflectorIter++ )
  176. {
  177. // We're sorted by score... so once we reach
  178. // a zero score we have nothing more to update.
  179. if ( (*reflectorIter)->score <= 0.0f && !screenShotMode )
  180. break;
  181. (*reflectorIter)->updateReflection( refparams );
  182. if (stereoTarget != 0) // only update MS if we're not rendering the left eye in separate mode
  183. {
  184. (*reflectorIter)->lastUpdateMs = startOfUpdateMs;
  185. }
  186. numUpdated++;
  187. // If we run out of update time then stop.
  188. if ( mTimer->getElapsedMs() > targetMs && !screenShotMode && (*reflectorIter)->score < 1000.0f )
  189. break;
  190. }
  191. // Set metric/debug related script variables...
  192. U32 numVisible = 0;
  193. U32 numOccluded = 0;
  194. reflectorIter = mReflectors.begin();
  195. for ( ; reflectorIter != mReflectors.end(); reflectorIter++ )
  196. {
  197. ReflectorBase *pReflector = (*reflectorIter);
  198. if ( pReflector->isOccluded() )
  199. numOccluded++;
  200. else
  201. numVisible++;
  202. }
  203. #ifdef TORQUE_GATHER_METRICS
  204. U32 numEnabled = mReflectors.size();
  205. U32 totalElapsed = mTimer->getElapsedMs();
  206. const GFXTextureProfileStats &stats = ReflectRenderTargetProfile.getStats();
  207. F32 mb = ( stats.activeBytes / 1024.0f ) / 1024.0f;
  208. char temp[256];
  209. dSprintf( temp, 256, "%s %d %0.2f\n",
  210. ReflectRenderTargetProfile.getName().c_str(),
  211. stats.activeCount,
  212. mb );
  213. Con::setVariable( "$Reflect::textureStats", temp );
  214. Con::setIntVariable( "$Reflect::renderTargetsAllocated", stats.allocatedTextures );
  215. Con::setIntVariable( "$Reflect::poolSize", stats.activeCount );
  216. Con::setIntVariable( "$Reflect::numObjects", numEnabled );
  217. Con::setIntVariable( "$Reflect::numVisible", numVisible );
  218. Con::setIntVariable( "$Reflect::numOccluded", numOccluded );
  219. Con::setIntVariable( "$Reflect::numUpdated", numUpdated );
  220. Con::setIntVariable( "$Reflect::elapsed", totalElapsed );
  221. #endif
  222. }
  223. GFXTexHandle ReflectionManager::allocRenderTarget( const Point2I &size )
  224. {
  225. return GFXTexHandle( size.x, size.y, mReflectFormat,
  226. &ReflectRenderTargetProfile,
  227. avar("%s() - mReflectTex (line %d)", __FUNCTION__, __LINE__) );
  228. }
  229. GFXTextureObject* ReflectionManager::getRefractTex( bool forceUpdate )
  230. {
  231. GFXTarget *target = GFX->getActiveRenderTarget();
  232. GFXFormat targetFormat = target->getFormat();
  233. const Point2I &targetSize = target->getSize();
  234. #if defined(TORQUE_OS_XENON)
  235. // On the Xbox360, it needs to do a resolveTo from the active target, so this
  236. // may as well be the full size of the active target
  237. const U32 desWidth = targetSize.x;
  238. const U32 desHeight = targetSize.y;
  239. #else
  240. U32 desWidth, desHeight;
  241. // D3D11 needs to be the same size as the active target
  242. if (GFX->getAdapterType() == Direct3D11)
  243. {
  244. desWidth = targetSize.x;
  245. desHeight = targetSize.y;
  246. }
  247. else
  248. {
  249. desWidth = mFloor((F32)targetSize.x * smRefractTexScale);
  250. desHeight = mFloor((F32)targetSize.y * smRefractTexScale);
  251. }
  252. #endif
  253. if ( mRefractTex.isNull() ||
  254. mRefractTex->getWidth() != desWidth ||
  255. mRefractTex->getHeight() != desHeight ||
  256. mRefractTex->getFormat() != targetFormat )
  257. {
  258. mRefractTex.set( desWidth, desHeight, targetFormat, &RefractTextureProfile, "mRefractTex" );
  259. mUpdateRefract = true;
  260. }
  261. if ( forceUpdate || mUpdateRefract )
  262. {
  263. target->resolveTo( mRefractTex );
  264. mUpdateRefract = false;
  265. }
  266. return mRefractTex;
  267. }
  268. BaseMatInstance* ReflectionManager::getReflectionMaterial( BaseMatInstance *inMat ) const
  269. {
  270. // See if we have an existing material hook.
  271. ReflectionMaterialHook *hook = static_cast<ReflectionMaterialHook*>( inMat->getHook( ReflectionMaterialHook::Type ) );
  272. if ( !hook )
  273. {
  274. // Create a hook and initialize it using the incoming material.
  275. hook = new ReflectionMaterialHook;
  276. hook->init( inMat );
  277. inMat->addHook( hook );
  278. }
  279. return hook->getReflectMat();
  280. }
  281. bool ReflectionManager::_handleDeviceEvent( GFXDevice::GFXDeviceEventType evt )
  282. {
  283. switch( evt )
  284. {
  285. case GFXDevice::deStartOfFrame:
  286. case GFXDevice::deStartOfField:
  287. mUpdateRefract = true;
  288. break;
  289. case GFXDevice::deDestroy:
  290. mRefractTex = NULL;
  291. break;
  292. default:
  293. break;
  294. }
  295. return true;
  296. }
  297. DefineEngineFunction( setReflectFormat, void, ( GFXFormat format ),,
  298. "Set the reflection texture format.\n"
  299. "@ingroup GFX\n" )
  300. {
  301. REFLECTMGR->setReflectFormat( format );
  302. }