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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#include "Headers/GLWrapper.h"
#include "Headers/glImmediateModeEmulation.h"

#include "Graphs/Headers/SceneGraph.h"
#include "Scenes/Headers/SceneState.h"

#include "GUI/Headers/GUI.h"
#include "GUI/Headers/GUIText.h"

#include "Core/Headers/ParamHandler.h"
#include "Core/Math/Headers/Transform.h"
#include "Core/Resources/Headers/ResourceCache.h"

#include "Geometry/Material/Headers/Material.h"
#include "Geometry/Shapes/Headers/SubMesh.h"
#include "Geometry/Shapes/Headers/Predefined/Box3D.h"
#include "Geometry/Shapes/Headers/Predefined/Sphere3D.h"
#include "Geometry/Shapes/Headers/Predefined/Quad3D.h"
#include "Geometry/Shapes/Headers/Predefined/Text3D.h"

#include "Hardware/Video/Headers/GFXDevice.h"
#include "Hardware/Video/OpenGL/glsw/Headers/glsw.h"

#include "Hardware/Video/OpenGL/Buffers/Framebuffer/Headers/glFramebuffer.h"
#include "Hardware/Video/OpenGL/Buffers/PixelBuffer/Headers/glPixelBuffer.h"
#include "Hardware/Video/OpenGL/Buffers/VertexBuffer/Headers/glVertexArray.h"
#include "Hardware/Video/OpenGL/Buffers/VertexBuffer/Headers/glGenericVertexData.h"
#include "Hardware/Video/OpenGL/Buffers/ShaderBuffer/Headers/glUniformBuffer.h"

#include <glsl/glsl_optimizer.h>

#ifndef GLFONTSTASH_IMPLEMENTATION
#define GLFONTSTASH_IMPLEMENTATION
#define FONTSTASH_IMPLEMENTATION
#include "Text/Headers/fontstash.h"
#include "Text/Headers/glfontstash.h"
#endif

GLuint64 GL_API::FRAME_DURATION_GPU = 0;

#include <glim.h>

void GL_API::createFonsContext() {
    _fonsContext = glfonsCreate(512, 512, FONS_ZERO_BOTTOMLEFT);
}

void GL_API::deleteFonsContext() {
    glfonsDelete(_fonsContext);
    _fonsContext = nullptr;
}

void GL_API::beginFrame(){
#ifdef _DEBUG
    GLuint queryId = _queryID[_queryBackBuffer][0];
    glBeginQuery(GL_TIME_ELAPSED, queryId);
#endif
    GL_API::clearColor(DefaultColors::DIVIDE_BLUE(), 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT/* | GL_STENCIL_BUFFER_BIT*/);
    GFX_DEVICE.registerDrawCall();
}

void GL_API::endFrame(){

    //unbind all states (shaders, textures, buffers)
    clearStates(false,false,false);

    glfwSwapBuffers(Divide::GLUtil::_mainWindow);

#ifdef _DEBUG
    glEndQuery(GL_TIME_ELAPSED);

    GLuint query = GFX_DEVICE.getFrameCount() % 4;
    
    _queryBackBuffer = query;
    _queryFrontBuffer = 3 - _queryBackBuffer;
    
#endif
}

void GL_API::flush(){
    clearStates(false,false,false);
}

