2
0

CmRenderSystem.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org/
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. // RenderSystem implementation
  25. // Note that most of this class is abstract since
  26. // we cannot know how to implement the behaviour without
  27. // being aware of the 3D API. However there are a few
  28. // simple functions which can have a base implementation
  29. #include "CmRenderSystem.h"
  30. #include "CmViewport.h"
  31. #include "CmException.h"
  32. #include "CmRenderTarget.h"
  33. #include "CmRenderWindow.h"
  34. #include "CmHardwarePixelBuffer.h"
  35. #include "CmHardwareOcclusionQuery.h"
  36. #include "CmCommandQueue.h"
  37. #include "CmDeferredRenderContext.h"
  38. #include "boost/bind.hpp"
  39. #if CM_DEBUG_MODE
  40. #define THROW_IF_NOT_RENDER_THREAD throwIfNotRenderThread();
  41. #else
  42. #define THROW_IF_NOT_RENDER_THREAD
  43. #endif
  44. namespace CamelotEngine {
  45. static const TexturePtr sNullTexPtr;
  46. //-----------------------------------------------------------------------
  47. RenderSystem::RenderSystem()
  48. : mActiveRenderTarget(0)
  49. , mCullingMode(CULL_CLOCKWISE)
  50. , mVsync(false)
  51. , mVSyncInterval(1)
  52. , mInvertVertexWinding(false)
  53. , mDisabledTexUnitsFrom(0)
  54. , mVertexProgramBound(false)
  55. , mGeometryProgramBound(false)
  56. , mFragmentProgramBound(false)
  57. , mClipPlanesDirty(true)
  58. , mCurrentCapabilities(nullptr)
  59. , mRenderThreadFunc(nullptr)
  60. , mRenderThreadShutdown(false)
  61. , mCommandQueue(nullptr)
  62. , mMaxCommandNotifyId(0)
  63. {
  64. }
  65. //-----------------------------------------------------------------------
  66. RenderSystem::~RenderSystem()
  67. {
  68. shutdown_internal();
  69. delete mCurrentCapabilities;
  70. mCurrentCapabilities = 0;
  71. }
  72. //-----------------------------------------------------------------------
  73. void RenderSystem::startUp()
  74. {
  75. mRenderThreadId = CM_THREAD_CURRENT_ID;
  76. mCommandQueue = new CommandQueue(CM_THREAD_CURRENT_ID);
  77. initRenderThread();
  78. queueCommand(boost::bind(&RenderSystem::startUp_internal, this));
  79. }
  80. //-----------------------------------------------------------------------
  81. void RenderSystem::startUp_internal()
  82. {
  83. THROW_IF_NOT_RENDER_THREAD;
  84. mVertexProgramBound = false;
  85. mGeometryProgramBound = false;
  86. mFragmentProgramBound = false;
  87. }
  88. //-----------------------------------------------------------------------
  89. void RenderSystem::shutdown(void)
  90. {
  91. queueCommand(boost::bind(&RenderSystem::shutdown_internal, this), true);
  92. // TODO - What if something gets queued between these two calls?
  93. shutdownRenderThread();
  94. }
  95. //-----------------------------------------------------------------------
  96. void RenderSystem::shutdown_internal(void)
  97. {
  98. // TODO - I should probably sync this up to make sure no other threads are doing anything while shutdown is in progress
  99. // Remove all the render targets.
  100. // (destroy primary target last since others may depend on it)
  101. RenderTarget* primary = 0;
  102. for (auto it = mRenderTargets.begin(); it != mRenderTargets.end(); ++it)
  103. {
  104. if (!primary && (*it)->isPrimary())
  105. primary = *it;
  106. else
  107. delete *it;
  108. }
  109. delete primary;
  110. mRenderTargets.clear();
  111. mPrioritisedRenderTargets.clear();
  112. if(mCommandQueue != nullptr)
  113. {
  114. delete mCommandQueue;
  115. mCommandQueue = nullptr;
  116. }
  117. }
  118. //-----------------------------------------------------------------------
  119. void RenderSystem::swapAllRenderTargetBuffers(bool waitForVSync)
  120. {
  121. THROW_IF_NOT_RENDER_THREAD;
  122. // Update all in order of priority
  123. // This ensures render-to-texture targets get updated before render windows
  124. RenderTargetPriorityMap::iterator itarg, itargend;
  125. itargend = mPrioritisedRenderTargets.end();
  126. for( itarg = mPrioritisedRenderTargets.begin(); itarg != itargend; ++itarg )
  127. {
  128. if( itarg->second->isActive())
  129. itarg->second->swapBuffers(waitForVSync);
  130. }
  131. }
  132. //---------------------------------------------------------------------------------------------
  133. RenderWindow* RenderSystem::createRenderWindow(const String &name, unsigned int width, unsigned int height,
  134. bool fullScreen, const NameValuePairList *miscParams)
  135. {
  136. AsyncOp op;
  137. if(miscParams != nullptr)
  138. op = queueReturnCommand(boost::bind(&RenderSystem::createRenderWindow_internal, this, name, width, height, fullScreen, *miscParams, _1), true);
  139. else
  140. op = queueReturnCommand(boost::bind(&RenderSystem::createRenderWindow_internal, this, name, width, height, fullScreen, NameValuePairList(), _1), true);
  141. return op.getReturnValue<RenderWindow*>();
  142. }
  143. //---------------------------------------------------------------------------------------------
  144. void RenderSystem::destroyRenderWindow(RenderWindow* renderWindow)
  145. {
  146. THROW_IF_NOT_RENDER_THREAD;
  147. destroyRenderTarget(renderWindow);
  148. }
  149. //---------------------------------------------------------------------------------------------
  150. void RenderSystem::destroyRenderTexture(RenderTexture* renderTexture)
  151. {
  152. THROW_IF_NOT_RENDER_THREAD;
  153. destroyRenderTarget(renderTexture);
  154. }
  155. //---------------------------------------------------------------------------------------------
  156. void RenderSystem::destroyRenderTarget(RenderTarget* renderTarget)
  157. {
  158. THROW_IF_NOT_RENDER_THREAD;
  159. detachRenderTarget(*renderTarget);
  160. delete renderTarget;
  161. }
  162. //---------------------------------------------------------------------------------------------
  163. void RenderSystem::attachRenderTarget( RenderTarget &target )
  164. {
  165. THROW_IF_NOT_RENDER_THREAD;
  166. assert( target.getPriority() < CM_NUM_RENDERTARGET_GROUPS );
  167. mRenderTargets.push_back(&target);
  168. mPrioritisedRenderTargets.insert(
  169. RenderTargetPriorityMap::value_type(target.getPriority(), &target ));
  170. }
  171. //---------------------------------------------------------------------------------------------
  172. void RenderSystem::detachRenderTarget(RenderTarget& renderTarget)
  173. {
  174. THROW_IF_NOT_RENDER_THREAD;
  175. auto it = std::find(mRenderTargets.begin(), mRenderTargets.end(), &renderTarget);
  176. RenderTarget* foundRT = nullptr;
  177. if( it != mRenderTargets.end() )
  178. {
  179. foundRT = *it;
  180. /* Remove the render target from the priority groups. */
  181. RenderTargetPriorityMap::iterator itarg, itargend;
  182. itargend = mPrioritisedRenderTargets.end();
  183. for( itarg = mPrioritisedRenderTargets.begin(); itarg != itargend; ++itarg )
  184. {
  185. if( itarg->second == *it ) {
  186. mPrioritisedRenderTargets.erase( itarg );
  187. break;
  188. }
  189. }
  190. mRenderTargets.erase( it );
  191. }
  192. /// If detached render target is the active render target, reset active render target
  193. if(foundRT == mActiveRenderTarget)
  194. mActiveRenderTarget = 0;
  195. }
  196. //---------------------------------------------------------------------------------------------
  197. const RenderSystemCapabilities* RenderSystem::getCapabilities(void) const
  198. {
  199. THROW_IF_NOT_RENDER_THREAD;
  200. return mCurrentCapabilities;
  201. }
  202. //---------------------------------------------------------------------------------------------
  203. const DriverVersion& RenderSystem::getDriverVersion(void) const
  204. {
  205. THROW_IF_NOT_RENDER_THREAD;
  206. return mDriverVersion;
  207. }
  208. //-----------------------------------------------------------------------
  209. Viewport RenderSystem::getViewport(void)
  210. {
  211. THROW_IF_NOT_RENDER_THREAD;
  212. return mActiveViewport;
  213. }
  214. //-----------------------------------------------------------------------
  215. void RenderSystem::disableTextureUnit(UINT16 texUnit)
  216. {
  217. THROW_IF_NOT_RENDER_THREAD;
  218. setTexture(texUnit, false, sNullTexPtr);
  219. }
  220. //---------------------------------------------------------------------
  221. void RenderSystem::disableTextureUnitsFrom(UINT16 texUnit)
  222. {
  223. THROW_IF_NOT_RENDER_THREAD;
  224. UINT16 disableTo = CM_MAX_TEXTURE_LAYERS;
  225. if (disableTo > mDisabledTexUnitsFrom)
  226. disableTo = mDisabledTexUnitsFrom;
  227. mDisabledTexUnitsFrom = texUnit;
  228. for (UINT16 i = texUnit; i < disableTo; ++i)
  229. {
  230. disableTextureUnit(i);
  231. }
  232. }
  233. //-----------------------------------------------------------------------
  234. bool RenderSystem::getWaitForVerticalBlank(void) const
  235. {
  236. THROW_IF_NOT_RENDER_THREAD;
  237. return mVsync;
  238. }
  239. //-----------------------------------------------------------------------
  240. void RenderSystem::setWaitForVerticalBlank(bool enabled)
  241. {
  242. THROW_IF_NOT_RENDER_THREAD;
  243. mVsync = enabled;
  244. }
  245. //-----------------------------------------------------------------------
  246. void RenderSystem::setInvertVertexWinding(bool invert)
  247. {
  248. THROW_IF_NOT_RENDER_THREAD;
  249. mInvertVertexWinding = invert;
  250. }
  251. //-----------------------------------------------------------------------
  252. bool RenderSystem::getInvertVertexWinding(void) const
  253. {
  254. THROW_IF_NOT_RENDER_THREAD;
  255. return mInvertVertexWinding;
  256. }
  257. //-----------------------------------------------------------------------
  258. CullingMode RenderSystem::getCullingMode(void) const
  259. {
  260. THROW_IF_NOT_RENDER_THREAD;
  261. return mCullingMode;
  262. }
  263. //---------------------------------------------------------------------
  264. void RenderSystem::addClipPlane (const Plane &p)
  265. {
  266. THROW_IF_NOT_RENDER_THREAD;
  267. mClipPlanes.push_back(p);
  268. mClipPlanesDirty = true;
  269. }
  270. //---------------------------------------------------------------------
  271. void RenderSystem::addClipPlane (float A, float B, float C, float D)
  272. {
  273. THROW_IF_NOT_RENDER_THREAD;
  274. addClipPlane(Plane(A, B, C, D));
  275. }
  276. //---------------------------------------------------------------------
  277. void RenderSystem::setClipPlanes(const PlaneList& clipPlanes)
  278. {
  279. THROW_IF_NOT_RENDER_THREAD;
  280. if (clipPlanes != mClipPlanes)
  281. {
  282. mClipPlanes = clipPlanes;
  283. mClipPlanesDirty = true;
  284. }
  285. }
  286. //---------------------------------------------------------------------
  287. void RenderSystem::resetClipPlanes()
  288. {
  289. THROW_IF_NOT_RENDER_THREAD;
  290. if (!mClipPlanes.empty())
  291. {
  292. mClipPlanes.clear();
  293. mClipPlanesDirty = true;
  294. }
  295. }
  296. //-----------------------------------------------------------------------
  297. void RenderSystem::bindGpuProgram(GpuProgramHandle prg)
  298. {
  299. THROW_IF_NOT_RENDER_THREAD;
  300. switch(prg->getBindingDelegate_internal()->getType())
  301. {
  302. case GPT_VERTEX_PROGRAM:
  303. // mark clip planes dirty if changed (programmable can change space)
  304. if (!mVertexProgramBound && !mClipPlanes.empty())
  305. mClipPlanesDirty = true;
  306. mVertexProgramBound = true;
  307. break;
  308. case GPT_GEOMETRY_PROGRAM:
  309. mGeometryProgramBound = true;
  310. break;
  311. case GPT_FRAGMENT_PROGRAM:
  312. mFragmentProgramBound = true;
  313. break;
  314. }
  315. }
  316. //-----------------------------------------------------------------------
  317. void RenderSystem::unbindGpuProgram(GpuProgramType gptype)
  318. {
  319. THROW_IF_NOT_RENDER_THREAD;
  320. switch(gptype)
  321. {
  322. case GPT_VERTEX_PROGRAM:
  323. // mark clip planes dirty if changed (programmable can change space)
  324. if (mVertexProgramBound && !mClipPlanes.empty())
  325. mClipPlanesDirty = true;
  326. mVertexProgramBound = false;
  327. break;
  328. case GPT_GEOMETRY_PROGRAM:
  329. mGeometryProgramBound = false;
  330. break;
  331. case GPT_FRAGMENT_PROGRAM:
  332. mFragmentProgramBound = false;
  333. break;
  334. }
  335. }
  336. //-----------------------------------------------------------------------
  337. bool RenderSystem::isGpuProgramBound(GpuProgramType gptype)
  338. {
  339. THROW_IF_NOT_RENDER_THREAD;
  340. switch(gptype)
  341. {
  342. case GPT_VERTEX_PROGRAM:
  343. return mVertexProgramBound;
  344. case GPT_GEOMETRY_PROGRAM:
  345. return mGeometryProgramBound;
  346. case GPT_FRAGMENT_PROGRAM:
  347. return mFragmentProgramBound;
  348. }
  349. // Make compiler happy
  350. return false;
  351. }
  352. //-----------------------------------------------------------------------
  353. void RenderSystem::render(const RenderOperation& op)
  354. {
  355. THROW_IF_NOT_RENDER_THREAD;
  356. // sort out clip planes
  357. // have to do it here in case of matrix issues
  358. if (mClipPlanesDirty)
  359. {
  360. setClipPlanesImpl(mClipPlanes);
  361. mClipPlanesDirty = false;
  362. }
  363. }
  364. /************************************************************************/
  365. /* PRIVATE */
  366. /************************************************************************/
  367. void RenderSystem::initRenderThread()
  368. {
  369. mRenderThreadFunc = new RenderWorkerFunc(this);
  370. #if CM_THREAD_SUPPORT
  371. CM_THREAD_CREATE(t, *mRenderThreadFunc);
  372. mRenderThread = t;
  373. CM_LOCK_MUTEX_NAMED(mRenderThreadStartMutex, lock)
  374. CM_THREAD_WAIT(mRenderThreadStartCondition, mRenderThreadStartMutex, lock)
  375. #else
  376. CM_EXCEPT(InternalErrorException, "Attempting to start a render thread but Camelot isn't compiled with thread support.");
  377. #endif
  378. }
  379. void RenderSystem::runRenderThread()
  380. {
  381. mRenderThreadId = CM_THREAD_CURRENT_ID;
  382. CM_THREAD_NOTIFY_ALL(mRenderThreadStartCondition)
  383. while(true)
  384. {
  385. if(mRenderThreadShutdown)
  386. return;
  387. // Wait until we get some ready commands
  388. vector<CommandQueue::Command>::type* commands = nullptr;
  389. {
  390. CM_LOCK_MUTEX_NAMED(mCommandQueueMutex, lock)
  391. while(mCommandQueue->isEmpty())
  392. CM_THREAD_WAIT(mCommandReadyCondition, mCommandQueueMutex, lock)
  393. commands = mCommandQueue->flush();
  394. }
  395. // Play commands
  396. mCommandQueue->playback(commands, boost::bind(&RenderSystem::commandCompletedNotify, this, _1));
  397. }
  398. }
  399. void RenderSystem::shutdownRenderThread()
  400. {
  401. mRenderThreadShutdown = true;
  402. // Wake all threads. They will quit after they see the shutdown flag
  403. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition)
  404. mRenderThread->join();
  405. CM_THREAD_DESTROY(mRenderThread);
  406. mRenderThread = nullptr;
  407. mRenderThreadId = CM_THREAD_CURRENT_ID;
  408. }
  409. DeferredRenderContextPtr RenderSystem::createDeferredContext()
  410. {
  411. return DeferredRenderContextPtr(new DeferredRenderContext(this, CM_THREAD_CURRENT_ID));
  412. }
  413. AsyncOp RenderSystem::queueReturnCommand(boost::function<void(AsyncOp&)> commandCallback, bool blockUntilComplete)
  414. {
  415. #ifdef CM_DEBUG_MODE
  416. if(CM_THREAD_CURRENT_ID == getRenderThreadId())
  417. CM_EXCEPT(InternalErrorException, "You are not allowed to call this method on the render thread!");
  418. #endif
  419. AsyncOp op;
  420. UINT32 commandId = -1;
  421. {
  422. CM_LOCK_MUTEX(mCommandQueueMutex);
  423. if(blockUntilComplete)
  424. {
  425. commandId = mMaxCommandNotifyId++;
  426. op = mCommandQueue->queueReturn(commandCallback, true, commandId);
  427. }
  428. else
  429. op = mCommandQueue->queueReturn(commandCallback);
  430. }
  431. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  432. if(blockUntilComplete)
  433. blockUntilCommandCompleted(commandId);
  434. return op;
  435. }
  436. void RenderSystem::queueCommand(boost::function<void()> commandCallback, bool blockUntilComplete)
  437. {
  438. #ifdef CM_DEBUG_MODE
  439. if(CM_THREAD_CURRENT_ID == getRenderThreadId())
  440. CM_EXCEPT(InternalErrorException, "You are not allowed to call this method on the render thread!");
  441. #endif
  442. UINT32 commandId = -1;
  443. {
  444. CM_LOCK_MUTEX(mCommandQueueMutex);
  445. if(blockUntilComplete)
  446. {
  447. commandId = mMaxCommandNotifyId++;
  448. mCommandQueue->queue(commandCallback, true, commandId);
  449. }
  450. else
  451. mCommandQueue->queue(commandCallback);
  452. }
  453. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  454. if(blockUntilComplete)
  455. blockUntilCommandCompleted(commandId);
  456. }
  457. void RenderSystem::blockUntilCommandCompleted(UINT32 commandId)
  458. {
  459. CM_LOCK_MUTEX_NAMED(mCommandNotifyMutex, lock);
  460. while(true)
  461. {
  462. // Check if our command id is in the completed list
  463. auto iter = mCommandsCompleted.begin();
  464. for(; iter != mCommandsCompleted.end(); ++iter)
  465. {
  466. if(*iter == commandId)
  467. break;
  468. }
  469. if(iter != mCommandsCompleted.end())
  470. {
  471. mCommandsCompleted.erase(iter);
  472. break;
  473. }
  474. CM_THREAD_WAIT(mCommandCompleteCondition, mCommandNotifyMutex, lock);
  475. }
  476. }
  477. void RenderSystem::commandCompletedNotify(UINT32 commandId)
  478. {
  479. {
  480. CM_LOCK_MUTEX(mCommandNotifyMutex);
  481. mCommandsCompleted.push_back(commandId);
  482. }
  483. CM_THREAD_NOTIFY_ALL(mCommandCompleteCondition);
  484. }
  485. void RenderSystem::throwIfNotRenderThread() const
  486. {
  487. if(CM_THREAD_CURRENT_ID != getRenderThreadId())
  488. CM_EXCEPT(InternalErrorException, "Calling the render system from a non-render thread!");
  489. }
  490. /************************************************************************/
  491. /* THREAD WORKER */
  492. /************************************************************************/
  493. RenderSystem::RenderWorkerFunc::RenderWorkerFunc(RenderSystem* rs)
  494. :mRS(rs)
  495. {
  496. assert(mRS != nullptr);
  497. }
  498. void RenderSystem::RenderWorkerFunc::operator()()
  499. {
  500. mRS->runRenderThread();
  501. }
  502. }
  503. #undef THROW_IF_NOT_RENDER_THREAD