gfxDevice.h 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _GFXDEVICE_H_
  23. #define _GFXDEVICE_H_
  24. #ifndef _GFXADAPTER_H_
  25. #include "gfx/gfxAdapter.h"
  26. #endif
  27. #ifndef _GFXTARGET_H_
  28. #include "gfx/gfxTarget.h"
  29. #endif
  30. #ifndef _GFXVERTEXBUFFER_H_
  31. #include "gfx/gfxVertexBuffer.h"
  32. #endif
  33. #ifndef _GFXSTATEBLOCK_H_
  34. #include "gfx/gfxStateBlock.h"
  35. #endif
  36. #ifndef _GFXSHADER_H_
  37. #include "gfx/gfxShader.h"
  38. #endif
  39. #ifndef _GFXCUBEMAP_H_
  40. #include "gfx/gfxCubemap.h"
  41. #endif
  42. #ifndef _TDICTIONARY_H_
  43. #include "core/util/tDictionary.h"
  44. #endif
  45. #ifndef _TSIGNAL_H_
  46. #include "core/util/tSignal.h"
  47. #endif
  48. #ifndef _GFXDEVICESTATISTICS_H_
  49. #include "gfx/gfxDeviceStatistics.h"
  50. #endif
  51. #ifndef _MATHUTIL_FRUSTUM_H_
  52. #include "math/util/frustum.h"
  53. #endif
  54. class FontRenderBatcher;
  55. class GFont;
  56. class GFXCardProfiler;
  57. class GFXDrawUtil;
  58. class GFXFence;
  59. class GFXOcclusionQuery;
  60. class GFXPrimitiveBuffer;
  61. class GFXShader;
  62. class GFXStateBlock;
  63. class GFXShaderConstBuffer;
  64. class GFXTextureManager;
  65. // Global macro
  66. #define GFX GFXDevice::get()
  67. #define MAX_MRT_TARGETS 4
  68. //-----------------------------------------------------------------------------
  69. /// GFXDevice is the TSE graphics interface layer. This allows the TSE to
  70. /// do many things, such as use multiple render devices for multi-head systems,
  71. /// and allow a game to render in DirectX 9, OpenGL or any other API which has
  72. /// a GFX implementation seamlessly. There are many concepts in GFX device which
  73. /// may not be familiar to you, especially if you have not used DirectX.
  74. /// @n
  75. /// <b>Buffers</b>
  76. /// There are three types of buffers in GFX: vertex, index and primitive. Please
  77. /// note that index buffers are not accessable outside the GFX layer, they are wrapped
  78. /// by primitive buffers. Primitive buffers will be explained in detail later.
  79. /// Buffers are allocated and deallocated using their associated allocXBuffer and
  80. /// freeXBuffer methods on the device. When a buffer is allocated you pass in a
  81. /// pointer to, depending on the buffer, a vertex type pointer or a U16 pointer.
  82. /// During allocation, this pointer is set to the address of where you should
  83. /// copy in the information for this buffer. You must the tell the GFXDevice
  84. /// that the information is in, and it should prepare the buffer for use by calling
  85. /// the prepare method on it. Dynamic vertex buffer example:
  86. /// @code
  87. /// GFXVertexP *verts; // Making a buffer containing verticies with only position
  88. ///
  89. /// // Allocate a dynamic vertex buffer to hold 3 vertices and use *verts as the location to copy information into
  90. /// GFXVertexBufferHandle vb = GFX->allocVertexBuffer( 3, &verts, true );
  91. ///
  92. /// // Now set the information, we're making a triangle
  93. /// verts[0].point = Point3F( 200.f, 200.f, 0.f );
  94. /// verts[1].point = Point3F( 200.f, 400.f, 0.f );
  95. /// verts[2].point = Point3F( 400.f, 200.f, 0.f );
  96. ///
  97. /// // Tell GFX that the information is in and it should be made ready for use
  98. /// // Note that nothing is done with verts, this should not and MUST NOT be deleted
  99. /// // stored, or otherwise used after prepare is called.
  100. /// GFX->prepare( vb );
  101. ///
  102. /// // Because this is a dynamic vertex buffer, it is only assured to be valid until someone
  103. /// // else allocates a dynamic vertex buffer, so we will render it now
  104. /// GFX->setVertexBuffer( vb );
  105. /// GFX->drawPrimitive( GFXTriangleStrip, 0, 1 );
  106. ///
  107. /// // Now because this is a dynamic vertex buffer it MUST NOT BE FREED you are only
  108. /// // given a handle to a vertex buffer which belongs to the device
  109. /// @endcode
  110. ///
  111. /// To use a static vertex buffer, it is very similar, this is an example using a
  112. /// static primitive buffer:
  113. /// @n
  114. /// This takes place inside a constructor for a class which has a member variable
  115. /// called mPB which is the primitive buffer for the class instance.
  116. /// @code
  117. /// U16 *idx; // This is going to be where to write indices
  118. /// GFXPrimitiveInfo *primitiveInfo; // This will be where to write primitive information
  119. ///
  120. /// // Allocate a primitive buffer with 4 indices, and 1 primitive described for use
  121. /// mPB = GFX->allocPrimitiveBuffer( 4, &idx, 1, &primitiveInfo );
  122. ///
  123. /// // Write the index information, this is going to be for the outline of a triangle using
  124. /// // a line strip
  125. /// idx[0] = 0;
  126. /// idx[1] = 1;
  127. /// idx[2] = 2;
  128. /// idx[3] = 0;
  129. ///
  130. /// // Write the information for the primitive
  131. /// primitiveInfo->indexStart = 0; // Starting with index 0
  132. /// primitiveInfo->minVertex = 0; // The minimum vertex index is 0
  133. /// primitiveInfo->maxVertex = 3; // The maximum vertex index is 3
  134. /// primitiveInfo->primitiveCount = 3; // There are 3 lines we are drawing
  135. /// primitiveInfo->type = GFXLineStrip; // This primitive info describes a line strip
  136. /// @endcode
  137. /// The following code takes place in the destructor for the same class
  138. /// @code
  139. /// // Because this is a static buffer it's our responsibility to free it when we are done
  140. /// GFX->freePrimitiveBuffer( mPB );
  141. /// @endcode
  142. /// This last bit takes place in the rendering function for the class
  143. /// @code
  144. /// // You need to set a vertex buffer as well, primitive buffers contain indexing
  145. /// // information, not vertex information. This is so you could have, say, a static
  146. /// // vertex buffer, and a dynamic primitive buffer.
  147. ///
  148. /// // This sets the primitive buffer to the static buffer we allocated in the constructor
  149. /// GFX->setPrimitiveBuffer( mPB );
  150. ///
  151. /// // Draw the first primitive contained in the set primitive buffer, our primitive buffer
  152. /// // has only one primitive, so we could also technically call GFX->drawPrimitives(); and
  153. /// // get the same result.
  154. /// GFX->drawPrimitive( 0 );
  155. /// @endcode
  156. /// If you need any more examples on how to use these buffers please see the rest of the engine.
  157. /// @n
  158. /// <b>Primitive Buffers</b>
  159. /// @n
  160. /// Primitive buffers wrap and extend the concept of index buffers. The purpose of a primitive
  161. /// buffer is to let objects store all information they have to render their primitives in
  162. /// a central place. Say that a shape is made up of triangle strips and triangle fans, it would
  163. /// still have only one primitive buffer which contained primitive information for each strip
  164. /// and fan. It could then draw itself with one call.
  165. ///
  166. /// TO BE FINISHED LATER
  167. class GFXDevice
  168. {
  169. private:
  170. friend class GFXInit;
  171. friend class GFXPrimitiveBufferHandle;
  172. friend class GFXVertexBufferHandleBase;
  173. friend class GFXTextureObject;
  174. friend class GFXTexHandle;
  175. friend class GFXVertexFormat;
  176. friend class GFXTestFullscreenToggle;
  177. friend class TestGFXTextureCube;
  178. friend class TestGFXRenderTargetCube;
  179. friend class TestGFXRenderTargetStack;
  180. friend class GFXResource;
  181. friend class LightMatInstance; // For stencil interface
  182. //--------------------------------------------------------------------------
  183. // Static GFX interface
  184. //--------------------------------------------------------------------------
  185. public:
  186. enum GFXDeviceEventType
  187. {
  188. /// The device has been created, but not initialized
  189. deCreate,
  190. /// The device has been initialized
  191. deInit,
  192. /// The device is about to be destroyed.
  193. deDestroy,
  194. /// The device has started rendering a frame
  195. deStartOfFrame,
  196. /// The device is about to finish rendering a frame
  197. deEndOfFrame,
  198. };
  199. typedef Signal <bool (GFXDeviceEventType)> DeviceEventSignal;
  200. static DeviceEventSignal& getDeviceEventSignal();
  201. static GFXDevice *get() { return smGFXDevice; }
  202. static void initConsole();
  203. static bool destroy();
  204. static bool devicePresent() { return (smGFXDevice && smGFXDevice->getAdapterType() != NullDevice); }
  205. private:
  206. /// @name Device management variables
  207. /// @{
  208. static GFXDevice * smGFXDevice; ///< Global GFXDevice
  209. /// @}
  210. //--------------------------------------------------------------------------
  211. // Core GFX interface
  212. //--------------------------------------------------------------------------
  213. public:
  214. enum GFXDeviceRenderStyles
  215. {
  216. RS_Standard = 0,
  217. RS_StereoSideBySide = (1<<0),
  218. };
  219. private:
  220. /// Adapter for this device.
  221. GFXAdapter mAdapter;
  222. protected:
  223. /// List of valid video modes for this device.
  224. Vector<GFXVideoMode> mVideoModes;
  225. /// The CardProfiler for this device.
  226. GFXCardProfiler *mCardProfiler;
  227. /// Head of the resource list.
  228. ///
  229. /// @see GFXResource
  230. GFXResource *mResourceListHead;
  231. /// Set once the device is active.
  232. bool mCanCurrentlyRender;
  233. /// Set if we're in a mode where we want rendering to occur.
  234. bool mAllowRender;
  235. /// The style of rendering that is to be performed, based on GFXDeviceRenderStyles
  236. U32 mCurrentRenderStyle;
  237. /// The current projection offset. May be used during side-by-side rendering, for example.
  238. Point2F mCurrentProjectionOffset;
  239. /// Eye offset used when using a stereo rendering style
  240. Point3F mStereoEyeOffset;
  241. /// This will allow querying to see if a device is initialized and ready to
  242. /// have operations performed on it.
  243. bool mInitialized;
  244. /// This is called before this, or any other device, is deleted in the global destroy()
  245. /// method. It allows the device to clean up anything while everything is still valid.
  246. virtual void preDestroy();
  247. /// Set the adapter that this device is using. For use by GFXInit::createDevice only.
  248. virtual void setAdapter(const GFXAdapter& adapter) { mAdapter = adapter; }
  249. /// Notify GFXDevice that we are initialized
  250. virtual void deviceInited();
  251. public:
  252. GFXDevice();
  253. virtual ~GFXDevice();
  254. /// Initialize this GFXDevice, optionally specifying a platform window to
  255. /// bind to.
  256. virtual void init( const GFXVideoMode &mode, PlatformWindow *window = NULL ) = 0;
  257. /// Returns true if the scene has begun and its
  258. /// safe to make rendering calls.
  259. /// @see beginScene
  260. /// @see endScene
  261. bool canCurrentlyRender() const { return mCanCurrentlyRender; }
  262. void setAllowRender( bool render ) { mAllowRender = render; }
  263. inline bool allowRender() const { return mAllowRender; }
  264. /// Retrieve the current rendering style based on GFXDeviceRenderStyles
  265. U32 getCurrentRenderStyle() const { return mCurrentRenderStyle; }
  266. /// Set the current rendering style, based on GFXDeviceRenderStyles
  267. void setCurrentRenderStyle(U32 style) { mCurrentRenderStyle = style; }
  268. /// Set the current projection offset used during stereo rendering
  269. const Point2F& getCurrentProjectionOffset() { return mCurrentProjectionOffset; }
  270. /// Get the current projection offset used during stereo rendering
  271. void setCurrentProjectionOffset(const Point2F& offset) { mCurrentProjectionOffset = offset; }
  272. /// Get the current eye offset used during stereo rendering
  273. const Point3F& getStereoEyeOffset() { return mStereoEyeOffset; }
  274. /// Set the current eye offset used during stereo rendering
  275. void setStereoEyeOffset(const Point3F& offset) { mStereoEyeOffset = offset; }
  276. GFXCardProfiler* getCardProfiler() const { return mCardProfiler; }
  277. /// Returns active graphics adapter type.
  278. virtual GFXAdapterType getAdapterType()=0;
  279. /// Returns the Adapter that was used to create this device
  280. virtual const GFXAdapter& getAdapter() { return mAdapter; }
  281. /// @}
  282. /// @name Debug Methods
  283. /// @{
  284. virtual void enterDebugEvent(ColorI color, const char *name) = 0;
  285. virtual void leaveDebugEvent() = 0;
  286. virtual void setDebugMarker(ColorI color, const char *name) = 0;
  287. /// @}
  288. /// @name Resource debug methods
  289. /// @{
  290. /// Lists how many of each GFX resource (e.g. textures, texture targets, shaders, etc.) GFX is aware of
  291. /// @param unflaggedOnly If true, this method only counts unflagged resources
  292. virtual void listResources(bool unflaggedOnly);
  293. /// Flags all resources GFX is currently aware of
  294. virtual void flagCurrentResources();
  295. /// Clears the flag on all resources GFX is currently aware of
  296. virtual void clearResourceFlags();
  297. /// Dumps a description of the specified resource types to the console
  298. /// @param resNames A string of space separated class names (e.g. "GFXTextureObject GFXTextureTarget GFXShader")
  299. /// to describe to the console
  300. /// @param file A path to the file to write the descriptions to. If it is NULL or "", descriptions are
  301. /// written to the console.
  302. /// @param unflaggedOnly If true, this method only counts unflagged resources
  303. /// @note resNames is case sensitive because there is no dStristr function.
  304. virtual void describeResources(const char* resName, const char* file, bool unflaggedOnly);
  305. /// Returns the current GFXDeviceStatistics, stats are cleared every ::beginScene call.
  306. GFXDeviceStatistics* getDeviceStatistics() { return &mDeviceStatistics; }
  307. protected:
  308. GFXDeviceStatistics mDeviceStatistics;
  309. /// This is a helper method for describeResourcesToFile. It walks through the
  310. /// GFXResource list and sorts it by item type, putting the resources into the proper vector.
  311. /// @see describeResources
  312. virtual void fillResourceVectors(const char* resNames, bool unflaggedOnly, Vector<GFXResource*> &textureObjects,
  313. Vector<GFXResource*> &textureTargets, Vector<GFXResource*> &windowTargets, Vector<GFXResource*> &vertexBuffers,
  314. Vector<GFXResource*> &primitiveBuffers, Vector<GFXResource*> &fences, Vector<GFXResource*> &cubemaps,
  315. Vector<GFXResource*> &shaders, Vector<GFXResource*> &stateblocks);
  316. public:
  317. /// @}
  318. /// @name Video Mode Functions
  319. /// @{
  320. /// Enumerates the supported video modes of the device
  321. virtual void enumerateVideoModes() = 0;
  322. /// Returns the video mode list.
  323. /// @see GFXVideoMode
  324. const Vector<GFXVideoMode>* const getVideoModeList() const { return &mVideoModes; }
  325. /// Returns the first format from the list which meets all
  326. /// the criteria of the texture profile and query options.
  327. virtual GFXFormat selectSupportedFormat(GFXTextureProfile *profile,
  328. const Vector<GFXFormat> &formats, bool texture, bool mustblend, bool mustfilter) = 0;
  329. /// @}
  330. //-----------------------------------------------------------------------------
  331. protected:
  332. /// @name State tracking variables
  333. /// @{
  334. /// Set if ANY state is dirty, including matrices or primitive buffers.
  335. bool mStateDirty;
  336. enum TexDirtyType
  337. {
  338. GFXTDT_Normal,
  339. GFXTDT_Cube
  340. };
  341. GFXTexHandle mCurrentTexture[TEXTURE_STAGE_COUNT];
  342. GFXTexHandle mNewTexture[TEXTURE_STAGE_COUNT];
  343. GFXCubemapHandle mCurrentCubemap[TEXTURE_STAGE_COUNT];
  344. GFXCubemapHandle mNewCubemap[TEXTURE_STAGE_COUNT];
  345. TexDirtyType mTexType[TEXTURE_STAGE_COUNT];
  346. bool mTextureDirty[TEXTURE_STAGE_COUNT];
  347. bool mTexturesDirty;
  348. // This maps a GFXStateBlockDesc hash value to a GFXStateBlockRef
  349. typedef Map<U32, GFXStateBlockRef> StateBlockMap;
  350. StateBlockMap mCurrentStateBlocks;
  351. // This tracks whether or not our state block is dirty.
  352. bool mStateBlockDirty;
  353. GFXStateBlockRef mCurrentStateBlock;
  354. GFXStateBlockRef mNewStateBlock;
  355. GFXShaderConstBuffer *mCurrentShaderConstBuffer;
  356. /// A global forced wireframe mode.
  357. static bool smWireframe;
  358. /// The global vsync state.
  359. static bool smDisableVSync;
  360. /// The forced shader model version if non-zero.
  361. static F32 smForcedPixVersion;
  362. /// Disable all hardware occlusion queries causing
  363. /// them to return only the visibile state.
  364. static bool smDisableOcclusionQuery;
  365. /// @}
  366. /// @name Light Tracking
  367. /// @{
  368. GFXLightInfo mCurrentLight[LIGHT_STAGE_COUNT];
  369. bool mCurrentLightEnable[LIGHT_STAGE_COUNT];
  370. bool mLightDirty[LIGHT_STAGE_COUNT];
  371. bool mLightsDirty;
  372. ColorF mGlobalAmbientColor;
  373. bool mGlobalAmbientColorDirty;
  374. /// @}
  375. /// @name Fixed function material tracking
  376. /// @{
  377. GFXLightMaterial mCurrentLightMaterial;
  378. bool mLightMaterialDirty;
  379. /// @}
  380. /// @name Bitmap modulation and color stack
  381. /// @{
  382. ///
  383. /// @}
  384. /// @see getDeviceSwizzle32
  385. Swizzle<U8, 4> *mDeviceSwizzle32;
  386. /// @see getDeviceSwizzle24
  387. Swizzle<U8, 3> *mDeviceSwizzle24;
  388. //-----------------------------------------------------------------------------
  389. /// @name Matrix managing variables
  390. /// @{
  391. ///
  392. MatrixF mWorldMatrix[WORLD_STACK_MAX];
  393. bool mWorldMatrixDirty;
  394. S32 mWorldStackSize;
  395. MatrixF mProjectionMatrix;
  396. bool mProjectionMatrixDirty;
  397. MatrixF mViewMatrix;
  398. bool mViewMatrixDirty;
  399. MatrixF mTextureMatrix[TEXTURE_STAGE_COUNT];
  400. bool mTextureMatrixDirty[TEXTURE_STAGE_COUNT];
  401. bool mTextureMatrixCheckDirty;
  402. /// @}
  403. /// @name Current frustum planes
  404. /// @{
  405. ///
  406. Frustum mFrustum;
  407. //-----------------------------------------------------------------------------
  408. /// @name Stateblock functions
  409. /// @{
  410. /// Called by GFXDevice to create a device specific stateblock
  411. virtual GFXStateBlockRef createStateBlockInternal(const GFXStateBlockDesc& desc) = 0;
  412. /// Called by GFXDevice to actually set a stateblock.
  413. /// @param force If true, set all states
  414. virtual void setStateBlockInternal(GFXStateBlock* block, bool force) = 0;
  415. /// @}
  416. /// Called by base GFXDevice to actually set a const buffer
  417. virtual void setShaderConstBufferInternal(GFXShaderConstBuffer* buffer) = 0;
  418. virtual void setTextureInternal(U32 textureUnit, const GFXTextureObject*texture) = 0;
  419. virtual void setLightInternal(U32 lightStage, const GFXLightInfo light, bool lightEnable) = 0;
  420. virtual void setGlobalAmbientInternal(ColorF color) = 0;
  421. virtual void setLightMaterialInternal(const GFXLightMaterial mat) = 0;
  422. virtual bool beginSceneInternal() = 0;
  423. virtual void endSceneInternal() = 0;
  424. /// @name State Initialization.
  425. /// @{
  426. /// State initialization. This MUST BE CALLED in setVideoMode after the device
  427. /// is created.
  428. virtual void initStates() = 0;
  429. /// @}
  430. //-----------------------------------------------------------------------------
  431. /// This function must be implemented differently per
  432. /// API and it should set ONLY the current matrix.
  433. /// For example, in OpenGL, there should be NO matrix stack
  434. /// activity, all the stack stuff is managed in the GFX layer.
  435. ///
  436. /// OpenGL does not have separate world and
  437. /// view matrices. It has ModelView which is world * view.
  438. /// You must take this into consideration.
  439. ///
  440. /// @param mtype Which matrix to set, world/view/projection
  441. /// @param mat Matrix to assign
  442. virtual void setMatrix( GFXMatrixType mtype, const MatrixF &mat ) = 0;
  443. //-----------------------------------------------------------------------------
  444. protected:
  445. /// @name Buffer Allocation
  446. /// These methods are implemented per-device and are called by the GFX layer
  447. /// when a user calls an alloc
  448. ///
  449. /// @note Primitive Buffers are NOT implemented per device, they wrap index buffers
  450. /// @{
  451. /// This allocates a vertex buffer and returns a pointer to the allocated buffer.
  452. /// This function should not be called directly - rather it should be used by
  453. /// the GFXVertexBufferHandle class.
  454. virtual GFXVertexBuffer *allocVertexBuffer( U32 numVerts,
  455. const GFXVertexFormat *vertexFormat,
  456. U32 vertSize,
  457. GFXBufferType bufferType ) = 0;
  458. /// Called from GFXVertexFormat to allocate the hardware
  459. /// specific vertex declaration for rendering.
  460. virtual GFXVertexDecl* allocVertexDecl( const GFXVertexFormat *vertexFormat ) = 0;
  461. /// Sets the current vertex declaration on the device.
  462. virtual void setVertexDecl( const GFXVertexDecl *decl ) = 0;
  463. /// Sets the vertex buffer on the device.
  464. virtual void setVertexStream( U32 stream, GFXVertexBuffer *buffer ) = 0;
  465. /// Set the vertex stream frequency on the device.
  466. virtual void setVertexStreamFrequency( U32 stream, U32 frequency ) = 0;
  467. /// The maximum number of supported vertex streams which
  468. /// may be more than the device supports.
  469. static const U32 VERTEX_STREAM_COUNT = 4;
  470. StrongRefPtr<GFXVertexBuffer> mCurrentVertexBuffer[VERTEX_STREAM_COUNT];
  471. bool mVertexBufferDirty[VERTEX_STREAM_COUNT];
  472. U32 mVertexBufferFrequency[VERTEX_STREAM_COUNT];
  473. bool mVertexBufferFrequencyDirty[VERTEX_STREAM_COUNT];
  474. const GFXVertexDecl *mCurrVertexDecl;
  475. bool mVertexDeclDirty;
  476. StrongRefPtr<GFXPrimitiveBuffer> mCurrentPrimitiveBuffer;
  477. bool mPrimitiveBufferDirty;
  478. /// This allocates a primitive buffer and returns a pointer to the allocated buffer.
  479. /// A primitive buffer's type argument refers to the index data - the primitive data will
  480. /// always be preserved from call to call.
  481. ///
  482. /// @note All index buffers use unsigned 16-bit indices.
  483. virtual GFXPrimitiveBuffer *allocPrimitiveBuffer( U32 numIndices,
  484. U32 numPrimitives,
  485. GFXBufferType bufferType ) = 0;
  486. /// @}
  487. //---------------------------------------
  488. // SFX buffer
  489. //---------------------------------------
  490. protected:
  491. GFXTexHandle mFrontBuffer[2];
  492. U32 mCurrentFrontBufferIdx;
  493. //---------------------------------------
  494. // Render target related
  495. //---------------------------------------
  496. /// A stack of previously active render targets.
  497. Vector<GFXTargetRef> mRTStack;
  498. /// The current render target which may or may not
  499. /// not be yet activated.
  500. /// @see mRTDirty
  501. GFXTargetRef mCurrentRT;
  502. /// This tracks a previously activated render target
  503. /// which need to be deactivated.
  504. GFXTargetRef mRTDeactivate;
  505. /// This is set when the current and/or deactivate render
  506. /// targets have changed and the device need to update
  507. /// its state on the next draw/clear.
  508. bool mRTDirty;
  509. /// Updates the render targets and viewport in a device
  510. /// specific manner when they are dirty.
  511. virtual void _updateRenderTargets() = 0;
  512. /// The current viewport rect.
  513. RectI mViewport;
  514. /// If true the viewport has been changed and
  515. /// it must be updated on the next draw/clear.
  516. bool mViewportDirty;
  517. public:
  518. /// @name Texture functions
  519. /// @{
  520. protected:
  521. GFXTextureManager * mTextureManager;
  522. public:
  523. virtual GFXCubemap * createCubemap() = 0;
  524. inline GFXTextureManager *getTextureManager()
  525. {
  526. return mTextureManager;
  527. }
  528. ///@}
  529. /// Swizzle to convert 32bpp bitmaps from RGBA to the native device format.
  530. const Swizzle<U8, 4> *getDeviceSwizzle32() const
  531. {
  532. return mDeviceSwizzle32;
  533. }
  534. /// Swizzle to convert 24bpp bitmaps from RGB to the native device format.
  535. const Swizzle<U8, 3> *getDeviceSwizzle24() const
  536. {
  537. return mDeviceSwizzle24;
  538. }
  539. /// @name Render Target functions
  540. /// @{
  541. /// Allocate a target for doing render to texture operations, with no
  542. /// depth/stencil buffer.
  543. virtual GFXTextureTarget *allocRenderToTextureTarget()=0;
  544. /// Allocate a target for a given window.
  545. virtual GFXWindowTarget *allocWindowTarget(PlatformWindow *window)=0;
  546. /// Store the current render target to restore later.
  547. void pushActiveRenderTarget();
  548. /// Restore the previous render target.
  549. void popActiveRenderTarget();
  550. /// Assign a new active render target.
  551. void setActiveRenderTarget( GFXTarget *target, bool updateViewport=true );
  552. /// Returns the current active render target.
  553. inline GFXTarget* getActiveRenderTarget() { return mCurrentRT; }
  554. ///@}
  555. /// @name Shader functions
  556. /// @{
  557. virtual F32 getPixelShaderVersion() const = 0;
  558. virtual void setPixelShaderVersion( F32 version ) = 0;
  559. /// Returns the number of texture samplers that can be used in a shader rendering pass
  560. virtual U32 getNumSamplers() const = 0;
  561. /// Returns the number of simultaneous render targets supported by the device.
  562. virtual U32 getNumRenderTargets() const = 0;
  563. virtual void setShader( GFXShader *shader ) {}
  564. virtual void disableShaders() {}
  565. /// Set the buffer! (Actual set happens on the next draw call, just like textures, state blocks, etc)
  566. void setShaderConstBuffer(GFXShaderConstBuffer* buffer);
  567. /// Creates a new empty shader which must be initialized
  568. /// and deleted by the caller.
  569. /// @see GFXShader::init
  570. virtual GFXShader* createShader() = 0;
  571. /// @}
  572. //-----------------------------------------------------------------------------
  573. /// @name Rendering methods
  574. /// @{
  575. ///
  576. virtual void clear( U32 flags, ColorI color, F32 z, U32 stencil ) = 0;
  577. virtual bool beginScene();
  578. virtual void endScene();
  579. virtual GFXTexHandle & getFrontBuffer(){ return mFrontBuffer[mCurrentFrontBufferIdx]; }
  580. void setPrimitiveBuffer( GFXPrimitiveBuffer *buffer );
  581. /// Sets the vertex buffer.
  582. ///
  583. /// When setting the stream 0 vertex buffer it will automatically
  584. /// set its associated vertex format as the active format.
  585. ///
  586. /// @param buffer The vertex buffer or NULL to clear the buffer.
  587. /// @param stream The stream index of the vertex source stream to place the buffer.
  588. /// @param frequency The stream frequency of the vertex buffer.
  589. void setVertexBuffer( GFXVertexBuffer *buffer, U32 stream = 0, U32 frequency = 0 );
  590. /// Sets the current vertex format.
  591. ///
  592. /// This should only be used if the vertex format of the stream 0 vertex
  593. /// buffer is different from the one associated to it. Typically this
  594. /// is used when rendering from multiple vertex streams.
  595. ///
  596. void setVertexFormat( const GFXVertexFormat *vertexFormat );
  597. virtual void drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount ) = 0;
  598. /// The parameters to drawIndexedPrimitive are somewhat complicated. From a raw-data stand point
  599. /// they evaluate to something like the following:
  600. /// @code
  601. /// U16 indicies[] = { 0, 1, 2, 1, 0, 0, 2 };
  602. /// Point3F verts[] = { Point3F( 0.0f, 0.0f, 0.0f ), Point3F( 0.0f, 1.0f, 0.0f ), Point3F( 0.0f, 0.0f, 1.0f ) };
  603. ///
  604. /// GFX->drawIndexedPrimitive( GFXLineList, // Drawing a list of lines, each line is two verts
  605. /// 0, // vertex 0 will be referenced so minIndex = 0
  606. /// 3, // 3 verticies will be used for this draw call
  607. /// 1, // We want index 1 to be the first index used, so indicies 1-6 will be used
  608. /// 3 // Drawing 3 LineList primitives, meaning 6 verts will be drawn
  609. /// );
  610. ///
  611. /// U16 *idxPtr = &indicies[1]; // 1 = startIndex, so the pointer is offset such that:
  612. /// // idxPtr[0] is the same as indicies[1]
  613. ///
  614. /// U32 numVertsToDrawFromBuffer = primitiveCount * 2; // 2 verts define a line in the GFXLineList primitive type (6)
  615. /// @endcode
  616. ///
  617. /// @param primType Type of primitive to draw
  618. ///
  619. /// @param startVertex This defines index zero. Its the offset from the start of
  620. /// the vertex buffer to the first vertex.
  621. ///
  622. /// @param minIndex The smallest index into the vertex stream which will be used for this draw call.
  623. /// This is a zero based index relative to startVertex. It is strictly a performance
  624. /// hint for implementations. No vertex below minIndex will be referenced by this draw
  625. /// call. For device implementors, this should _not_ be used to offset the vertex buffer,
  626. /// or index buffer.
  627. ///
  628. /// @param numVerts The number of verticies which will be referenced in this draw call. This is not
  629. /// the number of verticies which will be drawn. That is a function of 'primType' and
  630. /// 'primitiveCount'.
  631. ///
  632. /// @param startIndex An offset from the start of the index buffer to specify where to start. If
  633. /// 'idxBuffer' is a pointer to an array of integers, this could be written as
  634. /// int *offsetIdx = idxBuffer + startIndex;
  635. ///
  636. /// @param primitiveCount The number of primitives of type 'primType' to draw.
  637. ///
  638. virtual void drawIndexedPrimitive( GFXPrimitiveType primType,
  639. U32 startVertex,
  640. U32 minIndex,
  641. U32 numVerts,
  642. U32 startIndex,
  643. U32 primitiveCount ) = 0;
  644. void drawPrimitive( const GFXPrimitive &prim );
  645. void drawPrimitive( U32 primitiveIndex );
  646. void drawPrimitives();
  647. void drawPrimitiveBuffer( GFXPrimitiveBuffer *buffer );
  648. /// @}
  649. //-----------------------------------------------------------------------------
  650. /// Allocate a fence. The API specific implementation of GFXDevice is responsible
  651. /// to make sure that the proper type is used. GFXGeneralFence should work in
  652. /// all cases.
  653. virtual GFXFence *createFence() = 0;
  654. /// Returns a hardware occlusion query object or NULL
  655. /// if this device does not support them.
  656. virtual GFXOcclusionQuery* createOcclusionQuery() { return NULL; }
  657. /// @name Light Settings
  658. /// NONE of these should be overridden by API implementations
  659. /// because of the state caching stuff.
  660. /// @{
  661. void setLight(U32 stage, GFXLightInfo* light);
  662. void setLightMaterial(GFXLightMaterial mat);
  663. void setGlobalAmbientColor(ColorF color);
  664. /// @}
  665. /// @name Texture State Settings
  666. /// NONE of these should be overridden by API implementations
  667. /// because of the state caching stuff.
  668. /// @{
  669. ///
  670. void setTexture(U32 stage, GFXTextureObject*texture);
  671. void setCubeTexture( U32 stage, GFXCubemap *cubemap );
  672. inline GFXTextureObject* getCurrentTexture( U32 stage ) { return mCurrentTexture[stage]; }
  673. /// @}
  674. /// @name State Block Interface
  675. /// @{
  676. /// Creates a state block object based on the desc passed in. This object
  677. /// represents an immutable state.
  678. virtual GFXStateBlockRef createStateBlock( const GFXStateBlockDesc &desc );
  679. /// Sets the current stateblock (actually activated in ::updateStates)
  680. virtual void setStateBlock( GFXStateBlock *block );
  681. /// This sets a stateblock directly from the description
  682. /// structure. Its acceptable to use this for debug rendering
  683. /// and other low frequency rendering tasks.
  684. virtual void setStateBlockByDesc( const GFXStateBlockDesc &desc );
  685. /// @}
  686. /// @name General state interface
  687. /// @{
  688. /// Sets the dirty Render/Texture/Sampler states from the caching system
  689. void updateStates(bool forceSetAll = false);
  690. /// Returns the forced global wireframe state.
  691. static bool getWireframe() { return smWireframe; }
  692. /// Returns true if the occlusion query is disabled.
  693. static bool getDisableOcclusionQuery() { return smDisableOcclusionQuery; }
  694. /// @}
  695. //-----------------------------------------------------------------------------
  696. /// @name Matrix interface
  697. /// @{
  698. /// Sets the top of the world matrix stack
  699. /// @param newWorld New world matrix to set
  700. void setWorldMatrix( const MatrixF &newWorld );
  701. /// Gets the matrix on the top of the world matrix stack
  702. inline const MatrixF &getWorldMatrix() const { return mWorldMatrix[mWorldStackSize]; }
  703. /// Pushes the world matrix stack and copies the current top
  704. /// matrix to the new top of the stack
  705. void pushWorldMatrix();
  706. /// Pops the world matrix stack
  707. void popWorldMatrix();
  708. /// Sets the projection matrix
  709. /// @param newProj New projection matrix to set
  710. void setProjectionMatrix( const MatrixF &newProj );
  711. /// Gets the projection matrix
  712. inline const MatrixF &getProjectionMatrix() const { return mProjectionMatrix; }
  713. /// Sets the view matrix
  714. /// @param newView New view matrix to set
  715. void setViewMatrix( const MatrixF &newView );
  716. /// Gets the view matrix
  717. inline const MatrixF &getViewMatrix() const { return mViewMatrix; }
  718. /// Multiplies the matrix at the top of the world matrix stack by a matrix
  719. /// and replaces the top of the matrix stack with the result
  720. /// @param mat Matrix to multiply
  721. void multWorld( const MatrixF &mat );
  722. /// Set texture matrix for a sampler
  723. void setTextureMatrix( const U32 stage, const MatrixF &texMat );
  724. /// Set an area of the target to render to.
  725. void setViewport( const RectI &rect );
  726. /// Get the current area of the target we will render to.
  727. const RectI &getViewport() const { return mViewport; }
  728. virtual void setClipRect( const RectI &rect ) = 0;
  729. virtual const RectI &getClipRect() const = 0;
  730. /// Set the projection frustum.
  731. ///
  732. /// @see MathUtils::makeFrustum()
  733. virtual void setFrustum( F32 left, F32 right,
  734. F32 bottom, F32 top,
  735. F32 nearPlane, F32 farPlane,
  736. bool bRotate = true);
  737. ///
  738. virtual void setFrustum( const Frustum& frust,
  739. bool bRotate = true );
  740. /// Get the projection frustum.
  741. void getFrustum( F32 *left,
  742. F32 *right,
  743. F32 *bottom,
  744. F32 *top,
  745. F32 *nearPlane,
  746. F32 *farPlane,
  747. bool *isOrtho ) const;
  748. /// Get the projection frustum.
  749. const Frustum& getFrustum() const { return mFrustum; }
  750. /// This will construct and apply an orthographic projection matrix with the provided parameters
  751. /// @param doRotate If set to true, the resulting matrix will be rotated PI/2 around the X axis
  752. // for support in tsShapeInstance. You probably want to leave this as 'false'.
  753. void setOrtho(F32 left, F32 right, F32 bottom, F32 top, F32 nearPlane, F32 farPlane, bool doRotate = false);
  754. /// Return true if the current frustum uses orthographic projection rather than perspective projection.
  755. bool isFrustumOrtho() const { return mFrustum.isOrtho(); }
  756. /// @}
  757. /// Returns the scale for converting world space
  758. /// units to screen space units... aka pixels.
  759. ///
  760. /// This is the true scale which is best used for GUI
  761. /// drawing. For doing lod calculations you should be
  762. /// using the functions in SceneState which is adjusted
  763. /// for special cases like shadows and reflections.
  764. ///
  765. /// @see SceneState::getWorldToScreenScale()
  766. /// @see SceneState::projectRadius()
  767. ///
  768. Point2F getWorldToScreenScale() const;
  769. public:
  770. enum GenericShaderType
  771. {
  772. GSColor = 0,
  773. GSTexture,
  774. GSModColorTexture,
  775. GSAddColorTexture,
  776. GSTargetRestore,
  777. GS_COUNT
  778. };
  779. /// This is a helper function to set a default shader for rendering GUI elements
  780. /// on systems which do not support fixed-function operations as well as for
  781. /// things which need just generic position/texture/color shaders
  782. ///
  783. /// @param type Type of generic shader, add your own if you need
  784. virtual void setupGenericShaders( GenericShaderType type = GSColor ) {};
  785. /// Get the fill convention for this device
  786. virtual F32 getFillConventionOffset() const = 0;
  787. virtual U32 getMaxDynamicVerts() = 0;
  788. virtual U32 getMaxDynamicIndices() = 0;
  789. virtual void doParanoidStateCheck(){};
  790. /// Get access to this device's drawing utility class.
  791. GFXDrawUtil *getDrawUtil();
  792. #ifndef TORQUE_SHIPPING
  793. /// This is a method designed for debugging. It will allow you to dump the states
  794. /// in the render manager out to a file so that it can be diffed and examined.
  795. void dumpStates( const char *fileName ) const;
  796. #else
  797. void dumpStates( const char *fileName ) const {};
  798. #endif
  799. protected:
  800. GFXDrawUtil *mDrawer;
  801. };
  802. //-----------------------------------------------------------------------------
  803. // Matrix interface
  804. inline void GFXDevice::setWorldMatrix( const MatrixF &newWorld )
  805. {
  806. mWorldMatrixDirty = true;
  807. mStateDirty = true;
  808. mWorldMatrix[mWorldStackSize] = newWorld;
  809. }
  810. inline void GFXDevice::pushWorldMatrix()
  811. {
  812. mWorldMatrixDirty = true;
  813. mStateDirty = true;
  814. mWorldStackSize++;
  815. AssertFatal( mWorldStackSize < WORLD_STACK_MAX, "GFX: Exceeded world matrix stack size" );
  816. mWorldMatrix[mWorldStackSize] = mWorldMatrix[mWorldStackSize - 1];
  817. }
  818. inline void GFXDevice::popWorldMatrix()
  819. {
  820. mWorldMatrixDirty = true;
  821. mStateDirty = true;
  822. mWorldStackSize--;
  823. AssertFatal( mWorldStackSize >= 0, "GFX: Negative WorldStackSize!" );
  824. }
  825. inline void GFXDevice::multWorld( const MatrixF &mat )
  826. {
  827. mWorldMatrixDirty = true;
  828. mStateDirty = true;
  829. mWorldMatrix[mWorldStackSize].mul(mat);
  830. }
  831. inline void GFXDevice::setProjectionMatrix( const MatrixF &newProj )
  832. {
  833. mProjectionMatrixDirty = true;
  834. mStateDirty = true;
  835. mProjectionMatrix = newProj;
  836. }
  837. inline void GFXDevice::setViewMatrix( const MatrixF &newView )
  838. {
  839. mStateDirty = true;
  840. mViewMatrixDirty = true;
  841. mViewMatrix = newView;
  842. }
  843. inline void GFXDevice::setTextureMatrix( const U32 stage, const MatrixF &texMat )
  844. {
  845. AssertFatal( stage < TEXTURE_STAGE_COUNT, "Out of range texture sampler" );
  846. mStateDirty = true;
  847. mTextureMatrixDirty[stage] = true;
  848. mTextureMatrix[stage] = texMat;
  849. mTextureMatrixCheckDirty = true;
  850. }
  851. //-----------------------------------------------------------------------------
  852. // Buffer management
  853. inline void GFXDevice::setVertexBuffer( GFXVertexBuffer *buffer, U32 stream, U32 frequency )
  854. {
  855. AssertFatal( stream < VERTEX_STREAM_COUNT, "GFXDevice::setVertexBuffer - Bad stream index!" );
  856. if ( buffer && stream == 0 )
  857. setVertexFormat( &buffer->mVertexFormat );
  858. if ( buffer != mCurrentVertexBuffer[stream] )
  859. {
  860. mCurrentVertexBuffer[stream] = buffer;
  861. mVertexBufferDirty[stream] = true;
  862. mStateDirty = true;
  863. }
  864. if ( mVertexBufferFrequency[stream] != frequency )
  865. {
  866. mVertexBufferFrequency[stream] = frequency;
  867. mVertexBufferFrequencyDirty[stream] = true;
  868. mStateDirty = true;
  869. }
  870. }
  871. inline void GFXDevice::setVertexFormat( const GFXVertexFormat *vertexFormat )
  872. {
  873. if ( vertexFormat->getDecl() == mCurrVertexDecl )
  874. return;
  875. mCurrVertexDecl = vertexFormat->getDecl();
  876. mVertexDeclDirty = true;
  877. mStateDirty = true;
  878. }
  879. #endif // _GFXDEVICE_H_