D3D9Graphics.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  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. #pragma once
  24. #include "Color.h"
  25. #include "HashMap.h"
  26. #include "Object.h"
  27. #include "Rect.h"
  28. #include "GraphicsDefs.h"
  29. class Image;
  30. class IndexBuffer;
  31. class Matrix3;
  32. class Matrix4;
  33. class Matrix3x4;
  34. class GPUObject;
  35. class GraphicsImpl;
  36. class RenderSurface;
  37. class ShaderVariation;
  38. class Texture;
  39. class Texture2D;
  40. class TextureCube;
  41. class Vector3;
  42. class Vector4;
  43. class VertexBuffer;
  44. class VertexDeclaration;
  45. struct ShaderParameter;
  46. /// %Graphics subsystem. Manages the application window, rendering state and GPU resources.
  47. class Graphics : public Object
  48. {
  49. OBJECT(Graphics);
  50. public:
  51. /// Construct.
  52. Graphics(Context* context);
  53. /// Destruct. Close the window and release the Direct3D9 device .
  54. virtual ~Graphics();
  55. /// %Set window title.
  56. void SetWindowTitle(const String& windowTitle);
  57. /// %Set screen mode. Return true if successful.
  58. bool SetMode(int width, int height, bool fullscreen, bool vsync, bool tripleBuffer, int multiSample);
  59. /// %Set screen resolution only. Return true if successful.
  60. bool SetMode(int width, int height);
  61. /// Toggle between full screen and windowed mode. Return true if successful.
  62. bool ToggleFullscreen();
  63. /// Close the window.
  64. void Close();
  65. /// Take a screenshot. Return true if successful.
  66. bool TakeScreenShot(Image& destImage);
  67. /// Begin frame rendering. Return true if device available and can render.
  68. bool BeginFrame();
  69. /// End frame rendering and swap buffers.
  70. void EndFrame();
  71. /// Clear any or all of rendertarget, depth buffer and stencil buffer.
  72. void Clear(unsigned flags, const Color& color = Color(0.0f, 0.0f, 0.0f, 0.0f), float depth = 1.0f, unsigned stencil = 0);
  73. /// Resolve multisampled backbuffer to a texture rendertarget.
  74. bool ResolveToTexture(Texture2D* destination, const IntRect& viewport);
  75. /// Draw non-indexed geometry.
  76. void Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount);
  77. /// Draw indexed geometry.
  78. void Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount);
  79. /// Draw indexed, instanced geometry. An instancing vertex buffer must be set.
  80. void DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount, unsigned instanceCount);
  81. /// %Set vertex buffer.
  82. void SetVertexBuffer(VertexBuffer* buffer);
  83. /// %Set multiple vertex buffers.
  84. bool SetVertexBuffers(const Vector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks, unsigned instanceOffset = 0);
  85. /// %Set multiple vertex buffers.
  86. bool SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>& elementMasks, unsigned instanceOffset = 0);
  87. /// %Set index buffer.
  88. void SetIndexBuffer(IndexBuffer* buffer);
  89. /// %Set shaders.
  90. void SetShaders(ShaderVariation* vs, ShaderVariation* ps);
  91. /// %Set shader float constants.
  92. void SetShaderParameter(StringHash param, const float* data, unsigned count);
  93. /// %Set shader float constant.
  94. void SetShaderParameter(StringHash param, float value);
  95. /// %Set shader color constant.
  96. void SetShaderParameter(StringHash param, const Color& color);
  97. /// %Set shader 3x3 matrix constant.
  98. void SetShaderParameter(StringHash param, const Matrix3& matrix);
  99. /// %Set shader 3D vector constant.
  100. void SetShaderParameter(StringHash param, const Vector3& vector);
  101. /// %Set shader 4x4 matrix constant.
  102. void SetShaderParameter(StringHash param, const Matrix4& matrix);
  103. /// %Set shader 4D vector constant.
  104. void SetShaderParameter(StringHash param, const Vector4& vector);
  105. /// %Set shader 3x4 matrix constant.
  106. void SetShaderParameter(StringHash param, const Matrix3x4& matrix);
  107. /// Register a shader parameter globally. Called by Shader.
  108. void RegisterShaderParameter(StringHash param, const ShaderParameter& definition);
  109. /// Check whether a shader parameter group needs update. Does not actually check whether parameters exist in the shaders.
  110. bool NeedParameterUpdate(ShaderParameterGroup group, const void* source);
  111. /// Check whether a shader parameter exists on the currently set shaders.
  112. bool HasShaderParameter(ShaderType type, StringHash param);
  113. /// Check whether the current pixel shader uses a texture unit.
  114. bool HasTextureUnit(TextureUnit unit);
  115. /// Clear remembered shader parameter source group.
  116. void ClearParameterSource(ShaderParameterGroup group);
  117. /// Clear remembered shader parameter sources.
  118. void ClearParameterSources();
  119. /// Clear remembered transform shader parameter sources.
  120. void ClearTransformSources();
  121. /// %Set texture.
  122. void SetTexture(unsigned index, Texture* texture);
  123. /// %Set default texture filtering mode.
  124. void SetDefaultTextureFilterMode(TextureFilterMode mode);
  125. /// %Set texture anisotropy.
  126. void SetTextureAnisotropy(unsigned level);
  127. /// Reset all rendertargets, depth-stencil surface and viewport.
  128. void ResetRenderTargets();
  129. /// Reset specific rendertarget.
  130. void ResetRenderTarget(unsigned index);
  131. /// Reset depth-stencil surface.
  132. void ResetDepthStencil();
  133. /// %Set rendertarget.
  134. void SetRenderTarget(unsigned index, RenderSurface* renderTarget);
  135. /// %Set rendertarget.
  136. void SetRenderTarget(unsigned index, Texture2D* texture);
  137. /// %Set depth-stencil surface.
  138. void SetDepthStencil(RenderSurface* depthStencil);
  139. /// %Set depth-stencil surface.
  140. void SetDepthStencil(Texture2D* texture);
  141. /// %Set view texture (deferred rendering final output rendertarget) to prevent it from being sampled.
  142. void SetViewTexture(Texture* texture);
  143. /// %Set viewport.
  144. void SetViewport(const IntRect& rect);
  145. /// %Set blending mode.
  146. void SetBlendMode(BlendMode mode);
  147. /// %Set color write on/off.
  148. void SetColorWrite(bool enable);
  149. /// %Set hardware culling mode.
  150. void SetCullMode(CullMode mode);
  151. /// %Set depth bias.
  152. void SetDepthBias(float constantBias, float slopeScaledBias);
  153. /// %Set depth compare.
  154. void SetDepthTest(CompareMode mode);
  155. /// %Set depth write on/off.
  156. void SetDepthWrite(bool enable);
  157. /// %Set scissor test.
  158. void SetScissorTest(bool enable, const Rect& rect = Rect::FULL, bool borderInclusive = true);
  159. /// %Set scissor test.
  160. void SetScissorTest(bool enable, const IntRect& rect);
  161. /// %Set stencil test.
  162. void SetStencilTest(bool enable, CompareMode mode = CMP_ALWAYS, StencilOp pass = OP_KEEP, StencilOp fail = OP_KEEP, StencilOp zFail = OP_KEEP, unsigned stencilRef = 0, unsigned compareMask = M_MAX_UNSIGNED, unsigned writeMask = M_MAX_UNSIGNED);
  163. /// %Set vertex buffer stream frequency.
  164. void SetStreamFrequency(unsigned index, unsigned frequency);
  165. /// Reset stream frequencies.
  166. void ResetStreamFrequencies();
  167. /// %Set force Shader Model 2 flag.
  168. void SetForceSM2(bool enable);
  169. /// Return whether rendering initialized.
  170. bool IsInitialized() const;
  171. /// Return graphics implementation, which holds the actual API-specific resources.
  172. GraphicsImpl* GetImpl() const { return impl_; }
  173. /// Return window title.
  174. const String& GetWindowTitle() const { return windowTitle_; }
  175. /// Return window width.
  176. int GetWidth() const { return width_; }
  177. /// Return window height.
  178. int GetHeight() const { return height_; }
  179. /// Return multisample mode (1 = no multisampling.)
  180. int GetMultiSample() const { return multiSample_; }
  181. /// Return whether window is fullscreen.
  182. bool GetFullscreen() const { return fullscreen_; }
  183. /// Return whether vertical sync is on.
  184. bool GetVSync() const { return vsync_; }
  185. /// Return whether triple buffering is enabled.
  186. bool GetTripleBuffer() const { return tripleBuffer_; }
  187. /// Return whether Direct3D device is lost, and can not yet render. This happens during fullscreen resolution switching.
  188. bool IsDeviceLost() const { return deviceLost_; }
  189. /// Return window handle.
  190. unsigned GetWindowHandle() const;
  191. /// Return number of primitives drawn this frame.
  192. unsigned GetNumPrimitives() const { return numPrimitives_; }
  193. /// Return number of batches drawn this frame.
  194. unsigned GetNumBatches() const { return numBatches_; }
  195. /// Return dummy color texture format for shadow maps. Is "NULL" (consume no video memory) if supported.
  196. unsigned GetDummyColorFormat() const { return dummyColorFormat_; }
  197. /// Return shadow map depth texture format, or 0 if not supported.
  198. unsigned GetShadowMapFormat() const { return shadowMapFormat_; }
  199. /// Return 24-bit shadow map depth texture format, or 0 if not supported.
  200. unsigned GetHiresShadowMapFormat() const { return hiresShadowMapFormat_; }
  201. /// Return whether Shader Model 3 is supported.
  202. bool GetSM3Support() const { return hasSM3_; }
  203. /// Return whether light pre-pass rendering is supported.
  204. bool GetLightPrepassSupport() const { return lightPrepassSupport_; }
  205. /// Return whether deferred rendering is supported.
  206. bool GetDeferredSupport() const { return deferredSupport_; }
  207. /// Return whether hardware depth can be read as a texture.
  208. bool GetHardwareDepthSupport() const { return hardwareDepthSupport_; }
  209. /// Return whether shadow map depth compare is done in hardware.
  210. bool GetHardwareShadowSupport() const { return hardwareShadowSupport_; }
  211. /// Return whether 24-bit shadow maps are supported.
  212. bool GetHiresShadowSupport() const { return hiresShadowSupport_; }
  213. /// Return whether stream offset is supported.
  214. bool GetStreamOffsetSupport() const { return streamOffsetSupport_; }
  215. /// Return whether DXT texture compression is supported. Always true on Direct3D9.
  216. bool GetCompressedTextureSupport() const { return true; }
  217. /// Return supported fullscreen resolutions.
  218. PODVector<IntVector2> GetResolutions() const;
  219. /// Return supported multisampling levels.
  220. PODVector<int> GetMultiSampleLevels() const;
  221. /// Return vertex buffer by index.
  222. VertexBuffer* GetVertexBuffer(unsigned index) const;
  223. /// Return current index buffer.
  224. IndexBuffer* GetIndexBuffer() const { return indexBuffer_; }
  225. /// Return current vertex declaration.
  226. VertexDeclaration* GetVertexDeclaration() const { return vertexDeclaration_; }
  227. /// Return current vertex shader.
  228. ShaderVariation* GetVertexShader() const { return vertexShader_; }
  229. /// Return current pixel shader.
  230. ShaderVariation* GetPixelShader() const { return pixelShader_; }
  231. /// Return texture unit index by name.
  232. TextureUnit GetTextureUnit(const String& name);
  233. /// Return current texture by texture unit index.
  234. Texture* GetTexture(unsigned index) const;
  235. /// Return default texture filtering mode.
  236. TextureFilterMode GetDefaultTextureFilterMode() const { return defaultTextureFilterMode_; }
  237. /// Return current rendertarget by index.
  238. RenderSurface* GetRenderTarget(unsigned index) const;
  239. /// Return current depth-stencil surface.
  240. RenderSurface* GetDepthStencil() const { return depthStencil_; }
  241. /// Return backbuffer depth-stencil texture, created if available.
  242. Texture2D* GetDepthTexture() const;
  243. /// Return the viewport coordinates.
  244. IntRect GetViewport() const { return viewport_; }
  245. /// Return texture anisotropy.
  246. unsigned GetTextureAnisotropy() const { return textureAnisotropy_; }
  247. /// Return blending mode.
  248. BlendMode GetBlendMode() const { return blendMode_; }
  249. /// Return whether color write is enabled.
  250. bool GetColorWrite() const { return colorWrite_; }
  251. /// Return hardware culling mode.
  252. CullMode GetCullMode() const { return cullMode_; }
  253. /// Return depth constant bias.
  254. float GetDepthConstantBias() const { return constantDepthBias_; }
  255. /// Return depth slope scaled bias.
  256. float GetDepthSlopeScaledBias() const { return slopeScaledDepthBias_; }
  257. /// Return depth compare mode.
  258. CompareMode GetDepthTest() const { return depthTestMode_; }
  259. /// Return whether depth write is enabled.
  260. bool GetDepthWrite() const { return depthWrite_; }
  261. /// Return whether stencil test is enabled.
  262. bool GetStencilTest() const { return stencilTest_; }
  263. /// Return whether scissor test is enabled.
  264. bool GetScissorTest() const { return scissorTest_; }
  265. /// Return scissor rectangle coordinates.
  266. const IntRect& GetScissorRect() const { return scissorRect_; }
  267. /// Return stencil compare mode.
  268. CompareMode GetStencilTestMode() const { return stencilTestMode_; }
  269. /// Return stencil operation to do if stencil test passes.
  270. StencilOp GetStencilPass() const { return stencilPass_; }
  271. /// Return stencil operation to do if stencil test fails.
  272. StencilOp GetStencilFail() const { return stencilFail_; }
  273. /// Return stencil operation to do if depth compare fails.
  274. StencilOp GetStencilZFail() const { return stencilZFail_; }
  275. /// Return stencil reference value.
  276. unsigned GetStencilRef() const { return stencilRef_; }
  277. /// Return stencil compare bitmask.
  278. unsigned GetStencilCompareMask() const { return stencilCompareMask_; }
  279. /// Return stencil write bitmask.
  280. unsigned GetStencilWriteMask() const { return stencilWriteMask_; }
  281. /// Return stream frequency by vertex buffer index.
  282. unsigned GetStreamFrequency(unsigned index) const;
  283. /// Return rendertarget width and height.
  284. IntVector2 GetRenderTargetDimensions() const;
  285. /// Return force Shader Model 2 flag.
  286. bool GetForceSM2() const { return forceSM2_; }
  287. /// Add a GPU object to keep track of. Called by GPUObject.
  288. void AddGPUObject(GPUObject* object);
  289. /// Remove a GPU object. Called by GPUObject.
  290. void RemoveGPUObject(GPUObject* object);
  291. /// Return the API-specific alpha texture format.
  292. static unsigned GetAlphaFormat();
  293. /// Return the API-specific luminance texture format.
  294. static unsigned GetLuminanceFormat();
  295. /// Return the API-specific luminance alpha texture format.
  296. static unsigned GetLuminanceAlphaFormat();
  297. /// Return the API-specific RGB texture format.
  298. static unsigned GetRGBFormat();
  299. /// Return the API-specific RGBA texture format.
  300. static unsigned GetRGBAFormat();
  301. /// Return the API-specific single channel float texture format.
  302. static unsigned GetFloatFormat();
  303. /// Return the API-specific linear depth texture format.
  304. static unsigned GetLinearDepthFormat();
  305. /// Return the API-specific hardware depth-stencil texture format.
  306. static unsigned GetDepthStencilFormat();
  307. private:
  308. /// Create the application window.
  309. bool OpenWindow(int width, int height);
  310. /// Adjust the window for new resolution and fullscreen mode.
  311. void AdjustWindow(int newWidth, int newHeight, bool newFullscreen);
  312. /// Create the Direct3D interface.
  313. bool CreateInterface();
  314. /// Create the Direct3D device.
  315. bool CreateDevice(unsigned adapter, unsigned deviceType);
  316. /// Check supported rendering features.
  317. void CheckFeatureSupport();
  318. /// Reset the Direct3D device.
  319. void ResetDevice();
  320. /// Notify all GPU resources so they can release themselves as needed.
  321. void OnDeviceLost();
  322. /// Notify all GPU resources so they can recreate themselves as needed.
  323. void OnDeviceReset();
  324. /// Reset cached rendering state.
  325. void ResetCachedState();
  326. /// Initialize texture unit mappings.
  327. void SetTextureUnitMappings();
  328. /// Handle operating system window message.
  329. void HandleWindowMessage(StringHash eventType, VariantMap& eventData);
  330. /// Implementation.
  331. GraphicsImpl* impl_;
  332. /// Window title.
  333. String windowTitle_;
  334. /// Window width.
  335. int width_;
  336. /// Window height.
  337. int height_;
  338. /// Multisampling mode.
  339. int multiSample_;
  340. /// Stored window X-position.
  341. int windowPosX_;
  342. /// Stored window Y-position.
  343. int windowPosY_;
  344. /// Fullscreen flag.
  345. bool fullscreen_;
  346. /// Vertical sync flag.
  347. bool vsync_;
  348. /// Triple buffering flag.
  349. bool tripleBuffer_;
  350. /// Direct3D device lost flag.
  351. bool deviceLost_;
  352. /// System depth-stencil flag.
  353. bool systemDepthStencil_;
  354. /// Light pre-pass rendering support flag.
  355. bool lightPrepassSupport_;
  356. /// Deferred rendering support flag.
  357. bool deferredSupport_;
  358. /// Hardware depth texture support flag.
  359. bool hardwareDepthSupport_;
  360. /// Hardware shadow map depth compare support flag.
  361. bool hardwareShadowSupport_;
  362. /// 24-bit shadow map support flag.
  363. bool hiresShadowSupport_;
  364. /// Stream offset support flag.
  365. bool streamOffsetSupport_;
  366. /// Shader Model 3 flag.
  367. bool hasSM3_;
  368. /// Force Shader Model 2 flag.
  369. bool forceSM2_;
  370. /// Number of primitives this frame.
  371. unsigned numPrimitives_;
  372. /// Number of batches this frame.
  373. unsigned numBatches_;
  374. /// GPU objects.
  375. Vector<GPUObject*> gpuObjects_;
  376. /// Vertex declarations.
  377. HashMap<unsigned long long, SharedPtr<VertexDeclaration> > vertexDeclarations_;
  378. /// Shadow map dummy color texture format.
  379. unsigned dummyColorFormat_;
  380. /// Shadow map depth texture format.
  381. unsigned shadowMapFormat_;
  382. /// Shadow map 24-bit depth texture format.
  383. unsigned hiresShadowMapFormat_;
  384. /// Vertex buffers in use.
  385. VertexBuffer* vertexBuffers_[MAX_VERTEX_STREAMS];
  386. /// Stream frequencies by vertex buffer.
  387. unsigned streamFrequencies_[MAX_VERTEX_STREAMS];
  388. /// Stream offsets by vertex buffer.
  389. unsigned streamOffsets_[MAX_VERTEX_STREAMS];
  390. /// Index buffer in use.
  391. IndexBuffer* indexBuffer_;
  392. /// Vertex declaration in use.
  393. VertexDeclaration* vertexDeclaration_;
  394. /// Vertex shader in use.
  395. ShaderVariation* vertexShader_;
  396. /// Pixel shader in use.
  397. ShaderVariation* pixelShader_;
  398. /// All known shader parameters.
  399. HashMap<StringHash, ShaderParameter> shaderParameters_;
  400. /// Textures in use.
  401. Texture* textures_[MAX_TEXTURE_UNITS];
  402. /// Texture unit mappings.
  403. HashMap<String, TextureUnit> textureUnits_;
  404. /// Rendertargets in use.
  405. RenderSurface* renderTargets_[MAX_RENDERTARGETS];
  406. /// Depth-stencil surface in use.
  407. RenderSurface* depthStencil_;
  408. /// Backbuffer depth-stencil texture.
  409. SharedPtr<Texture2D> depthTexture_;
  410. /// View texture.
  411. Texture* viewTexture_;
  412. /// Viewport coordinates.
  413. IntRect viewport_;
  414. /// Texture anisotropy level.
  415. unsigned textureAnisotropy_;
  416. /// Blending mode.
  417. BlendMode blendMode_;
  418. /// Color write enable.
  419. bool colorWrite_;
  420. /// Hardware culling mode.
  421. CullMode cullMode_;
  422. /// Depth constant bias.
  423. float constantDepthBias_;
  424. /// Depth slope scaled bias.
  425. float slopeScaledDepthBias_;
  426. /// Depth compare mode.
  427. CompareMode depthTestMode_;
  428. /// Depth write enable flag.
  429. bool depthWrite_;
  430. /// Scissor test rectangle.
  431. IntRect scissorRect_;
  432. /// Scissor test enable flag.
  433. bool scissorTest_;
  434. /// Stencil test compare mode.
  435. CompareMode stencilTestMode_;
  436. /// Stencil operation on pass.
  437. StencilOp stencilPass_;
  438. /// Stencil operation on fail.
  439. StencilOp stencilFail_;
  440. /// Stencil operation on depth fail.
  441. StencilOp stencilZFail_;
  442. /// Stencil test enable flag.
  443. bool stencilTest_;
  444. /// Stencil test reference value.
  445. unsigned stencilRef_;
  446. /// Stencil compare bitmask.
  447. unsigned stencilCompareMask_;
  448. /// Stencil write bitmask.
  449. unsigned stencilWriteMask_;
  450. /// Default texture filtering mode.
  451. TextureFilterMode defaultTextureFilterMode_;
  452. /// Remembered shader parameter sources.
  453. const void* shaderParameterSources_[MAX_SHADER_PARAMETER_GROUPS];
  454. };
  455. /// Register Graphics library objects.
  456. void RegisterGraphicsLibrary(Context* context);