bool GL_API::initShaders(){
    //Init glsw library
    GLint glswState = glswInit();
    glswAddDirectiveToken("","#version 440 core\n/*�Copyright 2009-2014 DIVIDE-Studio�*/");
#if defined(_DEBUG)
    glswAddDirectiveToken("", "#define _DEBUG");
#elif defined(_PROFILE)
    glswAddDirectiveToken("", "#define _PROFILE");
#else
    glswAddDirectiveToken("", "#define _RELEASE");
#endif

    glswAddDirectiveToken("Vertex",   "#define VERT_SHADER");
    glswAddDirectiveToken("Geometry", "#define GEOM_SHADER");
    glswAddDirectiveToken("Fragment", "#define FRAG_SHADER");

    if(getGPUVendor() == GPU_VENDOR_NVIDIA){ //nVidia specific
        glswAddDirectiveToken("","#pragma optionNV(fastmath on)");
        glswAddDirectiveToken("","#pragma optionNV(fastprecision on)");
        glswAddDirectiveToken("","#pragma optionNV(inline all)");
        glswAddDirectiveToken("","#pragma optionNV(ifcvt none)");
        glswAddDirectiveToken("","#pragma optionNV(strict on)");
        glswAddDirectiveToken("","#pragma optionNV(unroll all)");
    }

    glswAddDirectiveToken("", std::string("#define MAX_INSTANCES " + Util::toString(Config::MAX_INSTANCE_COUNT)).c_str());
    glswAddDirectiveToken("", std::string("#define MAX_CLIP_PLANES " + Util::toString(Config::MAX_CLIP_PLANES)).c_str());
    glswAddDirectiveToken("", std::string("#define MAX_SHADOW_CASTING_LIGHTS " + Util::toString(Config::Lighting::MAX_SHADOW_CASTING_LIGHTS_PER_NODE)).c_str());
    glswAddDirectiveToken("", std::string("#define MAX_SPLITS_PER_LIGHT " + Util::toString(Config::Lighting::MAX_SPLITS_PER_LIGHT)).c_str());
    glswAddDirectiveToken("", std::string("const uint MAX_LIGHTS_PER_SCENE = " + Util::toString(Config::Lighting::MAX_LIGHTS_PER_SCENE) + ";").c_str());
    glswAddDirectiveToken("", std::string("#define MAX_LIGHTS_PER_SCENE_NODE 3").c_str());
    glswAddDirectiveToken("", std::string("#define SHADER_BUFFER_LIGHT_NORMAL " + Util::toString(Divide::SHADER_BUFFER_LIGHT_NORMAL)).c_str());
    glswAddDirectiveToken("", std::string("#define SHADER_BUFFER_GPU_BLOCK " + Util::toString(Divide::SHADER_BUFFER_GPU_BLOCK)).c_str());
    glswAddDirectiveToken("", std::string("#define SHADER_BUFFER_NODE_MATERIAL " + Util::toString(Divide::SHADER_BUFFER_NODE_MATERIAL)).c_str());
    glswAddDirectiveToken("", std::string("#define SHADER_BUFFER_NODE_TRANSFORMS " + Util::toString(Divide::SHADER_BUFFER_NODE_TRANSFORMS)).c_str());
    glswAddDirectiveToken("", "const float Z_TEST_SIGMA = 0.0001;");
    glswAddDirectiveToken("", "const float ALPHA_DISCARD_THRESHOLD = 0.25;");
    glswAddDirectiveToken("", "//__CUSTOM_DEFINES__");
    glswAddDirectiveToken("", "//__CUSTOM_UNIFORMS__");
    glswAddDirectiveToken("Vertex",   std::string("#define MAX_BONE_COUNT_PER_NODE " + Util::toString(Config::MAX_BONE_COUNT_PER_NODE)).c_str());
    glswAddDirectiveToken("Vertex",   std::string("#define SHADER_BUFFER_BONE_TRANSFORMS " + Util::toString(Divide::SHADER_BUFFER_BONE_TRANSFORMS)).c_str());
    glswAddDirectiveToken("Fragment", std::string("#define SHADER_BUFFER_LIGHT_SHADOW " + Util::toString(Divide::SHADER_BUFFER_LIGHT_SHADOW)).c_str());
    glswAddDirectiveToken("Fragment", std::string("#define TEXTURE_UNIT0 " + Util::toString(Material::TEXTURE_UNIT0)).c_str());
    glswAddDirectiveToken("Fragment", std::string("#define TEXTURE_UNIT1 " + Util::toString(Material::TEXTURE_UNIT1)).c_str());
    glswAddDirectiveToken("Fragment", std::string("#define TEXTURE_NORMALMAP " + Util::toString(Material::TEXTURE_NORMALMAP)).c_str());
    glswAddDirectiveToken("Fragment", std::string("#define TEXTURE_OPACITY " + Util::toString(Material::TEXTURE_OPACITY)).c_str());
    glswAddDirectiveToken("Fragment", std::string("#define TEXTURE_SPECULAR " + Util::toString(Material::TEXTURE_SPECULAR)).c_str());

    glswAddDirectiveToken("Fragment", "const uint DEPTH_EXP_WARP = 32;");
    
    // GLSL <-> VBO intercommunication 
    glswAddDirectiveToken("Vertex", std::string("layout(location = " + Util::toString(Divide::VERTEX_POSITION_LOCATION) + ") in vec3  inVertexData;").c_str());
    glswAddDirectiveToken("Vertex", std::string("layout(location = " + Util::toString(Divide::VERTEX_COLOR_LOCATION) + ") in vec4  inColorData;").c_str());
    glswAddDirectiveToken("Vertex", std::string("layout(location = " + Util::toString(Divide::VERTEX_NORMAL_LOCATION) + ") in vec3  inNormalData;").c_str());
    glswAddDirectiveToken("Vertex", std::string("layout(location = " + Util::toString(Divide::VERTEX_TEXCOORD_LOCATION) + ") in vec2  inTexCoordData;").c_str());
    glswAddDirectiveToken("Vertex", std::string("layout(location = " + Util::toString(Divide::VERTEX_TANGENT_LOCATION) + ") in vec3  inTangentData;").c_str());
    glswAddDirectiveToken("Vertex", std::string("layout(location = " + Util::toString(Divide::VERTEX_BITANGENT_LOCATION) + ") in vec3  inBiTangentData;").c_str());
    glswAddDirectiveToken("Vertex", std::string("layout(location = " + Util::toString(Divide::VERTEX_BONE_WEIGHT_LOCATION) + ") in vec4  inBoneWeightData;").c_str());
    glswAddDirectiveToken("Vertex", std::string("layout(location = " + Util::toString(Divide::VERTEX_BONE_INDICE_LOCATION) + ") in ivec4 inBoneIndiceData;").c_str());

    glswAddDirectiveToken("", std::string("#include \"nodeDataInput.cmn\"").c_str());
    GL_API::_GLSLOptContex = glslopt_initialize(GFX_DEVICE.getApi() == OpenGLES ? kGlslTargetOpenGLES30 : kGlslTargetOpenGL);

    return glswState == 1 && GL_API::_GLSLOptContex != nullptr;
}

