CmRenderSystem.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 "CmPixelBuffer.h"
  35. #include "CmOcclusionQuery.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. // Base classes need to call virtual destroy_internal method (queue it on render thread)
  69. // TODO - What if something gets queued between the queued call to destroy_internal and this!?
  70. shutdownRenderThread();
  71. if(mCommandQueue != nullptr)
  72. {
  73. delete mCommandQueue;
  74. mCommandQueue = nullptr;
  75. }
  76. delete mCurrentCapabilities;
  77. mCurrentCapabilities = 0;
  78. }
  79. //-----------------------------------------------------------------------
  80. void RenderSystem::initialize()
  81. {
  82. mRenderThreadId = CM_THREAD_CURRENT_ID;
  83. mCommandQueue = new CommandQueue(CM_THREAD_CURRENT_ID);
  84. initRenderThread();
  85. queueCommand(boost::bind(&RenderSystem::initialize_internal, this), true);
  86. }
  87. //-----------------------------------------------------------------------
  88. void RenderSystem::initialize_internal()
  89. {
  90. THROW_IF_NOT_RENDER_THREAD;
  91. mVertexProgramBound = false;
  92. mGeometryProgramBound = false;
  93. mFragmentProgramBound = false;
  94. }
  95. //-----------------------------------------------------------------------
  96. void RenderSystem::destroy_internal()
  97. {
  98. // Remove all the render targets.
  99. // (destroy primary target last since others may depend on it)
  100. RenderTarget* primary = 0;
  101. for (auto it = mRenderTargets.begin(); it != mRenderTargets.end(); ++it)
  102. {
  103. if (!primary && (*it)->isPrimary())
  104. primary = *it;
  105. else
  106. delete *it;
  107. }
  108. delete primary;
  109. mRenderTargets.clear();
  110. mPrioritisedRenderTargets.clear();
  111. }
  112. //-----------------------------------------------------------------------
  113. void RenderSystem::swapAllRenderTargetBuffers(bool waitForVSync)
  114. {
  115. THROW_IF_NOT_RENDER_THREAD;
  116. // Update all in order of priority
  117. // This ensures render-to-texture targets get updated before render windows
  118. RenderTargetPriorityMap::iterator itarg, itargend;
  119. itargend = mPrioritisedRenderTargets.end();
  120. for( itarg = mPrioritisedRenderTargets.begin(); itarg != itargend; ++itarg )
  121. {
  122. if( itarg->second->isActive())
  123. itarg->second->swapBuffers(waitForVSync);
  124. }
  125. }
  126. //---------------------------------------------------------------------------------------------
  127. void RenderSystem::destroyRenderWindow(RenderWindow* renderWindow)
  128. {
  129. THROW_IF_NOT_RENDER_THREAD;
  130. destroyRenderTarget(renderWindow);
  131. }
  132. //---------------------------------------------------------------------------------------------
  133. void RenderSystem::destroyRenderTexture(RenderTexture* renderTexture)
  134. {
  135. THROW_IF_NOT_RENDER_THREAD;
  136. destroyRenderTarget(renderTexture);
  137. }
  138. //---------------------------------------------------------------------------------------------
  139. void RenderSystem::destroyRenderTarget(RenderTarget* renderTarget)
  140. {
  141. THROW_IF_NOT_RENDER_THREAD;
  142. detachRenderTarget(*renderTarget);
  143. delete renderTarget;
  144. }
  145. //---------------------------------------------------------------------------------------------
  146. void RenderSystem::attachRenderTarget( RenderTarget &target )
  147. {
  148. THROW_IF_NOT_RENDER_THREAD;
  149. assert( target.getPriority() < CM_NUM_RENDERTARGET_GROUPS );
  150. mRenderTargets.push_back(&target);
  151. mPrioritisedRenderTargets.insert(
  152. RenderTargetPriorityMap::value_type(target.getPriority(), &target ));
  153. }
  154. //---------------------------------------------------------------------------------------------
  155. void RenderSystem::detachRenderTarget(RenderTarget& renderTarget)
  156. {
  157. THROW_IF_NOT_RENDER_THREAD;
  158. auto it = std::find(mRenderTargets.begin(), mRenderTargets.end(), &renderTarget);
  159. RenderTarget* foundRT = nullptr;
  160. if( it != mRenderTargets.end() )
  161. {
  162. foundRT = *it;
  163. /* Remove the render target from the priority groups. */
  164. RenderTargetPriorityMap::iterator itarg, itargend;
  165. itargend = mPrioritisedRenderTargets.end();
  166. for( itarg = mPrioritisedRenderTargets.begin(); itarg != itargend; ++itarg )
  167. {
  168. if( itarg->second == *it ) {
  169. mPrioritisedRenderTargets.erase( itarg );
  170. break;
  171. }
  172. }
  173. mRenderTargets.erase( it );
  174. }
  175. /// If detached render target is the active render target, reset active render target
  176. if(foundRT == mActiveRenderTarget)
  177. mActiveRenderTarget = 0;
  178. }
  179. //---------------------------------------------------------------------------------------------
  180. const RenderSystemCapabilities* RenderSystem::getCapabilities(void) const
  181. {
  182. THROW_IF_NOT_RENDER_THREAD;
  183. return mCurrentCapabilities;
  184. }
  185. //---------------------------------------------------------------------------------------------
  186. const DriverVersion& RenderSystem::getDriverVersion(void) const
  187. {
  188. THROW_IF_NOT_RENDER_THREAD;
  189. return mDriverVersion;
  190. }
  191. //-----------------------------------------------------------------------
  192. Viewport RenderSystem::getViewport(void)
  193. {
  194. THROW_IF_NOT_RENDER_THREAD;
  195. return mActiveViewport;
  196. }
  197. //-----------------------------------------------------------------------
  198. void RenderSystem::disableTextureUnit(GpuProgramType gptype, UINT16 texUnit)
  199. {
  200. THROW_IF_NOT_RENDER_THREAD;
  201. setTexture(gptype, texUnit, false, sNullTexPtr);
  202. }
  203. //-----------------------------------------------------------------------
  204. bool RenderSystem::getWaitForVerticalBlank(void) const
  205. {
  206. THROW_IF_NOT_RENDER_THREAD;
  207. return mVsync;
  208. }
  209. //-----------------------------------------------------------------------
  210. void RenderSystem::setWaitForVerticalBlank(bool enabled)
  211. {
  212. THROW_IF_NOT_RENDER_THREAD;
  213. mVsync = enabled;
  214. }
  215. //---------------------------------------------------------------------
  216. void RenderSystem::addClipPlane (const Plane &p)
  217. {
  218. THROW_IF_NOT_RENDER_THREAD;
  219. mClipPlanes.push_back(p);
  220. mClipPlanesDirty = true;
  221. }
  222. //---------------------------------------------------------------------
  223. void RenderSystem::addClipPlane (float A, float B, float C, float D)
  224. {
  225. THROW_IF_NOT_RENDER_THREAD;
  226. addClipPlane(Plane(A, B, C, D));
  227. }
  228. //---------------------------------------------------------------------
  229. void RenderSystem::setClipPlanes(const PlaneList& clipPlanes)
  230. {
  231. THROW_IF_NOT_RENDER_THREAD;
  232. if (clipPlanes != mClipPlanes)
  233. {
  234. mClipPlanes = clipPlanes;
  235. mClipPlanesDirty = true;
  236. }
  237. }
  238. //---------------------------------------------------------------------
  239. void RenderSystem::resetClipPlanes()
  240. {
  241. THROW_IF_NOT_RENDER_THREAD;
  242. if (!mClipPlanes.empty())
  243. {
  244. mClipPlanes.clear();
  245. mClipPlanesDirty = true;
  246. }
  247. }
  248. //-----------------------------------------------------------------------
  249. void RenderSystem::bindGpuProgram(GpuProgramHandle prg)
  250. {
  251. THROW_IF_NOT_RENDER_THREAD;
  252. switch(prg->getBindingDelegate()->getType())
  253. {
  254. case GPT_VERTEX_PROGRAM:
  255. // mark clip planes dirty if changed (programmable can change space)
  256. if (!mVertexProgramBound && !mClipPlanes.empty())
  257. mClipPlanesDirty = true;
  258. mVertexProgramBound = true;
  259. break;
  260. case GPT_GEOMETRY_PROGRAM:
  261. mGeometryProgramBound = true;
  262. break;
  263. case GPT_FRAGMENT_PROGRAM:
  264. mFragmentProgramBound = true;
  265. break;
  266. }
  267. }
  268. //-----------------------------------------------------------------------
  269. void RenderSystem::unbindGpuProgram(GpuProgramType gptype)
  270. {
  271. THROW_IF_NOT_RENDER_THREAD;
  272. switch(gptype)
  273. {
  274. case GPT_VERTEX_PROGRAM:
  275. // mark clip planes dirty if changed (programmable can change space)
  276. if (mVertexProgramBound && !mClipPlanes.empty())
  277. mClipPlanesDirty = true;
  278. mVertexProgramBound = false;
  279. break;
  280. case GPT_GEOMETRY_PROGRAM:
  281. mGeometryProgramBound = false;
  282. break;
  283. case GPT_FRAGMENT_PROGRAM:
  284. mFragmentProgramBound = false;
  285. break;
  286. }
  287. }
  288. //-----------------------------------------------------------------------
  289. bool RenderSystem::isGpuProgramBound(GpuProgramType gptype)
  290. {
  291. THROW_IF_NOT_RENDER_THREAD;
  292. switch(gptype)
  293. {
  294. case GPT_VERTEX_PROGRAM:
  295. return mVertexProgramBound;
  296. case GPT_GEOMETRY_PROGRAM:
  297. return mGeometryProgramBound;
  298. case GPT_FRAGMENT_PROGRAM:
  299. return mFragmentProgramBound;
  300. }
  301. // Make compiler happy
  302. return false;
  303. }
  304. //-----------------------------------------------------------------------
  305. void RenderSystem::render(const RenderOperation& op)
  306. {
  307. THROW_IF_NOT_RENDER_THREAD;
  308. // sort out clip planes
  309. // have to do it here in case of matrix issues
  310. if (mClipPlanesDirty)
  311. {
  312. setClipPlanesImpl(mClipPlanes);
  313. mClipPlanesDirty = false;
  314. }
  315. setVertexDeclaration(op.vertexData->vertexDeclaration);
  316. auto vertexBuffers = op.vertexData->getBuffers();
  317. for(auto iter = vertexBuffers.begin(); iter != vertexBuffers.end() ; ++iter)
  318. setVertexBuffer(iter->first, iter->second);
  319. setDrawOperation(op.operationType);
  320. if (op.useIndexes)
  321. {
  322. setIndexBuffer(op.indexData->indexBuffer);
  323. drawIndexed(op.indexData->indexStart, op.indexData->indexCount, op.vertexData->vertexCount);
  324. }
  325. else
  326. draw(op.vertexData->vertexCount);
  327. }
  328. /************************************************************************/
  329. /* PRIVATE */
  330. /************************************************************************/
  331. void RenderSystem::initRenderThread()
  332. {
  333. #if !CM_FORCE_SINGLETHREADED_RENDERING
  334. mRenderThreadFunc = new RenderWorkerFunc(this);
  335. #if CM_THREAD_SUPPORT
  336. CM_THREAD_CREATE(t, *mRenderThreadFunc);
  337. mRenderThread = t;
  338. CM_LOCK_MUTEX_NAMED(mRenderThreadStartMutex, lock)
  339. CM_THREAD_WAIT(mRenderThreadStartCondition, mRenderThreadStartMutex, lock)
  340. #else
  341. CM_EXCEPT(InternalErrorException, "Attempting to start a render thread but Camelot isn't compiled with thread support.");
  342. #endif
  343. #endif
  344. }
  345. void RenderSystem::runRenderThread()
  346. {
  347. #if !CM_FORCE_SINGLETHREADED_RENDERING
  348. mRenderThreadId = CM_THREAD_CURRENT_ID;
  349. CM_THREAD_NOTIFY_ALL(mRenderThreadStartCondition)
  350. while(true)
  351. {
  352. // Wait until we get some ready commands
  353. vector<CommandQueue::Command>::type* commands = nullptr;
  354. {
  355. CM_LOCK_MUTEX_NAMED(mCommandQueueMutex, lock)
  356. while(mCommandQueue->isEmpty())
  357. {
  358. if(mRenderThreadShutdown)
  359. return;
  360. CM_THREAD_WAIT(mCommandReadyCondition, mCommandQueueMutex, lock);
  361. }
  362. commands = mCommandQueue->flush();
  363. }
  364. // Play commands
  365. mCommandQueue->playback(commands, boost::bind(&RenderSystem::commandCompletedNotify, this, _1));
  366. }
  367. #endif
  368. }
  369. void RenderSystem::shutdownRenderThread()
  370. {
  371. #if !CM_FORCE_SINGLETHREADED_RENDERING
  372. {
  373. CM_LOCK_MUTEX(mCommandQueueMutex);
  374. mRenderThreadShutdown = true;
  375. }
  376. // Wake all threads. They will quit after they see the shutdown flag
  377. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  378. mRenderThread->join();
  379. CM_THREAD_DESTROY(mRenderThread);
  380. mRenderThread = nullptr;
  381. mRenderThreadId = CM_THREAD_CURRENT_ID;
  382. #endif
  383. }
  384. DeferredRenderContextPtr RenderSystem::createDeferredContext()
  385. {
  386. return DeferredRenderContextPtr(new DeferredRenderContext(this, CM_THREAD_CURRENT_ID));
  387. }
  388. AsyncOp RenderSystem::queueReturnCommand(boost::function<void(AsyncOp&)> commandCallback, bool blockUntilComplete)
  389. {
  390. AsyncOp op;
  391. if(CM_THREAD_CURRENT_ID == getRenderThreadId())
  392. {
  393. commandCallback(op); // Execute immediately
  394. return op;
  395. }
  396. UINT32 commandId = -1;
  397. {
  398. CM_LOCK_MUTEX(mCommandQueueMutex);
  399. if(blockUntilComplete)
  400. {
  401. commandId = mMaxCommandNotifyId++;
  402. op = mCommandQueue->queueReturn(commandCallback, true, commandId);
  403. }
  404. else
  405. op = mCommandQueue->queueReturn(commandCallback);
  406. }
  407. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  408. if(blockUntilComplete)
  409. blockUntilCommandCompleted(commandId);
  410. return op;
  411. }
  412. void RenderSystem::queueCommand(boost::function<void()> commandCallback, bool blockUntilComplete)
  413. {
  414. if(CM_THREAD_CURRENT_ID == getRenderThreadId())
  415. {
  416. commandCallback(); // Execute immediately
  417. return;
  418. }
  419. UINT32 commandId = -1;
  420. {
  421. CM_LOCK_MUTEX(mCommandQueueMutex);
  422. if(blockUntilComplete)
  423. {
  424. commandId = mMaxCommandNotifyId++;
  425. mCommandQueue->queue(commandCallback, true, commandId);
  426. }
  427. else
  428. mCommandQueue->queue(commandCallback);
  429. }
  430. CM_THREAD_NOTIFY_ALL(mCommandReadyCondition);
  431. if(blockUntilComplete)
  432. blockUntilCommandCompleted(commandId);
  433. }
  434. void RenderSystem::blockUntilCommandCompleted(UINT32 commandId)
  435. {
  436. #if !CM_FORCE_SINGLETHREADED_RENDERING
  437. CM_LOCK_MUTEX_NAMED(mCommandNotifyMutex, lock);
  438. while(true)
  439. {
  440. // Check if our command id is in the completed list
  441. auto iter = mCommandsCompleted.begin();
  442. for(; iter != mCommandsCompleted.end(); ++iter)
  443. {
  444. if(*iter == commandId)
  445. break;
  446. }
  447. if(iter != mCommandsCompleted.end())
  448. {
  449. mCommandsCompleted.erase(iter);
  450. break;
  451. }
  452. CM_THREAD_WAIT(mCommandCompleteCondition, mCommandNotifyMutex, lock);
  453. }
  454. #endif
  455. }
  456. void RenderSystem::commandCompletedNotify(UINT32 commandId)
  457. {
  458. {
  459. CM_LOCK_MUTEX(mCommandNotifyMutex);
  460. mCommandsCompleted.push_back(commandId);
  461. }
  462. CM_THREAD_NOTIFY_ALL(mCommandCompleteCondition);
  463. }
  464. void RenderSystem::throwIfNotRenderThread() const
  465. {
  466. #if !CM_FORCE_SINGLETHREADED_RENDERING
  467. if(CM_THREAD_CURRENT_ID != getRenderThreadId())
  468. CM_EXCEPT(InternalErrorException, "Calling the render system from a non-render thread!");
  469. #endif
  470. }
  471. /************************************************************************/
  472. /* THREAD WORKER */
  473. /************************************************************************/
  474. RenderSystem::RenderWorkerFunc::RenderWorkerFunc(RenderSystem* rs)
  475. :mRS(rs)
  476. {
  477. assert(mRS != nullptr);
  478. }
  479. void RenderSystem::RenderWorkerFunc::operator()()
  480. {
  481. mRS->runRenderThread();
  482. }
  483. }
  484. #undef THROW_IF_NOT_RENDER_THREAD