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 
7 Copyright (c) 2000-2013 Torus Knot Software Ltd
8 
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15 
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18 
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 THE SOFTWARE.
26 -----------------------------------------------------------------------------
27 */
28 
29 #ifndef __GL3PlusRenderSystem_H__
30 #define __GL3PlusRenderSystem_H__
31 
32 #include "OgreGL3PlusPrerequisites.h"
33 
34 #include "OgreMaterialManager.h"
35 #include "OgreRenderSystem.h"
36 #include "OgreGL3PlusGpuProgram.h"
37 
38 namespace Ogre {
39     class GL3PlusContext;
40     class GL3PlusSupport;
41     class GL3PlusRTTManager;
42     class GL3PlusGpuProgramManager;
43     class GLSLProgramFactory;
44     class GLSLGpuProgram;
45     class GLSLLinkProgram;
46     class HardwareBufferManager;
47 
48     /**
49       Implementation of GL 3 as a rendering system.
50      */
51     class _OgreGL3PlusExport GL3PlusRenderSystem : public RenderSystem
52     {
53         private:
54             /// Rendering loop control
55             bool mStopRendering;
56 
57             typedef HashMap<GLenum, GLuint>  BindBufferMap;
58 
59             /// View matrix to set world against
60             Matrix4 mViewMatrix;
61             Matrix4 mWorldMatrix;
62             Matrix4 mTextureMatrix;
63 
64             /// Last min & mip filtering options, so we can combine them
65             FilterOptions mMinFilter;
66             FilterOptions mMipFilter;
67 
68             bool mTextureCompareEnabled;
69 
70             /** Used to store the number of mipmaps in the currently bound texture.  This is then
71              used to modify the texture unit filtering.
72              */
73             size_t mTextureMipmapCount;
74 
75             /// What texture coord set each texture unit is using
76             size_t mTextureCoordIndex[OGRE_MAX_TEXTURE_LAYERS];
77 
78             /// Holds texture type settings for every stage
79             GLenum mTextureTypes[OGRE_MAX_TEXTURE_LAYERS];
80 
81             /// Number of fixed-function texture units
82             unsigned short mFixedFunctionTextureUnits;
83 
84             void initConfigOptions(void);
85 
86             /// Store last colour write state
87             bool mColourWrite[4];
88 
89             /// Store last depth write state
90             bool mDepthWrite;
91 
92             /// Store last stencil mask state
93             uint32 mStencilWriteMask;
94 
95             GLfloat mAutoTextureMatrix[16];
96 
97             bool mUseAutoTextureMatrix;
98 
99             /// GL support class, used for creating windows etc.
100             GL3PlusSupport *mGLSupport;
101 
102             /* The main GL context - main thread only */
103             GL3PlusContext *mMainContext;
104 
105             /* The current GL context  - main thread only */
106             GL3PlusContext *mCurrentContext;
107 
108             typedef list<GL3PlusContext*>::type GL3PlusContextList;
109             /// List of background thread contexts
110             GL3PlusContextList mBackgroundContextList;
111 
112             GL3PlusGpuProgramManager *mGpuProgramManager;
113             GLSLProgramFactory* mGLSLProgramFactory;
114             HardwareBufferManager* mHardwareBufferManager;
115 
116             /** Manager object for creating render textures.
117                 Direct render to texture via FBO is preferable
118                 to pbuffers, which depend on the GL support used and are generally
119                 unwieldy and slow. However, FBO support for stencil buffers is poor.
120               */
121             GL3PlusRTTManager *mRTTManager;
122 
123             /** These variables are used for caching RenderSystem state.
124                 They are cached because OpenGL state changes can be quite expensive,
125                 which is especially important on mobile or embedded systems.
126              */
127             GLenum mActiveTextureUnit;
128             BindBufferMap mActiveBufferMap;
129 
130             /// Check if the GL system has already been initialised
131             bool mGLInitialised;
132 
133             // local data members of _render that were moved here to improve performance
134             // (save allocations)
135             vector<GLuint>::type mRenderAttribsBound;
136             vector<GLuint>::type mRenderInstanceAttribsBound;
137 
138             /**
139                 Cache the polygon mode value
140              */
141             GLenum mPolygonMode;
142 
143             GLint getCombinedMinMipFilter(void) const;
144 
145             GL3PlusGpuProgram* mCurrentVertexProgram;
146             GL3PlusGpuProgram* mCurrentFragmentProgram;
147             GL3PlusGpuProgram* mCurrentGeometryProgram;
148             GL3PlusGpuProgram* mCurrentHullProgram;
149             GL3PlusGpuProgram* mCurrentDomainProgram;
150             GL3PlusGpuProgram* mCurrentComputeProgram;
151 
152             GLint getTextureAddressingMode(TextureUnitState::TextureAddressingMode tam) const;
153             GLenum getBlendMode(SceneBlendFactor ogreBlend) const;
154 
155             bool activateGLTextureUnit(size_t unit);
156             void bindVertexElementToGpu( const VertexElement &elem, HardwareVertexBufferSharedPtr vertexBuffer,
157                                         const size_t vertexStart,
158                                         vector<GLuint>::type &attribsBound,
159                                         vector<GLuint>::type &instanceAttribsBound,
160                                         bool updateVAO);
161 
162         public:
163             // Default constructor / destructor
164             GL3PlusRenderSystem();
165             ~GL3PlusRenderSystem();
166 
167             friend class ShaderGeneratorTechniqueResolverListener;
168 
169             // ----------------------------------
170             // Overridden RenderSystem functions
171             // ----------------------------------
172             /** See
173               RenderSystem
174              */
175             const String& getName(void) const;
176             /** See
177               RenderSystem
178              */
179             ConfigOptionMap& getConfigOptions(void);
180             /** See
181               RenderSystem
182              */
183             void setConfigOption(const String &name, const String &value);
184             /** See
185               RenderSystem
186              */
187             String validateConfigOptions(void);
188             /** See
189               RenderSystem
190              */
191             RenderWindow* _initialise(bool autoCreateWindow, const String& windowTitle = "OGRE Render Window");
192             /** See
193               RenderSystem
194              */
195             virtual RenderSystemCapabilities* createRenderSystemCapabilities() const;
196             /** See
197               RenderSystem
198              */
199             void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary);
200             /** See
201               RenderSystem
202              */
203             void reinitialise(void); // Used if settings changed mid-rendering
204             /** See
205               RenderSystem
206              */
207             void shutdown(void);
208             /** See
209               RenderSystem
210              */
setAmbientLight(float r,float g,float b)211             void setAmbientLight(float r, float g, float b) { };   // Not supported
212             /** See
213               RenderSystem
214              */
setShadingType(ShadeOptions so)215             void setShadingType(ShadeOptions so) { };   // Not supported
216             /** See
217               RenderSystem
218              */
setLightingEnabled(bool enabled)219             void setLightingEnabled(bool enabled) { };   // Not supported
220 
221             /// @copydoc RenderSystem::_createRenderWindow
222             RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height,
223                 bool fullScreen, const NameValuePairList *miscParams = 0);
224 
225             /// @copydoc RenderSystem::_createRenderWindows
226             bool _createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions,
227 			RenderWindowList& createdWindows);
228 
229             /// @copydoc RenderSystem::_createDepthBufferFor
230             DepthBuffer* _createDepthBufferFor( RenderTarget *renderTarget );
231 
232             /// Mimics D3D9RenderSystem::_getDepthStencilFormatFor, if no FBO RTT manager, outputs GL_NONE
233             void _getDepthStencilFormatFor( GLenum internalColourFormat, GLenum *depthFormat,
234                                             GLenum *stencilFormat );
235 
236             /// @copydoc RenderSystem::createMultiRenderTarget
237             virtual MultiRenderTarget * createMultiRenderTarget(const String & name);
238 
239             /** See
240               RenderSystem
241              */
242             void destroyRenderWindow(RenderWindow* pWin);
243             /** See
244               RenderSystem
245              */
246             String getErrorDescription(long errorNumber) const;
247             /** See
248               RenderSystem
249              */
250             VertexElementType getColourVertexElementType(void) const;
251             /** See
252               RenderSystem
253              */
setNormaliseNormals(bool normalise)254             void setNormaliseNormals(bool normalise) { };   // Not supported
255 
256             // -----------------------------
257             // Low-level overridden members
258             // -----------------------------
259             /** See
260              RenderSystem
261              */
_useLights(const LightList & lights,unsigned short limit)262             void _useLights(const LightList& lights, unsigned short limit) { };   // Not supported
263             /** See
264              RenderSystem
265              */
areFixedFunctionLightsInViewSpace()266             bool areFixedFunctionLightsInViewSpace() const { return true; }
267             /** See
268              RenderSystem
269              */
270             void _setWorldMatrix(const Matrix4 &m);
271             /** See
272              RenderSystem
273              */
274             void _setViewMatrix(const Matrix4 &m);
275             /** See
276              RenderSystem
277              */
278             void _setProjectionMatrix(const Matrix4 &m);
279             /** See
280              RenderSystem
281              */
_setSurfaceParams(const ColourValue & ambient,const ColourValue & diffuse,const ColourValue & specular,const ColourValue & emissive,Real shininess,TrackVertexColourType tracking)282             void _setSurfaceParams(const ColourValue &ambient,
283                                    const ColourValue &diffuse, const ColourValue &specular,
284                                    const ColourValue &emissive, Real shininess,
285                                    TrackVertexColourType tracking) {}
286             /** See
287              RenderSystem
288              */
289             void _setPointParameters(Real size, bool attenuationEnabled,
290                                      Real constant, Real linear, Real quadratic, Real minSize, Real maxSize);
291             /** See
292              RenderSystem
293              */
294             void _setPointSpritesEnabled(bool enabled);
295             /** See
296              RenderSystem
297              */
298             void _setTexture(size_t unit, bool enabled, const TexturePtr &tex);
299             /** See
300              RenderSystem
301              */
302             void _setTextureCoordSet(size_t stage, size_t index);
303             /** See
304              RenderSystem
305              */
306             void _setTextureCoordCalculation(size_t stage, TexCoordCalcMethod m,
307                     const Frustum* frustum = 0) { };   // Not supported
308             /** See
309              RenderSystem
310              */
_setTextureBlendMode(size_t stage,const LayerBlendModeEx & bm)311             void _setTextureBlendMode(size_t stage, const LayerBlendModeEx& bm) { };   // Not supported
312             /** See
313              RenderSystem
314              */
315             void _setTextureAddressingMode(size_t stage, const TextureUnitState::UVWAddressingMode& uvw);
316             /** See
317              RenderSystem
318              */
319             void _setTextureBorderColour(size_t stage, const ColourValue& colour);
320             /** See
321              RenderSystem
322              */
323             void _setTextureMipmapBias(size_t unit, float bias);
324             /** See
325              RenderSystem
326              */
_setTextureMatrix(size_t stage,const Matrix4 & xform)327             void _setTextureMatrix(size_t stage, const Matrix4& xform) { };   // Not supported
328             /** See
329              RenderSystem
330              */
331             void _setViewport(Viewport *vp);
332             /** See
333              RenderSystem
334              */
335             void _beginFrame(void);
336             /** See
337              RenderSystem
338              */
339             void _endFrame(void);
340             /** See
341              RenderSystem
342              */
343             void _setCullingMode(CullingMode mode);
344             /** See
345              RenderSystem
346              */
347             void _setDepthBufferParams(bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL);
348             /** See
349              RenderSystem
350              */
351             void _setDepthBufferCheckEnabled(bool enabled = true);
352             /** See
353              RenderSystem
354              */
355             void _setDepthBufferWriteEnabled(bool enabled = true);
356             /** See
357              RenderSystem
358              */
359             void _setDepthBufferFunction(CompareFunction func = CMPF_LESS_EQUAL);
360             /** See
361              RenderSystem
362              */
363             void _setDepthBias(float constantBias, float slopeScaleBias);
364             /** See
365              RenderSystem
366              */
367             void _setColourBufferWriteEnabled(bool red, bool green, bool blue, bool alpha);
368             /** See
369              RenderSystem
370              */
371             void _setFog(FogMode mode, const ColourValue& colour, Real density, Real start, Real end);
372             /** See
373              RenderSystem
374              */
375             void _convertProjectionMatrix(const Matrix4& matrix,
376                     Matrix4& dest, bool forGpuProgram = false);
377             /** See
378              RenderSystem
379              */
380             void _makeProjectionMatrix(const Radian& fovy, Real aspect, Real nearPlane, Real farPlane,
381                     Matrix4& dest, bool forGpuProgram = false);
382             /** See
383              RenderSystem
384              */
385             void _makeProjectionMatrix(Real left, Real right, Real bottom, Real top,
386                     Real nearPlane, Real farPlane, Matrix4& dest, bool forGpuProgram = false);
387             /** See
388              RenderSystem
389              */
390             void _makeOrthoMatrix(const Radian& fovy, Real aspect, Real nearPlane, Real farPlane,
391                     Matrix4& dest, bool forGpuProgram = false);
392             /** See
393              RenderSystem
394              */
395             void _applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane,
396                     bool forGpuProgram);
397             /** See
398              RenderSystem
399              */
400             void setClipPlane (ushort index, Real A, Real B, Real C, Real D);
401             /** See
402              RenderSystem
403              */
404             void enableClipPlane (ushort index, bool enable);
405             /** See
406              RenderSystem
407              */
408             void _setPolygonMode(PolygonMode level);
409             /** See
410              RenderSystem
411              */
412             void setStencilCheckEnabled(bool enabled);
413             /** See
414              RenderSystem.
415              */
416             void setStencilBufferParams(CompareFunction func = CMPF_ALWAYS_PASS,
417                     uint32 refValue = 0, uint32 compareMask = 0xFFFFFFFF, uint32 writeMask = 0xFFFFFFFF,
418                     StencilOperation stencilFailOp = SOP_KEEP,
419                     StencilOperation depthFailOp = SOP_KEEP,
420                     StencilOperation passOp = SOP_KEEP,
421                     bool twoSidedOperation = false);
422             /** See
423              RenderSystem
424              */
425             void _setTextureUnitFiltering(size_t unit, FilterType ftype, FilterOptions filter);
426             /** See
427              RenderSystem
428              */
429             void _setTextureUnitCompareFunction(size_t unit, CompareFunction function);
430             /** See
431              RenderSystem
432              */
433             void _setTextureUnitCompareEnabled(size_t unit, bool compare);
434             /** See
435              RenderSystem
436              */
437             void _setTextureLayerAnisotropy(size_t unit, unsigned int maxAnisotropy);
438             /** See
439              RenderSystem
440              */
setVertexDeclaration(VertexDeclaration * decl)441             void setVertexDeclaration(VertexDeclaration* decl) {}
442             /** See
443              RenderSystem
444              */
setVertexDeclaration(VertexDeclaration * decl,VertexBufferBinding * binding)445             void setVertexDeclaration(VertexDeclaration* decl, VertexBufferBinding* binding) {}
446             /** See
447              RenderSystem.
448              */
setVertexBufferBinding(VertexBufferBinding * binding)449             void setVertexBufferBinding(VertexBufferBinding* binding) {}
450             /** See
451              RenderSystem
452              */
453             void _render(const RenderOperation& op);
454             /** See
455              RenderSystem
456              */
457             void setScissorTest(bool enabled, size_t left = 0, size_t top = 0, size_t right = 800, size_t bottom = 600);
458 
459             void clearFrameBuffer(unsigned int buffers,
460                 const ColourValue& colour = ColourValue::Black,
461                 Real depth = 1.0f, unsigned short stencil = 0);
462             HardwareOcclusionQuery* createHardwareOcclusionQuery(void);
getHorizontalTexelOffset(void)463             Real getHorizontalTexelOffset(void) { return 0.0; }               // No offset in GL
getVerticalTexelOffset(void)464             Real getVerticalTexelOffset(void) { return 0.0; }                 // No offset in GL
getMinimumDepthInputValue(void)465             Real getMinimumDepthInputValue(void) { return -1.0f; }            // Range [-1.0f, 1.0f]
getMaximumDepthInputValue(void)466             Real getMaximumDepthInputValue(void) { return 1.0f; }             // Range [-1.0f, 1.0f]
467             OGRE_MUTEX(mThreadInitMutex);
468             void registerThread();
469             void unregisterThread();
470             void preExtraThreadsStarted();
471             void postExtraThreadsStarted();
472             void setClipPlanesImpl(const Ogre::PlaneList& planeList);
473 
474             // ----------------------------------
475             // GL3PlusRenderSystem specific members
476             // ----------------------------------
477             /** Returns the main context */
_getMainContext()478             GL3PlusContext* _getMainContext() { return mMainContext; }
479             /** Unregister a render target->context mapping. If the context of target
480              is the current context, change the context to the main context so it
481              can be destroyed safely.
482 
483              @note This is automatically called by the destructor of
484              GL3PlusContext.
485              */
486             void _unregisterContext(GL3PlusContext *context);
487             /** Switch GL context, dealing with involved internal cached states too
488              */
489             void _switchContext(GL3PlusContext *context);
490             /** One time initialization for the RenderState of a context. Things that
491              only need to be set once, like the LightingModel can be defined here.
492              */
493             void _oneTimeContextInitialization();
494             void initialiseContext(RenderWindow* primary);
495             /**
496              * Set current render target to target, enabling its GL context if needed
497              */
498             void _setRenderTarget(RenderTarget *target);
499 
500             GLint convertCompareFunction(CompareFunction func) const;
501             GLint convertStencilOp(StencilOperation op, bool invert = false) const;
502 
503             void bindGpuProgram(GpuProgram* prg);
504             void unbindGpuProgram(GpuProgramType gptype);
505             void bindGpuProgramParameters(GpuProgramType gptype, GpuProgramParametersSharedPtr params, uint16 mask);
506             void bindGpuProgramPassIterationParameters(GpuProgramType gptype);
507 
508 			/// @copydoc RenderSystem::_setSceneBlending
509 			void _setSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op );
510 			/// @copydoc RenderSystem::_setSeparateSceneBlending
511 			void _setSeparateSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendFactor sourceFactorAlpha, SceneBlendFactor destFactorAlpha, SceneBlendOperation op, SceneBlendOperation alphaOp );
512 			/// @copydoc RenderSystem::_setAlphaRejectSettings
513 			void _setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage );
514 			/// @copydoc RenderSystem::getDisplayMonitorCount
515 			unsigned int getDisplayMonitorCount() const;
516 
517             /// Internal method for anisotropy validation
518             GLfloat _getCurrentAnisotropy(size_t unit);
519 
_getPolygonMode(void)520             GLenum _getPolygonMode(void) { return mPolygonMode; }
521 
522             void _setSceneBlendingOperation(SceneBlendOperation op);
523             void _setSeparateSceneBlendingOperation(SceneBlendOperation op, SceneBlendOperation alphaOp);
524             /// @copydoc RenderSystem::hasAnisotropicMipMapFilter
hasAnisotropicMipMapFilter()525             virtual bool hasAnisotropicMipMapFilter() const { return false; }
526 
527             /// @copydoc RenderSystem::beginProfileEvent
528             virtual void beginProfileEvent( const String &eventName );
529 
530             /// @copydoc RenderSystem::endProfileEvent
531             virtual void endProfileEvent( void );
532 
533             /// @copydoc RenderSystem::markProfileEvent
534             virtual void markProfileEvent( const String &eventName );
535     };
536 }
537 
538 #endif
539