CmRenderSystem.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. #ifndef __RenderSystem_H_
  25. #define __RenderSystem_H_
  26. // Precompiler options
  27. #include "CmPrerequisites.h"
  28. #include <memory>
  29. #include "CmString.h"
  30. #include "CmSamplerState.h"
  31. #include "CmCommonEnums.h"
  32. #include "CmRenderOperation.h"
  33. #include "CmRenderSystemCapabilities.h"
  34. #include "CmRenderTarget.h"
  35. #include "CmRenderTexture.h"
  36. #include "CmRenderWindow.h"
  37. #include "CmGpuProgram.h"
  38. #include "CmPlane.h"
  39. #include "CmModule.h"
  40. #include "boost/function.hpp"
  41. #include "boost/signal.hpp"
  42. namespace CamelotFramework
  43. {
  44. /** \addtogroup Core
  45. * @{
  46. */
  47. /** \addtogroup RenderSystem
  48. * @{
  49. */
  50. typedef multimap<UINT8, RenderTarget * >::type RenderTargetPriorityMap;
  51. class TextureManager;
  52. /** Defines the functionality of a 3D API
  53. @remarks
  54. The RenderSystem class provides a base interface
  55. which abstracts the general functionality of the 3D API
  56. e.g. Direct3D or OpenGL. Whilst a few of the general
  57. methods have implementations, most of this class is
  58. abstract, requiring a subclass based on a specific API
  59. to be constructed to provide the full functionality.
  60. @author
  61. Steven Streeting
  62. @version
  63. 1.0
  64. */
  65. class CM_EXPORT RenderSystem : public Module<RenderSystem>
  66. {
  67. public:
  68. /** Default Constructor.
  69. */
  70. RenderSystem();
  71. /** Destructor.
  72. */
  73. virtual ~RenderSystem();
  74. /** Returns the name of the rendering system.
  75. */
  76. virtual const String& getName(void) const = 0;
  77. /**
  78. * @brief Gets the name of the primary shading language.
  79. */
  80. virtual const String& getShadingLanguageName() const = 0;
  81. /** Notifies the render system that a new window was created.
  82. *
  83. * @note Should only be called by internal methods.
  84. */
  85. virtual void _notifyWindowCreated(RenderWindow& window);
  86. /**
  87. * @brief Sets a sampler state for the specified texture unit.
  88. * @see SamplerState
  89. */
  90. virtual void setSamplerState(GpuProgramType gptype, UINT16 texUnit, const SamplerStatePtr& samplerState) = 0;
  91. /** Turns off a texture unit. */
  92. virtual void disableTextureUnit(GpuProgramType gptype, UINT16 texUnit);
  93. /**
  94. * @brief Sets a blend state used for all active render targets.
  95. * @see BlendState
  96. */
  97. virtual void setBlendState(const BlendStatePtr& blendState) = 0;
  98. /**
  99. * @brief Sets a state that controls various rasterizer options.
  100. * @see RasterizerState
  101. */
  102. virtual void setRasterizerState(const RasterizerStatePtr& rasterizerState) = 0;
  103. /**
  104. * @brief Sets a state that controls depth & stencil buffer options.
  105. * @see DepthStencilState
  106. */
  107. virtual void setDepthStencilState(const DepthStencilStatePtr& depthStencilState, UINT32 stencilRefValue) = 0;
  108. /**
  109. Sets the texture to bind to a given texture unit.
  110. User processes would not normally call this direct unless rendering
  111. primitives themselves.
  112. @param unit The index of the texture unit to modify. Multitexturing
  113. hardware can support multiple units (see
  114. RenderSystemCapabilites::getNumTextureUnits)
  115. @param enabled Boolean to turn the unit on/off
  116. @param texPtr Pointer to the texture to use.
  117. */
  118. virtual void setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const TexturePtr &texPtr) = 0;
  119. /**
  120. * Signifies the beginning of a frame, i.e. the start of rendering on a single viewport. Will occur
  121. * several times per complete frame if multiple viewports exist.
  122. */
  123. virtual void beginFrame(void) = 0;
  124. /**
  125. * Ends rendering of a frame to the current viewport.
  126. */
  127. virtual void endFrame(void) = 0;
  128. /**
  129. Sets the provided viewport as the active one for future
  130. rendering operations. This viewport is aware of it's own
  131. camera and render target. Must be implemented by subclass.
  132. @param target Viewport to render to.
  133. */
  134. virtual void setViewport(ViewportPtr& vp) = 0;
  135. /** Sets the current vertex buffer for the specified source index.
  136. /** @note Set buffer to nullptr to clear the buffer at the specified index.*/
  137. virtual void setVertexBuffer(UINT32 index, const VertexBufferPtr& buffer) = 0;
  138. /**
  139. * @brief Sets an index buffer to use when drawing. Indices in an index buffer
  140. * reference vertices in the vertex buffer, which increases cache coherency
  141. * and reduces the size of vertex buffers by eliminating duplicate data.
  142. */
  143. virtual void setIndexBuffer(const IndexBufferPtr& buffer) = 0;
  144. /**
  145. * @brief Sets the vertex declaration to use when drawing. Vertex declaration
  146. * is used to decode contents of a single vertex in a vertex buffer.
  147. */
  148. virtual void setVertexDeclaration(VertexDeclarationPtr vertexDeclaration) = 0;
  149. /**
  150. * @brief Sets the draw operation that determines how to interpret the elements
  151. * of the index or vertex buffers.
  152. */
  153. virtual void setDrawOperation(DrawOperationType op) = 0;
  154. /**
  155. * @brief A helper method that provides a simple way of rendering a single object.
  156. * It will automatically set up vertex declaration, draw operation,
  157. * vertex and index buffers and draw them.
  158. */
  159. virtual void render(const RenderOperation& op);
  160. /**
  161. * @brief Draw an object based on currently set
  162. * shaders, vertex declaration index buffers.
  163. *
  164. * Draws directly from the vertex buffer without using
  165. * indices.
  166. */
  167. virtual void draw(UINT32 vertexCount) = 0;
  168. /**
  169. * @brief Draw an object based on currently set
  170. * shaders, vertex declaration and vertex
  171. * and index buffers.
  172. */
  173. virtual void drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexCount) = 0;
  174. /**
  175. * @brief Swap the front and back buffer of the specified render target.
  176. */
  177. virtual void swapBuffers(RenderTargetPtr target);
  178. /** Gets the capabilities of the render system. */
  179. const RenderSystemCapabilities* getCapabilities(void) const;
  180. /** Returns the driver version.
  181. */
  182. virtual const DriverVersion& getDriverVersion(void) const;
  183. /** Binds a given GpuProgram (but not the parameters).
  184. @remarks Only one GpuProgram of each type can be bound at once, binding another
  185. one will simply replace the existing one.
  186. */
  187. virtual void bindGpuProgram(HGpuProgram prg);
  188. /** Bind Gpu program parameters.
  189. @param gptype The type of program to bind the parameters to
  190. @param params The parameters to bind
  191. */
  192. virtual void bindGpuParams(GpuProgramType gptype, BindableGpuParams& params) = 0;
  193. /** Unbinds GpuPrograms of a given GpuProgramType.
  194. @remarks
  195. This returns the pipeline to fixed-function processing for this type.
  196. */
  197. virtual void unbindGpuProgram(GpuProgramType gptype);
  198. /** Returns whether or not a Gpu program of the given type is currently bound. */
  199. virtual bool isGpuProgramBound(GpuProgramType gptype);
  200. /** Sets the user clipping region.
  201. */
  202. virtual void setClipPlanes(const PlaneList& clipPlanes);
  203. /** Add a user clipping plane. */
  204. virtual void addClipPlane (const Plane& p);
  205. /** Add a user clipping plane. */
  206. virtual void addClipPlane (float A, float B, float C, float D);
  207. /** Clears the user clipping region.
  208. */
  209. virtual void resetClipPlanes();
  210. /** Sets the 'scissor region' ie the region of the target in which rendering can take place.
  211. @remarks
  212. This method allows you to 'mask off' rendering in all but a given rectangular area
  213. as identified by the parameters to this method.
  214. @note
  215. Not all systems support this method. Check the RenderSystemCapabilities for the
  216. RSC_SCISSOR_TEST capability to see if it is supported.
  217. @param left, top, right, bottom The location of the corners of the rectangle, expressed in
  218. <i>pixels</i>.
  219. */
  220. virtual void setScissorRect(UINT32 left = 0, UINT32 top = 0, UINT32 right = 800, UINT32 bottom = 600) = 0;
  221. /** Clears the provided render target to the specified values
  222. @param renderTarget Render target to clear. Entire surface will be cleared
  223. regardless of viewport or scissor rect.
  224. @param buffers Combination of one or more elements of FrameBufferType
  225. denoting which buffers are to be cleared
  226. @param colour The colour to clear the colour buffer with, if enabled
  227. @param depth The value to initialise the depth buffer with, if enabled
  228. @param stencil The value to initialise the stencil buffer with, if enabled.
  229. */
  230. virtual void clear(RenderTargetPtr renderTarget, unsigned int buffers,
  231. const Color& color = Color::Black,
  232. float depth = 1.0f, unsigned short stencil = 0) = 0;
  233. /**
  234. * Set current render target to target, enabling its device context if needed
  235. */
  236. virtual void setRenderTarget(RenderTargetPtr target) = 0;
  237. /************************************************************************/
  238. /* UTILITY METHODS */
  239. /************************************************************************/
  240. /** Get the native VertexElementType for a compact 32-bit colour value
  241. for this rendersystem.
  242. */
  243. virtual VertexElementType getColorVertexElementType(void) const = 0;
  244. /** Converts a uniform projection matrix to suitable for this render system.
  245. @remarks
  246. Because different APIs have different requirements (some incompatible) for the
  247. projection matrix, this method allows each to implement their own correctly and pass
  248. back a generic Camelot matrix for storage in the engine.
  249. */
  250. virtual void convertProjectionMatrix(const Matrix4& matrix,
  251. Matrix4& dest, bool forGpuProgram = false) = 0;
  252. /** Returns the horizontal texel offset value required for mapping
  253. texel origins to pixel origins in this rendersystem.
  254. @remarks
  255. Since rendersystems sometimes disagree on the origin of a texel,
  256. mapping from texels to pixels can sometimes be problematic to
  257. implement generically. This method allows you to retrieve the offset
  258. required to map the origin of a texel to the origin of a pixel in
  259. the horizontal direction.
  260. */
  261. virtual float getHorizontalTexelOffset(void) = 0;
  262. /** Returns the vertical texel offset value required for mapping
  263. texel origins to pixel origins in this rendersystem.
  264. @remarks
  265. Since rendersystems sometimes disagree on the origin of a texel,
  266. mapping from texels to pixels can sometimes be problematic to
  267. implement generically. This method allows you to retrieve the offset
  268. required to map the origin of a texel to the origin of a pixel in
  269. the vertical direction.
  270. */
  271. virtual float getVerticalTexelOffset(void) = 0;
  272. /** Gets the minimum (closest) depth value to be used when rendering
  273. using identity transforms.
  274. @remarks
  275. When using identity transforms you can manually set the depth
  276. of a vertex; however the input values required differ per
  277. rendersystem. This method lets you retrieve the correct value.
  278. @see Renderable::getUseIdentityView, Renderable::getUseIdentityProjection
  279. */
  280. virtual float getMinimumDepthInputValue(void) = 0;
  281. /** Gets the maximum (farthest) depth value to be used when rendering
  282. using identity transforms.
  283. @remarks
  284. When using identity transforms you can manually set the depth
  285. of a vertex; however the input values required differ per
  286. rendersystem. This method lets you retrieve the correct value.
  287. @see Renderable::getUseIdentityView, Renderable::getUseIdentityProjection
  288. */
  289. virtual float getMaximumDepthInputValue(void) = 0;
  290. /************************************************************************/
  291. /* INTERNAL DATA & METHODS */
  292. /************************************************************************/
  293. protected:
  294. friend class RenderSystemManager;
  295. /** The Active render target. */
  296. RenderTargetPtr mActiveRenderTarget;
  297. CullingMode mCullingMode;
  298. bool mInvertVertexWinding;
  299. /// Texture units from this upwards are disabled
  300. UINT16 mDisabledTexUnitsFrom;
  301. bool mVertexProgramBound;
  302. bool mGeometryProgramBound;
  303. bool mFragmentProgramBound;
  304. // Recording user clip planes
  305. PlaneList mClipPlanes;
  306. // Indicator that we need to re-set the clip planes on next render call
  307. bool mClipPlanesDirty;
  308. /// Used to store the capabilities of the graphics card
  309. RenderSystemCapabilities* mCurrentCapabilities;
  310. // TODO - Only used between initialize and initialize_internal. Handle it better?
  311. RENDER_WINDOW_DESC mPrimaryWindowDesc;
  312. /**
  313. * @brief Initializes the render system and creates a primary render window.
  314. *
  315. * @note Although I'd like otherwise, due to the nature of some render system implementations,
  316. * you cannot initialize the render system without a window.
  317. */
  318. RenderWindowPtr initialize(const RENDER_WINDOW_DESC& primaryWindowDesc);
  319. virtual void initialize_internal(AsyncOp& asyncOp);
  320. virtual void destroy_internal();
  321. /// Internal method used to set the underlying clip planes when needed
  322. virtual void setClipPlanesImpl(const PlaneList& clipPlanes) = 0;
  323. /** Query the real capabilities of the GPU and driver in the RenderSystem*/
  324. virtual RenderSystemCapabilities* createRenderSystemCapabilities() const = 0;
  325. /** Initialize the render system from the capabilities*/
  326. virtual void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps) = 0;
  327. /** Returns a description of an error code.
  328. */
  329. virtual String getErrorDescription(long errorNumber) const = 0;
  330. DriverVersion mDriverVersion;
  331. /************************************************************************/
  332. /* RENDER THREAD */
  333. /************************************************************************/
  334. class RenderWorkerFunc CM_THREAD_WORKER_INHERIT
  335. {
  336. public:
  337. RenderWorkerFunc(RenderSystem* rs);
  338. void operator()();
  339. private:
  340. RenderSystem* mRS;
  341. };
  342. RenderWorkerFunc* mRenderThreadFunc;
  343. volatile bool mRenderThreadStarted;
  344. volatile bool mRenderThreadShutdown;
  345. CM_THREAD_ID_TYPE mRenderThreadId;
  346. CM_THREAD_SYNCHRONISER(mRenderThreadStartCondition)
  347. CM_MUTEX(mRenderThreadStartMutex)
  348. CM_MUTEX(mCommandQueueMutex)
  349. CM_THREAD_SYNCHRONISER(mCommandReadyCondition)
  350. CM_MUTEX(mCommandNotifyMutex)
  351. CM_THREAD_SYNCHRONISER(mCommandCompleteCondition)
  352. #if CM_THREAD_SUPPORT
  353. CM_THREAD_TYPE* mRenderThread;
  354. #endif
  355. CommandQueue* mCommandQueue;
  356. UINT32 mMaxCommandNotifyId; // ID that will be assigned to the next command with a notifier callback
  357. vector<UINT32>::type mCommandsCompleted; // Completed commands that have notifier callbacks set up
  358. /**
  359. * @brief Initializes a separate render thread. Should only be called once.
  360. */
  361. void initRenderThread();
  362. /**
  363. * @brief Main function of the render thread. Called once thread is started.
  364. */
  365. void runRenderThread();
  366. /**
  367. * @brief Shutdowns the render thread. It will complete all ready commands
  368. * before shutdown.
  369. */
  370. void shutdownRenderThread();
  371. /**
  372. * @brief Throws an exception if current thread isn't the render thread;
  373. */
  374. void throwIfNotRenderThread() const;
  375. /**
  376. * @brief Blocks the calling thread until the command with the specified ID completes.
  377. * Make sure that the specified ID actually exists, otherwise this will block forever.
  378. */
  379. void blockUntilCommandCompleted(UINT32 commandId);
  380. /**
  381. * @brief Callback called by the command list when a specific command finishes executing.
  382. * This is only called on commands that have a special notify on complete flag set.
  383. *
  384. * @param commandId Identifier for the command.
  385. */
  386. void commandCompletedNotify(UINT32 commandId);
  387. public:
  388. /**
  389. * @brief Returns the id of the render thread. If a separate render thread
  390. * is not used, then it returns the id of the thread RenderSystem
  391. * was initialized on.
  392. */
  393. CM_THREAD_ID_TYPE getRenderThreadId() const { return mRenderThreadId; }
  394. /**
  395. * @brief Creates a new render system context that you can use for rendering on
  396. * a non-render thread. You can have as many of these as you wish, the only limitation
  397. * is that you do not use a single instance on more than one thread. Each thread
  398. * requires its own context. The context will be bound to the thread you call this method on.
  399. */
  400. DeferredRenderContextPtr createDeferredContext();
  401. /**
  402. * @brief Queues a new command that will be added to the global command queue. You are allowed to call this from any thread,
  403. * however be aware that it involves possibly slow synchronization primitives, so limit your usage.
  404. *
  405. * @param blockUntilComplete If true the thread will be blocked until the command executes. Be aware that there be many commands queued before it
  406. * and they all need to be executed in order before the current command is reached, which might take a long time.
  407. *
  408. * @see CommandQueue::queueReturn
  409. */
  410. AsyncOp queueReturnCommand(boost::function<void(AsyncOp&)> commandCallback, bool blockUntilComplete = false);
  411. /**
  412. * @brief Queues a new command that will be added to the global command queue.You are allowed to call this from any thread,
  413. * however be aware that it involves possibly slow synchronization primitives, so limit your usage.
  414. *
  415. * @param blockUntilComplete If true the thread will be blocked until the command executes. Be aware that there be many commands queued before it
  416. * and they all need to be executed in order before the current command is reached, which might take a long time.
  417. * @see CommandQueue::queue
  418. */
  419. void queueCommand(boost::function<void()> commandCallback, bool blockUntilComplete = false);
  420. };
  421. /** @} */
  422. /** @} */
  423. }
  424. #endif