Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/*
   Copyright (c) 2014 DIVIDE-Studio
   Copyright (c) 2009 Ionut Cava

   This file is part of DIVIDE Framework.

   Permission is hereby granted, free of charge, to any person obtaining a copy of this software
   and associated documentation files (the "Software"), to deal in the Software without restriction,
   including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
   subject to the following conditions:

   The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
   INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
   OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 */

#ifndef _WRAPPER_GL_H_
#define _WRAPPER_GL_H_

#include "core.h"
#include "glResources.h"
#include "Hardware/Video/Headers/RenderAPIWrapper.h"
#include "Hardware/Video/Headers/ImmediateModeEmulation.h"
#include "Hardware/Video/OpenGL/Shaders/Headers/glShaderProgram.h"
#include "Hardware/Video/OpenGL/Shaders/Headers/glShader.h"
#include "Hardware/Video/OpenGL/Textures/Headers/glTexture.h"
#include "Hardware/Video/OpenGL/Headers/glEnumTable.h"
#include <boost/lockfree/spsc_queue.hpp>

class Text3D;
class glIMPrimitive;
class glUniformBuffer;

struct glslopt_ctx;

DEFINE_SINGLETON_EXT1(GL_API,RenderAPIWrapper)
    typedef Unordered_map<std::string, SceneGraphNode*> sceneGraphMap;
    typedef void (*callback)();	void glCommand(callback f){f();}

    friend class glShader;
    friend class glIMPrimitive;
    friend class glFrameBuffer;
    friend class glVertexArray;
    friend class glShaderProgram;
    friend class glSamplerObject;
    friend class glGenericVertexData;
protected:

    GL_API() : RenderAPIWrapper(),
               _prevWidthNode(0),
               _prevWidthString(0),
               _prevSizeNode(0),
               _prevSizeString(0),
               _lineWidthLimit(1),
               _pointDummyVAO(0)
    {
    }

    void exitRenderLoop(bool killCommand = false);

    GLbyte initHardware(const vec2<GLushort>& resolution, GLint argc, char **argv);
    void closeRenderingApi();
    void initDevice(GLuint targetFrameRate);
    ///Change the window's position
    void      setWindowPos(GLushort w, GLushort h) const;
    void      setMousePosition(GLushort x, GLushort y) const;

    void beginFrame();
    void endFrame();
    void idle();
    void flush();

    FrameBuffer*        newFB(bool multisampled) const;
    VertexBuffer*       newVB() const;
    PixelBuffer*        newPB(const PBType& type) const;
    GenericVertexData*  newGVD(const bool persistentMapped) const;
    ShaderBuffer*       newSB(const bool unbound = false) const;

    inline Texture*       newTextureArray(const bool flipped = false)   const {return New glTexture(glTextureTypeTable[TEXTURE_2D_ARRAY], flipped); }
    inline Texture*       newTexture2D(const bool flipped = false)      const {return New glTexture(glTextureTypeTable[TEXTURE_2D],flipped);}
    inline Texture*       newTextureCubemap(const bool flipped = false) const {return New glTexture(glTextureTypeTable[TEXTURE_CUBE_MAP],flipped);}
    inline ShaderProgram* newShaderProgram(const bool optimise = false) const {return New glShaderProgram(optimise); }
    inline Shader*        newShader(const std::string& name,const ShaderType& type, const bool optimise = false) const {return New glShader(name,type,optimise); }
           bool           initShaders();
           bool           deInitShaders();

    void updateClipPlanes();

    inline void toggleRasterization(bool state) { state ? glDisable(GL_RASTERIZER_DISCARD) : glEnable(GL_RASTERIZER_DISCARD); }

    void debugDraw(const SceneRenderState& sceneRenderState);
    void drawText(const TextLabel& textLabel, const vec2<I32>& position);
    void drawBox3D(const vec3<GLfloat>& min,const vec3<GLfloat>& max, const mat4<GLfloat>& globalOffset);
    void drawLines(const vectorImpl<vec3<GLfloat> >& pointsA,
                   const vectorImpl<vec3<GLfloat> >& pointsB,
                   const vectorImpl<vec4<GLubyte> >& colors,
                   const mat4<GLfloat>& globalOffset,
                   const bool orthoMode = false,
                   const bool disableDepth = false);
    void drawPoints(GLuint numPoints);

    /*immediate mode emmlation*/
    IMPrimitive* createPrimitive(bool allowPrimitiveRecycle = true);
    /*immediate mode emmlation end*/

    void loadInContextInternal();

    inline GLuint64 getFrameDurationGPU() const { 
#ifdef _DEBUG
        glGetQueryObjectui64v(_queryID[_queryFrontBuffer][0], GL_QUERY_RESULT, &GL_API::FRAME_DURATION_GPU); 
#endif
        return GL_API::FRAME_DURATION_GPU; 
    }

    inline GLuint      getFrameCount()    const { return GL_API::FRAME_COUNT; }
    inline GLint       getDrawCallCount() const { return GL_API::FRAME_DRAW_CALLS_PREV; }
    inline static void registerDrawCall()       { GL_API::FRAME_DRAW_CALLS++; }

    inline static GLuint getActiveVAOId()              {return _activeVAOId;}

    static void clearColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLuint renderTarget = 0, bool force = false);
    inline static void clearColor(const vec4<GLfloat>& color, GLuint renderTarget = 0, bool force = false) {
        clearColor(color.r,color.g,color.b,color.a,renderTarget,force);
    }
    inline static GLuint getActiveFB() { return _activeFBId; }


    inline static glslopt_ctx*     getGLSLOptContext()          {return _GLSLOptContex;}

    inline static GLuint getActiveTextureUnit() {return _activeTextureUnit;}