bool GL_API::deInitShaders(){
    glslopt_cleanup(_GLSLOptContex);
    //Shut down glsw and clean memory
    return (glswShutdown() == 1);
}

I32 GL_API::getFont(const std::string& fontName){
    const FontCache::const_iterator& it = _fonts.find(fontName);
    if(it == _fonts.end()){
        std::string fontPath = ParamHandler::getInstance().getParam<std::string>("assetsLocation") + "/";
        fontPath += "GUI/";
        fontPath += "fonts/";
        fontPath += fontName;
        I32 tempFont = fonsAddFont(_fonsContext, fontName.c_str(), fontPath.c_str());

        if (tempFont == FONS_INVALID) {
            ERROR_FN(Locale::get("ERROR_FONT_FILE"),fontName.c_str());
        }
        _fonts.insert(std::make_pair(fontName, tempFont));
        return tempFont;
    }
    
    return it->second;
}

void GL_API::drawText(const TextLabel& textLabel, const vec2<I32>& position){
    I32 font = getFont(textLabel._font);
    if(font == FONS_INVALID) return;

    F32 lh = 0;
    fonsClearState(_fonsContext);
    fonsSetSize(_fonsContext, textLabel._height);
    fonsSetFont(_fonsContext, font);
    fonsVertMetrics(_fonsContext, nullptr, nullptr, &lh);
    fonsSetColor(_fonsContext, textLabel._color.r * 255, 
                               textLabel._color.g * 255,
                               textLabel._color.b * 255, 
                               textLabel._color.a * 255);
    if(textLabel._blurAmount > 0.01f)
        fonsSetBlur(_fonsContext, textLabel._blurAmount );
    
    if(textLabel._spacing > 0.01f)
        fonsSetBlur(_fonsContext, textLabel._spacing );
    
    if(textLabel._alignFlag != 0)
        fonsSetAlign(_fonsContext, textLabel._alignFlag);
    
    fonsDrawText(_fonsContext, position.x, _cachedResolution.y - (position.y + lh), textLabel._text.c_str(), nullptr);
    GFX_DEVICE.registerDrawCall();
}

void GL_API::drawPoints(GLuint numPoints) {
    GL_API::setActiveVAO(_pointDummyVAO);
    glDrawArrays(GL_POINTS, 0, numPoints);
    GFX_DEVICE.registerDrawCall();
}

IMPrimitive* GL_API::newIMP() const {
    return New glIMPrimitive();
}

