CmD3D9RenderSystem.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 __D3D9RENDERSYSTEM_H__
  25. #define __D3D9RENDERSYSTEM_H__
  26. #include "CmD3D9Prerequisites.h"
  27. #include "CmString.h"
  28. #include "CmConfigOptionMap.h"
  29. #include "CmRenderSystem.h"
  30. #include "CmRenderSystemCapabilities.h"
  31. #include "CmD3D9Mappings.h"
  32. namespace CamelotEngine
  33. {
  34. class D3D9DriverList;
  35. class D3D9Driver;
  36. class D3D9Device;
  37. class D3D9DeviceManager;
  38. class D3D9ResourceManager;
  39. /**
  40. Implementation of DirectX9 as a rendering system.
  41. */
  42. class _OgreD3D9Export D3D9RenderSystem : public RenderSystem
  43. {
  44. private:
  45. /// Direct3D
  46. IDirect3D9* mpD3D;
  47. // Stored options
  48. ConfigOptionMap mOptions;
  49. size_t mFSAASamples;
  50. String mFSAAHint;
  51. /// instance
  52. HINSTANCE mhInstance;
  53. /// List of D3D drivers installed (video cards)
  54. D3D9DriverList* mDriverList;
  55. /// Currently active driver
  56. D3D9Driver* mActiveD3DDriver;
  57. /// NVPerfHUD allowed?
  58. bool mUseNVPerfHUD;
  59. /// Per-stage constant support? (not in main caps since D3D specific & minor)
  60. bool mPerStageConstantSupport;
  61. /// Fast singleton access.
  62. static D3D9RenderSystem* msD3D9RenderSystem;
  63. /// structure holding texture unit settings for every stage
  64. struct sD3DTextureStageDesc
  65. {
  66. /// the type of the texture
  67. D3D9Mappings::eD3DTexType texType;
  68. /// which texCoordIndex to use
  69. size_t coordIndex;
  70. /// type of auto tex. calc. used
  71. TexCoordCalcMethod autoTexCoordType;
  72. /// Frustum, used if the above is projection
  73. const Frustum *frustum;
  74. /// texture
  75. IDirect3DBaseTexture9 *pTex;
  76. /// vertex texture
  77. IDirect3DBaseTexture9 *pVertexTex;
  78. } mTexStageDesc[CM_MAX_TEXTURE_LAYERS];
  79. D3D9DriverList* getDirect3DDrivers();
  80. void refreshD3DSettings();
  81. void refreshFSAAOptions();
  82. // state management methods, very primitive !!!
  83. HRESULT __SetRenderState(D3DRENDERSTATETYPE state, DWORD value);
  84. HRESULT __SetSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value);
  85. HRESULT __SetTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value);
  86. HRESULT __SetFloatRenderState(D3DRENDERSTATETYPE state, float value)
  87. {
  88. #if OGRE_DOUBLE_PRECISION == 1
  89. float temp = static_cast<float>(value);
  90. return __SetRenderState(state, *((LPDWORD)(&temp)));
  91. #else
  92. return __SetRenderState(state, *((LPDWORD)(&value)));
  93. #endif
  94. }
  95. /// return anisotropy level
  96. DWORD _getCurrentAnisotropy(size_t unit);
  97. /// check if a FSAA is supported
  98. bool _checkMultiSampleQuality(D3DMULTISAMPLE_TYPE type, DWORD *outQuality, D3DFORMAT format, UINT adapterNum, D3DDEVTYPE deviceType, BOOL fullScreen);
  99. D3D9HardwareBufferManager* mHardwareBufferManager;
  100. D3D9GpuProgramManager* mGpuProgramManager;
  101. D3D9HLSLProgramFactory* mHLSLProgramFactory;
  102. D3D9ResourceManager* mResourceManager;
  103. D3D9DeviceManager* mDeviceManager;
  104. size_t mLastVertexSourceCount;
  105. /// Internal method for populating the capabilities structure
  106. virtual RenderSystemCapabilities* createRenderSystemCapabilities() const;
  107. RenderSystemCapabilities* updateRenderSystemCapabilities(D3D9RenderWindow* renderWindow);
  108. /** See RenderSystem definition */
  109. virtual void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary);
  110. void convertVertexShaderCaps(RenderSystemCapabilities* rsc) const;
  111. void convertPixelShaderCaps(RenderSystemCapabilities* rsc) const;
  112. bool checkVertexTextureFormats(D3D9RenderWindow* renderWindow) const;
  113. HashMap<IDirect3DDevice9*, unsigned short> mCurrentLights;
  114. /// Saved last view matrix
  115. Matrix4 mViewMatrix;
  116. D3DXMATRIX mDxViewMat, mDxProjMat, mDxWorldMat;
  117. typedef vector<D3D9RenderWindow*>::type D3D9RenderWindowList;
  118. // List of additional windows after the first (swap chains)
  119. D3D9RenderWindowList mRenderWindows;
  120. /** Mapping of texture format -> DepthStencil. Used as cache by _getDepthStencilFormatFor
  121. */
  122. typedef HashMap<unsigned int, D3DFORMAT> DepthStencilHash;
  123. DepthStencilHash mDepthStencilHash;
  124. /** Mapping of depthstencil format -> depthstencil buffer
  125. Keep one depthstencil buffer around for every format that is used, it must be large
  126. enough to hold the largest rendering target.
  127. This is used as cache by _getDepthStencilFor.
  128. */
  129. struct ZBufferIdentifier
  130. {
  131. IDirect3DDevice9* device;
  132. D3DFORMAT format;
  133. D3DMULTISAMPLE_TYPE multisampleType;
  134. };
  135. struct ZBufferRef
  136. {
  137. IDirect3DSurface9 *surface;
  138. size_t width, height;
  139. };
  140. struct ZBufferIdentifierComparator
  141. {
  142. bool operator()(const ZBufferIdentifier& z0, const ZBufferIdentifier& z1) const;
  143. };
  144. typedef deque<ZBufferRef>::type ZBufferRefQueue;
  145. typedef map<ZBufferIdentifier, ZBufferRefQueue, ZBufferIdentifierComparator>::type ZBufferHash;
  146. ZBufferHash mZBufferHash;
  147. protected:
  148. void setClipPlanesImpl(const PlaneList& clipPlanes);
  149. public:
  150. // constructor
  151. D3D9RenderSystem( HINSTANCE hInstance );
  152. // destructor
  153. ~D3D9RenderSystem();
  154. virtual void initConfigOptions();
  155. // Overridden RenderSystem functions
  156. String validateConfigOptions();
  157. RenderWindow* _initialise( bool autoCreateWindow, const String& windowTitle = "OGRE Render Window" );
  158. /// @copydoc RenderSystem::_createRenderWindow
  159. RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height,
  160. bool fullScreen, const NameValuePairList *miscParams = 0);
  161. /// @copydoc RenderSystem::_createRenderWindows
  162. bool _createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions,
  163. RenderWindowList& createdWindows);
  164. /**
  165. * Set current render target to target, enabling its GL context if needed
  166. */
  167. void _setRenderTarget(RenderTarget *target);
  168. /// @copydoc RenderSystem::createMultiRenderTarget
  169. virtual MultiRenderTarget * createMultiRenderTarget(const String & name);
  170. String getErrorDescription( long errorNumber ) const;
  171. const String& getName() const;
  172. // Low-level overridden members
  173. void setConfigOption( const String &name, const String &value );
  174. void reinitialise();
  175. void shutdown();
  176. void setAmbientLight( float r, float g, float b );
  177. void setShadingType( ShadeOptions so );
  178. void setLightingEnabled( bool enabled );
  179. void destroyRenderTarget(const String& name);
  180. VertexElementType getColourVertexElementType() const;
  181. void setStencilCheckEnabled(bool enabled);
  182. void setStencilBufferParams(CompareFunction func = CMPF_ALWAYS_PASS,
  183. UINT32 refValue = 0, UINT32 mask = 0xFFFFFFFF,
  184. StencilOperation stencilFailOp = SOP_KEEP,
  185. StencilOperation depthFailOp = SOP_KEEP,
  186. StencilOperation passOp = SOP_KEEP,
  187. bool twoSidedOperation = false);
  188. void setNormaliseNormals(bool normalise);
  189. // Low-level overridden members, mainly for internal use
  190. void _setWorldMatrix( const Matrix4 &m );
  191. void _setViewMatrix( const Matrix4 &m );
  192. void _setProjectionMatrix( const Matrix4 &m );
  193. void _setSurfaceParams( const Color &ambient, const Color &diffuse, const Color &specular, const Color &emissive, float shininess, TrackVertexColourType tracking );
  194. void _setPointSpritesEnabled(bool enabled);
  195. void _setPointParameters(float size, bool attenuationEnabled,
  196. float constant, float linear, float quadratic, float minSize, float maxSize);
  197. void _setTexture(size_t unit, bool enabled, const TexturePtr &texPtr);
  198. void _setVertexTexture(size_t unit, const TexturePtr& tex);
  199. void _disableTextureUnit(size_t texUnit);
  200. void _setTextureCoordSet( size_t unit, size_t index );
  201. void _setTextureCoordCalculation(size_t unit, TexCoordCalcMethod m,
  202. const Frustum* frustum = 0);
  203. void _setTextureAddressingMode(size_t stage, const TextureState::UVWAddressingMode& uvw);
  204. void _setTextureBorderColour(size_t stage, const Color& colour);
  205. void _setTextureMipmapBias(size_t unit, float bias);
  206. void _setTextureMatrix( size_t unit, const Matrix4 &xform );
  207. void _setSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op );
  208. void _setSeparateSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendFactor sourceFactorAlpha, SceneBlendFactor destFactorAlpha, SceneBlendOperation op, SceneBlendOperation alphaOp );
  209. void _setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage );
  210. void _setViewport( Viewport *vp );
  211. void _beginFrame();
  212. virtual RenderSystemContext* _pauseFrame(void);
  213. virtual void _resumeFrame(RenderSystemContext* context);
  214. void _endFrame();
  215. void _setCullingMode( CullingMode mode );
  216. void _setDepthBufferParams( bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL );
  217. void _setDepthBufferCheckEnabled( bool enabled = true );
  218. void _setColourBufferWriteEnabled(bool red, bool green, bool blue, bool alpha);
  219. void _setDepthBufferWriteEnabled(bool enabled = true);
  220. void _setDepthBufferFunction( CompareFunction func = CMPF_LESS_EQUAL );
  221. void _setDepthBias(float constantBias, float slopeScaleBias);
  222. void _setFog( FogMode mode = FOG_NONE, const Color& colour = Color::White, float expDensity = 1.0, float linearStart = 0.0, float linearEnd = 1.0 );
  223. void _convertProjectionMatrix(const Matrix4& matrix,
  224. Matrix4& dest, bool forGpuProgram = false);
  225. void _makeProjectionMatrix(const Radian& fovy, float aspect, float nearPlane, float farPlane,
  226. Matrix4& dest, bool forGpuProgram = false);
  227. void _makeProjectionMatrix(float left, float right, float bottom, float top, float nearPlane,
  228. float farPlane, Matrix4& dest, bool forGpuProgram = false);
  229. void _makeOrthoMatrix(const Radian& fovy, float aspect, float nearPlane, float farPlane,
  230. Matrix4& dest, bool forGpuProgram = false);
  231. void _applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane,
  232. bool forGpuProgram);
  233. void _setPolygonMode(PolygonMode level);
  234. void _setTextureUnitFiltering(size_t unit, FilterType ftype, FilterOptions filter);
  235. void _setTextureLayerAnisotropy(size_t unit, unsigned int maxAnisotropy);
  236. void setVertexDeclaration(VertexDeclaration* decl);
  237. void setVertexBufferBinding(VertexBufferBinding* binding);
  238. void _render(const RenderOperation& op);
  239. /** See
  240. RenderSystem
  241. */
  242. void bindGpuProgram(GpuProgram* prg);
  243. /** See
  244. RenderSystem
  245. */
  246. void unbindGpuProgram(GpuProgramType gptype);
  247. /** See
  248. RenderSystem
  249. */
  250. void bindGpuProgramParameters(GpuProgramType gptype,
  251. GpuProgramParametersSharedPtr params, UINT16 variabilityMask);
  252. void bindGpuProgramPassIterationParameters(GpuProgramType gptype);
  253. void setScissorTest(bool enabled, size_t left = 0, size_t top = 0, size_t right = 800, size_t bottom = 600);
  254. void clearFrameBuffer(unsigned int buffers,
  255. const Color& colour = Color::Black,
  256. float depth = 1.0f, unsigned short stencil = 0);
  257. void setClipPlane (UINT16 index, float A, float B, float C, float D);
  258. void enableClipPlane (UINT16 index, bool enable);
  259. HardwareOcclusionQuery* createHardwareOcclusionQuery();
  260. float getHorizontalTexelOffset();
  261. float getVerticalTexelOffset();
  262. float getMinimumDepthInputValue();
  263. float getMaximumDepthInputValue();
  264. void registerThread();
  265. void unregisterThread();
  266. void preExtraThreadsStarted();
  267. void postExtraThreadsStarted();
  268. static D3D9ResourceManager* getResourceManager();
  269. static D3D9DeviceManager* getDeviceManager();
  270. static IDirect3D9* getDirect3D9();
  271. static UINT getResourceCreationDeviceCount();
  272. static IDirect3DDevice9* getResourceCreationDevice(UINT index);
  273. static IDirect3DDevice9* getActiveD3D9Device();
  274. /**
  275. Get the matching Z-Buffer identifier for a certain render target
  276. */
  277. ZBufferIdentifier getZBufferIdentifier(RenderTarget* rt);
  278. /** Check which depthStencil formats can be used with a certain pixel format,
  279. and return the best suited.
  280. */
  281. D3DFORMAT _getDepthStencilFormatFor(D3DFORMAT fmt);
  282. /** Get a depth stencil surface that is compatible with an internal pixel format and
  283. multisample type.
  284. @returns A directx surface, or 0 if there is no compatible depthstencil possible.
  285. */
  286. IDirect3DSurface9* _getDepthStencilFor(D3DFORMAT fmt, D3DMULTISAMPLE_TYPE multisample, DWORD multisample_quality, size_t width, size_t height);
  287. /** Clear all cached depth stencil surfaces
  288. */
  289. void _cleanupDepthStencils(IDirect3DDevice9* d3d9Device);
  290. /** Check whether or not filtering is supported for the precise texture format requested
  291. with the given usage options.
  292. */
  293. bool _checkTextureFilteringSupported(TextureType ttype, PixelFormat format, int usage);
  294. /// Take in some requested FSAA settings and output supported D3D settings
  295. void determineFSAASettings(IDirect3DDevice9* d3d9Device, size_t fsaa, const String& fsaaHint, D3DFORMAT d3dPixelFormat,
  296. bool fullScreen, D3DMULTISAMPLE_TYPE *outMultisampleType, DWORD *outMultisampleQuality);
  297. /// @copydoc RenderSystem::getDisplayMonitorCount
  298. unsigned int getDisplayMonitorCount() const;
  299. protected:
  300. /// Notify when a device has been lost.
  301. void notifyOnDeviceLost(D3D9Device* device);
  302. /// Notify when a device has been reset.
  303. void notifyOnDeviceReset(D3D9Device* device);
  304. typedef map<RenderTarget*, ZBufferRef>::type TargetDepthStencilMap;
  305. TargetDepthStencilMap mCheckedOutTextures;
  306. private:
  307. friend class D3D9Device;
  308. friend class D3D9DeviceManager;
  309. };
  310. }
  311. #endif