public:
    static void togglePrimitiveRestart(bool state, bool smallIndices);
    static bool setActiveTextureUnit(GLuint unit,const bool force = false);
    static bool setActiveVAO(GLuint id, const bool force = false);
    static bool setActiveBuffer(GLenum target, GLuint id, const bool force = false);
    static bool setActiveFB(GLuint id, const bool read = true, const bool write = true, const bool force = false);
    static bool setActiveTransformFeedback(GLuint id, const bool force = false);
    static bool setActiveProgram(glShaderProgram* const program,const bool force = false);
           void activateStateBlock(const RenderStateBlock& newBlock, RenderStateBlock* const oldBlock) const;

    static bool bindTexture(GLuint unit, GLuint handle, GLenum type, GLuint samplerID = 0);
    static bool bindSampler(GLuint unit, GLuint handle);
    inline static bool unbindTexture(GLuint unit, GLenum type){
        return bindTexture(unit, 0, type);
    }
protected:
    boost::atomic_bool _closeLoadingThread;

    I32 getFont(const std::string& fontName);
    glIMPrimitive* getOrCreateIMPrimitive(bool allowPrimitiveRecycle = true);
    ///Used for rendering skeletons
    void setupLineState(const mat4<F32>& mat, const bool ortho);
    void releaseLineState(const bool ortho);
    void drawDebugAxisInternal(const SceneRenderState& sceneRenderState);
    void setupLineStateViewPort(const mat4<F32>& mat);
    void releaseLineStateViewPort();
    void changeResolutionInternal(GLushort w, GLushort h);
    void changeViewport(const vec4<GLint>& newViewport) const;
    void clearStates(const bool skipShader, const bool skipTextures, const bool skipBuffers, const bool forceAll);

private: //OpenGL specific:

    ///Text Rendering
    ///The previous Text3D node's font face size
    GLfloat _prevSizeNode;
    ///The previous plain text string's font face size
    GLfloat _prevSizeString;
    ///The previous Text3D node's line width
    GLfloat _prevWidthNode;
    ///The previous plain text string's line width
    GLfloat _prevWidthString;
    ///Window management:
    vec2<GLushort> _cachedResolution; ///<Current window resolution
    // line width limit
    GLint _lineWidthLimit;
    vectorImpl<vec3<GLfloat> > _pointsA, _axisPointsA;
    vectorImpl<vec3<GLfloat> > _pointsB, _axisPointsB;
    vectorImpl<vec4<GLubyte> > _colors, _axisColors;
    //Immediate mode emulation
    ShaderProgram*               _imShader;       //<The shader used to render VB data
    vectorImpl<glIMPrimitive* >  _glimInterfaces; //<The interface that coverts IM calls to VB data
    GLuint _pointDummyVAO; //< Used to render points (e.g. to render full screen quads with geometry shaders)
    ///A cache of all fonts used 
    typedef Unordered_map<std::string , I32 > FontCache;
    ///2D GUI-like text (bitmap fonts) go in this
    FontCache  _fonts;

    static glslopt_ctx* _GLSLOptContex;
    static GLuint _activeVAOId;
    static GLuint _activeFBId;
    static GLuint _activeBufferId[7]; //< VB, IB, SB, TB, UB, PUB, DIB
    static GLuint _activeTextureUnit;
    static GLuint _activeTransformFeedback;
    static Unordered_map<GLuint, vec4<GLfloat> > _prevClearColor;
    
    static bool _lastRestartIndexSmall;
    static bool _primitiveRestartEnabled;
    bool _activeClipPlanes[Config::MAX_CLIP_PLANES];

    /// performance counters
    // front x 2 and back x 2
    static const GLint PERFORMANCE_COUNTER_BUFFERS = 4;
    // number of queries
    static const GLint PERFORMANCE_COUNTERS = 1;
    // number of draw calls (rough estimate)
    static GLint FRAME_DRAW_CALLS;
    static GLint FRAME_DRAW_CALLS_PREV;
    static GLuint FRAME_COUNT;

    GLuint _queryID[PERFORMANCE_COUNTER_BUFFERS][PERFORMANCE_COUNTERS];
    GLuint _queryBackBuffer;
    GLuint _queryFrontBuffer;
    static GLuint64 FRAME_DURATION_GPU;

    struct FONScontext* _fonsContext;
    /*slot*/ /*<textureHandle , textureType>*/
    typedef Unordered_map<GLushort, std::pair<GLuint, GLenum> > textureBoundMapDef;
    static textureBoundMapDef textureBoundMap;

    typedef Unordered_map<GLushort, GLuint> samplerBoundMapDef;
    static samplerBoundMapDef samplerBoundMap;