/// Creates a new frame buffer
Framebuffer* GL_API::newFB(bool multisampled) const {
    // if MSAA is disabled, this will be a simple color / depth buffer
    // if we requested a MSFB and msaa is enabled, create a resolve buffer
    // and create our FB adding the resolve buffer as it's child
    // else, return a regular frame buffer
     return New glFramebuffer((multisampled && GFX_DEVICE.MSAAEnabled()) ? New glFramebuffer() : nullptr);
}

VertexBuffer* GL_API::newVB() const {
    return New glVertexArray();
}

PixelBuffer* GL_API::newPB(const PBType& type) const {
    return New glPixelBuffer(type);
}

GenericVertexData* GL_API::newGVD(const bool persistentMapped) const {
    return New glGenericVertexData(persistentMapped);
}

ShaderBuffer* GL_API::newSB(const bool unbound, const bool persistentMapped) const {
    return New glUniformBuffer(unbound, persistentMapped);
}

size_t GL_API::getOrCreateSamplerObject(const SamplerDescriptor& descriptor){
    size_t hashValue = descriptor.getHash();

    samplerObjectMap::iterator it = _samplerMap.find(hashValue);
    if (it == _samplerMap.end())
        _samplerMap.insert(std::make_pair(hashValue, New glSamplerObject(descriptor)));
 
    return hashValue;
}

GLuint GL_API::getSamplerHandle(size_t samplerHash) {
    if(samplerHash == 0)
        return 0;

    samplerObjectMap::iterator it = _samplerMap.find(samplerHash);
    if (it == _samplerMap.end()) 
        return 0;

    return it->second->getObjectHandle();
}

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

Diff revisions: vs.
Revision Author Commited Message
286 Diff Diff IonutCava picture IonutCava Fri 18 Jul, 2014 16:32:03 +0000

[Ionut] [[BR]]

    • very buggy commit ** [[BR]]

- New rendering pipeline: [[BR]]
— Bumped OpenGL version to 4.4 [[BR]]
— Command based rendering. GFXDevice dispatches rendering commands to their respective buffers [[BR]]
— State changing is exclusively controlled by the GFXDevice class [[BR]]
— Material properties and transform matrices are stored in shader storage buffers that are updated after culling and uploaded once per RenderPass. Objects use drawIDs to index data in shaders [[BR]]
— Removed all custom matrices and other, per shader, bind data [[BR]]
— Removed per node light data. Light culling and shader buffers will replace the old light management system [[BR]]
— Framebuffers now use the Texture class for attachments [[BR]]
— Sampler objects now work like RenderStateBlocks. GL_API handles them and stores them in a hash indexed map [[BR]]
— Removed “prepareMaterial” calls. Pre-draw material setup is now only limited to texture binding [[BR]]
— Moved immediate mode emulation and primitive rendering from API level to GFXDevice level [[BR]]
— Framebuffer rendering must be completed with a call to end() to ensure proper MSAA resolve (asserts, otherwise) [[BR]]
- Fixed hash code generation for RenderStateBlock (and now, glSamplerObject) using boost::hash_combine [[BR]]
- Temporarily disabled XML caching for materials [[BR]]

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]]

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]]

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]]

264 Diff Diff 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]]

263 Diff Diff k1ngp1n picture k1ngp1n Fri 09 May, 2014 16:43:53 +0000

[Ionut] [[BR]]
- Fullscreen quads are now rendered via Geometry Shaders [[BR]]
- Implemented shader subroutines [[BR]]
- Improved CVSM’s quality [[BR]]
- Separated shadow only light properties from general light properties in separate UBOs to improve update performance [[BR]]
- Removed shader mask and instead try to load all available shaders from a given file [[BR]]
- Added a method (hackish) of changing projection properties at runtime (e.g. z planes) [[BR]]
- Fixed a comparison bug in RenderStateBlock class (forgot to clean it at last commit) [[BR]]
- Fixed clipping plane upload to shader programs [[BR]]

262 k1ngp1n picture k1ngp1n Tue 06 May, 2014 21:04:00 +0000

[Ionut] [[BR]]
- Some AI refactoring (basic AIEntity <-> AESOP interoperability) [[BR]]
- Some render batch sorting code refactored and fixed (wasn’t properly sorted in FINAL_STAGE) [[BR]]
- Simplified RenderStateBlockDescriptor and deferred hash value calculation [[BR]]
- Basic draw call count implementation [[BR]]
- Renamed some classes [[BR]]