END_SINGLETON

#endif

Commits for Divide-Framework/trunk/Source Code/Hardware/Video/OpenGL/Headers/GLWrapper.h

Diff revisions: vs.
Revision Author Commited Message
280 Diff Diff IonutCava picture IonutCava Sat 28 Jun, 2014 19:11:37 +0000

[Ionut] [[BR]]
- Improve ClipPlane management (bunch equations into the matrix shader buffer) [[BR]]
- Immediate mode emulation primitives set their own state based on specified hash instead of relying on state functions to be defined [[BR]]
- updateStates() function is now called right before the actual draw call to facilitate future batching work [[BR]]
- added tracked bool values (similar to those in ShaderInfo) to SGN class to fix selection bug. [[BR]]
— will probably create a “stateTracker” class to allow multiple classes to use tracked variables without all of the code duplication [[BR]]

279 Diff Diff IonutCava picture IonutCava Sat 28 Jun, 2014 16:20:46 +0000

[Ionut][[BR]]
- Unified draw command system into GenericDrawCommand [[BR]]
- Fixed double VB creation in Object3D [[BR]]
- Reworked triangle data computation (now Object3D’s responsibility) [[BR]]
- VertexArrays can now render using the primitive type specified in the draw command instead of the fixed type specified at creation [[BR]]
- Optimized terrain shader [[BR]]

275 Diff Diff IonutCava picture IonutCava Fri 13 Jun, 2014 15:11:02 +0000

[Ionut [[BR]]
- Removed all GLM dependencies (great library, but my math class can handle all of my requirements now) [[BR]]
- Moved view/projection/texture matrix management to GFXDevice class (from API specific classes) [[BR]]

273 Diff Diff IonutCava picture IonutCava Wed 11 Jun, 2014 20:34:00 +0000

[Ionut] [[BR]]
- Improved batching part2: [[BR]]
— Moved all bone transformation matrices upload from uniform functions in SceneNode to Shader Storage Buffers in AnimationController class with updates controlled by SceneGraphNode’s AnimationComponent [[BR]]
-— No double-buffering or efficient mapping of data yet. Just raw buffer updates [[BR]]
— Replaced all RenderStateBlock* pointers with I64 hash values [[BR]]
-— Will be used later in draw commands as per-shader state hash [[BR]]
— Moved getShaderProgram from Material to Material::ShaderInfo [[BR]]
-— Improved redundant uniform checks [[BR]]
— Improved texture unit changing in case of redundant texture bind case (i.e. skip changing the texture unit) [[BR]]
[[BR]]
- Improved float and double comparison functions using algorithms described in http://randomascii.wordpress.com/2012/02/13/dont-store-that-in-a-float/ [[BR]]
- Added a new utility function, DIVIDE_ASSERT, to more easily bind an assert check with a specific message [[BR]]
- Added missing files from Forward+ renderer’s initial code [[BR]]

272 Diff Diff IonutCava picture IonutCava Wed 11 Jun, 2014 11:30:51 +0000

[Ionut] [[BR]]
- Added initial code for Forward+ rendering (grid based light culling) [[BR]]
- Simplified Light class [[BR]]
- Moved more light uniform data to ShaderBuffers [[BR]]
- Double buffered grass rendering [[BR]]
- Added a better attribute interface to GenericVertexData [[BR]]
- Fixed screenshot capture [[BR]]
- Fixed texture double-bind checks [[BR]]

271 Diff Diff IonutCava picture IonutCava Fri 06 Jun, 2014 19:27:02 +0000

[Ionut] [[BR]]
- Preparing GVD class to support persistent mapping [[BR]]
- Updates to grass buffer. Better eat up the cost of waiting for culling result than going through the severe visual artifacts cause by skipping draws [[BR]]

268 Diff Diff IonutCava picture IonutCava Wed 04 Jun, 2014 10:20:27 +0000

[IonutCava] [[BR]]
- Terrain and vegetation updates: [[BR]]
— Use standard phong lighting model [[BR]]
— Separate grass patches per chunk [[BR]]
— Reduce number of required texture bind points for terrain by adding both textures and normal maps in a single texture array [[BR]]
— Draw terrain with 2 drawcalls (using glMultiDrawElements twice, once for LoD == 0 and once for LoD > 0) [[BR]]
[[BR]]
- Buffer management updates: [[BR]]
— Unified buffer binding system [[BR]]
— Made Uniform buffer objects visible to all classes and moved lightUBO to LightManager, matricesUBO to GFXDevice etc [[BR]]
— Added initial support for Shader Buffer Objects [[BR]]
— Moved viewport management to GFXDevice class [[BR]]
[[BR]]
- Rendering improvements: [[BR]]
— Added Hi-Z occlusion culling to instanceCull shader (using Hi-Z depth buffer constructed in GFXDevice class) [[BR]]
— Resolved issues with shadow maps overriding texture bind locations [[[BR]]
— Improved shader and shader program loading [[BR]]
— Improved material transparency support [[BR]]
— Added buffer lock manager class from “Approaching Zero Driver Overhead in OpenGL (Presented by NVIDIA)” speech at GDC14 [[BR]]

267 Diff Diff k1ngp1n picture k1ngp1n Wed 28 May, 2014 11:08:12 +0000

[Ionut] [[BR]]
- Improved texture handling: [[BR]]
— No more texture unbind (except when clearing the frame state) [[BR]]
— Moved texture bind checking to the GL_API class [[BR]]
- Fixed a crash related to vegetation loading due to compiler optimizations [[BR]]
- removed all “releaseMaterial” functions as they are no longer needed [[BR]]

265 Diff Diff k1ngp1n picture k1ngp1n Tue 27 May, 2014 19:47:56 +0000

[Ionut] [[BR]]
- reworked uniform buffer binding [[BR]]
- modified framebuffer mipmap update [[BR]]

264 k1ngp1n picture k1ngp1n Tue 27 May, 2014 13:04:38 +0000

[Ionut] [[BR]]
- New camera system: [[BR]]
— Stack based (push/pop active camera) [[BR]]
— Per camera frustum [[BR]]
— Per camera projection [[BR]]
— Shadow mapping now uses the new camera system (each light has a shadow camera) [[BR]]
[[BR]]
- New terrain, water and vegetation system: [[BR]]
— Direct import of terrain from L3DT both as 8-bit grayscale and 16-bit raw formats [[BR]]
— Multiple alpha maps for texture splatting support [[BR]]
— Per texture detail map support [[BR]]
— Transform feedback based visibility culling for vegetation [[BR]]
— Alpha-map based vegetation placing on terrain [[BR]]
— Water now uses a refraction map instead of alpha blending for better refraction effects [[BR]]
[[BR]]
- SceneGraph improvements: [[BR]]
— Better bounding box updates from child to parent [[BR]]
— Better onDraw / postDraw implementation [[BR]]
[[BR]]
- Performance improvements: [[BR]]
— Batch 2D rendering tasks together as much as possible[[BR]]
— Improve renderStateBlock hash generation for better sorting [[BR]]
— Move most state related gfx changes from API implementation to the GFXDevice class [[BR]]
— Move viewport stack to the GFXDevice class [[BR]]
— Added various performance counters (frame duration with round-robin query system, draw call count, etc) [[BR]]
— Fixed and improved clip plane management [[BR]]
— Delete client-side texture data after GPU upload [[BR]]
[[BR]]
- New features: [[BR]]
— Added callback support to the Task class so that a specific task may call a function in the main thread upon completion [[BR]]
— Added mouse-wheel zoom support to Orbit/ThirdPerson cameras [[BR]]
— Added 2D Texture Array support (e.g. used for terrain textures) [[BR]]