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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
#include "Hardware/Video/OpenGL/Headers/glResources.h"
#include "Hardware/Video/OpenGL/glsw/Headers/glsw.h"
#include "Hardware/Video/OpenGL/Buffers/ShaderBuffer/Headers/glUniformBuffer.h"

#include "core.h"
#include <glsl/glsl_optimizer.h>
#include "Headers/glShaderProgram.h"

#include "Hardware/Video/Shaders/Headers/Shader.h"
#include "Core/Headers/ParamHandler.h"
#include "Hardware/Video/Headers/GFXDevice.h"
#include "Managers/Headers/ShaderManager.h"

glShaderProgram::glShaderProgram(const bool optimise) : ShaderProgram(optimise),
                                                        _validationQueued(false),
                                                        _loadedFromBinary(false),
                                                        _shaderProgramIDTemp(0)
{
    _shaderProgramId = Divide::GLUtil::_invalidObjectID;

    _shaderStageTable[VERTEX_SHADER] = GL_VERTEX_SHADER;
    _shaderStageTable[FRAGMENT_SHADER] = GL_FRAGMENT_SHADER;
    _shaderStageTable[GEOMETRY_SHADER] = GL_GEOMETRY_SHADER;
    _shaderStageTable[TESSELATION_CTRL_SHADER] = GL_TESS_CONTROL_SHADER;
    _shaderStageTable[TESSELATION_EVAL_SHADER] = GL_TESS_EVALUATION_SHADER;
    _shaderStageTable[COMPUTE_SHADER] = GL_COMPUTE_SHADER;

    _shaderStage[VERTEX_SHADER] = nullptr;
    _shaderStage[FRAGMENT_SHADER] = nullptr;
    _shaderStage[GEOMETRY_SHADER] = nullptr;
    _shaderStage[TESSELATION_CTRL_SHADER] = nullptr;
    _shaderStage[TESSELATION_EVAL_SHADER] = nullptr;
    _shaderStage[COMPUTE_SHADER] = nullptr;

}

glShaderProgram::~glShaderProgram()
{
    if (_shaderProgramId != 0 && _shaderProgramId != Divide::GLUtil::_invalidObjectID){
        FOR_EACH(ShaderIdMap::value_type& it, _shaderIdMap){
            it.second->removeParentProgram(this);
            glDetachShader(_shaderProgramId, it.second->getShaderId());
        }
        glDeleteProgram(_shaderProgramId);
    }
}

void glShaderProgram::validateInternal()  {
    glValidateProgram(_shaderProgramId);

    GLint status = 0;
    glGetProgramiv(_shaderProgramId, GL_VALIDATE_STATUS, &status);

    if (status == GL_FALSE){
        ERROR_FN(Locale::get("GLSL_VALIDATING_PROGRAM"), getName().c_str(), getLog().c_str());
    }
    else{
        D_PRINT_FN(Locale::get("GLSL_VALIDATING_PROGRAM"), getName().c_str(), getLog().c_str());
    }

    _validationQueued = false;
}

U8 glShaderProgram::update(const U64 deltaTime){
    //Validate the program after we used it once
    if(_validationQueued && isHWInitComplete() && _wasBound/*after it was used at least once*/){
        validateInternal();
#ifdef NDEBUG
        if (_shaderProgramId != 0 && _shaderProgramId != Divide::GLUtil::_invalidObjectID && !_loadedFromBinary){
            GLint   binaryLength;
   
            glGetProgramiv(_shaderProgramId, GL_PROGRAM_BINARY_LENGTH, &binaryLength);
            void* binary = (void*)malloc(binaryLength);
            DIVIDE_ASSERT(binary != NULL, "glShaderProgram error: could not allocate memory for the program binary!");
            glGetProgramBinary(_shaderProgramId, binaryLength, NULL, &_binaryFormat, binary);
 
            std::string outFileName("shaderCache/Binary/"+getName()+".bin");
            FILE* outFile = fopen(outFileName.c_str(), "wb");
            fwrite(binary, binaryLength, 1, outFile);
            fclose(outFile);
            free(binary);
        }
#endif
    }
      
    return ShaderProgram::update(deltaTime);
}

std::string glShaderProgram::getLog() const {
    std::string validationBuffer("[OK]");
    GLint length = 0;

    glGetProgramiv(_shaderProgramIDTemp, GL_INFO_LOG_LENGTH, &length);

    if(length > 1){
        validationBuffer = "\n -- ";
        vectorImpl<char> shaderProgramLog(length);
        glGetProgramInfoLog(_shaderProgramIDTemp, length, NULL, &shaderProgramLog[0]);
        validationBuffer.append(&shaderProgramLog[0]);
        if(validationBuffer.size() > 4096 * 16){
            validationBuffer.resize(4096 * 16 - strlen(Locale::get("GLSL_LINK_PROGRAM_LOG")) - 10);
            validationBuffer.append(" ... ");
        }
    }

    return validationBuffer;
}

void glShaderProgram::detachShader(Shader* const shader){
    DIVIDE_ASSERT(_threadedLoadComplete, "glShaderProgram error: tried to detach a shader from a program that didn't finish loading!");
    glDetachShader(_shaderProgramId ,shader->getShaderId());
}

void glShaderProgram::attachShader(Shader* const shader, const bool refresh){
    if (!shader)
        return;

    GLuint shaderId = shader->getShaderId();

    if(refresh){
        ShaderIdMap::iterator it = _shaderIdMap.find(shaderId);
        if(it != _shaderIdMap.end()){
            _shaderIdMap[shaderId] = shader;
            glDetachShader(_shaderProgramIDTemp, shaderId);
        }else{
            ERROR_FN(Locale::get("ERROR_SHADER_RECOMPILE_NOT_FOUND_ATOM"),shader->getName().c_str());
        }
    }else{
        _shaderIdMap.insert(std::make_pair(shaderId, shader));
    }

    glAttachShader(_shaderProgramIDTemp, shaderId);
    shader->addParentProgram(this);

    _linked = false;
}

void glShaderProgram::threadedLoad(const std::string& name){
    if (!_loadedFromBinary){
        //Create a new program
        if (_shaderProgramId == Divide::GLUtil::_invalidObjectID)
            _shaderProgramIDTemp = glCreateProgram();

        for (U8 i = 0; i < ShaderType_PLACEHOLDER; ++i){
            // Attach, compile and validate shaders into this program and update state
            Shader* shader = _shaderStage[i];
            if(shader){
                shader->validate();
                attachShader(shader, _refreshStage[i]);
                _refreshStage[i] = false;
            }
        }
        
        link();
    }

    validate();
    _shaderProgramId = _shaderProgramIDTemp;
    _textureSlots.clear();
    ShaderProgram::generateHWResource(name);
}

void glShaderProgram::link(){
    GLint linkStatus = 0;
#ifdef NDEBUG
    if (Config::USE_SHADER_BINARY){
        glProgramParameteri(_shaderProgramIDTemp, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);
    }
#endif
    D_PRINT_FN(Locale::get("GLSL_LINK_PROGRAM"), getName().c_str(), _shaderProgramIDTemp);

    if (_outputCount > 0){
        const char *vars[] = { "outVertexData", "outData1", "outData2", "outData3" };
        glTransformFeedbackVaryings(_shaderProgramIDTemp, _outputCount, vars, GL_SEPARATE_ATTRIBS);
    }

    glLinkProgram(_shaderProgramIDTemp);
    glGetProgramiv(_shaderProgramIDTemp, GL_LINK_STATUS, &linkStatus);

    if(linkStatus == GL_FALSE){
        ERROR_FN(Locale::get("GLSL_LINK_PROGRAM_LOG"), getName().c_str(), getLog().c_str());
    }else{
        D_PRINT_FN(Locale::get("GLSL_LINK_PROGRAM_LOG"), getName().c_str(), getLog().c_str());
    }
    _linked = true;
}

/// Creation of a new shader program.
/// Pass in a shader token and use glsw to load the corresponding effects
bool glShaderProgram::generateHWResource(const std::string& name){
    _name = name;
    
    //NULL_SHADER shader means use shaderProgram(0)
    if (name.compare("NULL_SHADER") == 0){
        _validationQueued = false;
        _shaderProgramId = 0;
        _threadedLoadComplete = HardwareResource::generateHWResource(name);
        return true;
    }

    //Set the compilation state
    _linked = false;

    //check for refresh flags
    bool refresh = false;
    for(U8 i = 0; i < ShaderType_PLACEHOLDER; ++i){
        if (_refreshStage[i]){
            refresh = true;
            break;
        }
    }

#ifdef NDEBUG
    //Load the program from the binary file, if available, to avoid linking
    if (Config::USE_SHADER_BINARY && !refresh){
        FILE* inFile = fopen(std::string("shaderCache/Binary/" + _name + ".bin").c_str(), "rb");
        if (inFile){
            GLint   binaryLength;
            GLint   success;
            _shaderProgramIDTemp = glCreateProgram();
            fseek(inFile, 0, SEEK_END);
            binaryLength = (GLint)ftell(inFile);
            void* binary = (void*)malloc(binaryLength);
            fseek(inFile, 0, SEEK_SET);
            fread(binary, binaryLength, 1, inFile);
            fclose(inFile);
            glProgramBinary(_shaderProgramIDTemp, _binaryFormat, binary, binaryLength);
            free(binary);
            glGetProgramiv(_shaderProgramIDTemp, GL_LINK_STATUS, &success);

            if (success) {
                _loadedFromBinary = _linked = true;
                _threadedLoading = false;
            }
        }
    }
#endif

    if (!_linked){
        //Use the specified shader path
        glswSetPath(std::string(getResourceLocation() + "GLSL/").c_str(), ".glsl");
        //Mirror initial shader defines to match line count
        GLint lineCountOffset[ShaderType_PLACEHOLDER];
        std::string shaderSourceUniforms[ShaderType_PLACEHOLDER];

        GLint initialOffset = 16;
        
        if (GFX_DEVICE.getGPUVendor() == GPU_VENDOR_NVIDIA){ //nVidia specific
            initialOffset += 6;
        }

        std::string shaderSourceHeader;
        //get all of the preprocessor defines
        for (U8 i = 0; i < _definesList.size(); i++){
            if (_definesList[i].compare("DEFINE_PLACEHOLDER") == 0) continue;

            shaderSourceHeader.append("#define " + _definesList[i] + "\n" );
            initialOffset++;
        }

        for (U8 i = 0; i < ShaderType_PLACEHOLDER; ++i){
            lineCountOffset[i] = initialOffset;
            for (U8 j = 0; j < _customUniforms[i].size(); j++){
                shaderSourceUniforms[i].append("uniform " + _customUniforms[i][j] + ";\n");
                lineCountOffset[i]++;
            }
        }

        lineCountOffset[VERTEX_SHADER] += 67;
        lineCountOffset[FRAGMENT_SHADER] += 68;

        //Split the shader name to get the effect file name and the effect properties
        std::string shaderName = name.substr(0, name.find_first_of(".,"));
        std::string shaderProperties, vertexProperties;

        size_t propPositionVertex = name.find_first_of(",");
        size_t propPosition = name.find_first_of(".");

        if (propPosition != std::string::npos){
            shaderProperties = "." + name.substr(propPosition + 1, propPositionVertex - propPosition - 1);
        }

        vertexProperties += shaderProperties;

        if (propPositionVertex != std::string::npos){
            vertexProperties += "." + name.substr(propPositionVertex + 1);
        }

        //Load the Vertex Shader
        std::string shaderCompileName[ShaderType_PLACEHOLDER];
        shaderCompileName[VERTEX_SHADER]   = shaderName + ".Vertex" + vertexProperties;
        shaderCompileName[FRAGMENT_SHADER] = shaderName + ".Fragment" + shaderProperties;
        shaderCompileName[GEOMETRY_SHADER] = shaderName + ".Geometry" + shaderProperties;
        shaderCompileName[TESSELATION_CTRL_SHADER] = shaderName + ".TessellationC" + shaderProperties;
        shaderCompileName[TESSELATION_EVAL_SHADER] = shaderName + ".TessellationE" + shaderProperties;
        shaderCompileName[COMPUTE_SHADER] = shaderName + ".Compute" + shaderProperties;

        for (U8 i = 0; i < ShaderType_PLACEHOLDER; ++i) {
            ShaderType type = (ShaderType)(i);

            //Recycle shaders only if we do not request a refresh for them
            if (!_refreshStage[type]) //See if it already exists in a compiled state
                _shaderStage[type] = ShaderManager::getInstance().findShader(shaderCompileName[type], refresh);
           
            //If it doesn't ...
            if (!_shaderStage[type]){
                //Use glsw to read the vertex part of the effect
                const char* sourceCode = glswGetShader(shaderCompileName[type].c_str(), lineCountOffset[type], _refreshStage[type]);
                if (sourceCode) {
                    //If reading was successful
                    std::string codeString(sourceCode);
                    Util::replaceStringInPlace(codeString, "//__CUSTOM_DEFINES__", shaderSourceHeader);
                    Util::replaceStringInPlace(codeString, "//__CUSTOM_UNIFORMS__", shaderSourceUniforms[type]);
                    //Load our shader and save it in the manager in case a new Shader Program needs it
                    _shaderStage[type] = ShaderManager::getInstance().loadShader(shaderCompileName[type], codeString, type, _refreshStage[type]);
                }
            }

            if (!_shaderStage[type]){ 
                PRINT_FN(Locale::get("WARN_GLSL_SHADER_LOAD"), shaderCompileName[type].c_str())
            }else{
                if (!_shaderStage[type]->compile())
                    ERROR_FN(Locale::get("ERROR_GLSL_SHADER_COMPILE"), _shaderStage[type]->getShaderId());
            }
        }   
    }

    return GFX_DEVICE.loadInContext(/*_threadedLoading ? GFX_LOADING_CONTEXT : */GFX_RENDERING_CONTEXT, DELEGATE_BIND(&glShaderProgram::threadedLoad, this, name));
}

///Cache uniform/attribute locations for shader programs
///When we call this function, we check our name<->address map to see if we queried the location before
///If we did not, ask the GPU to give us the variables address and save it for later use
GLint glShaderProgram::cachedLoc(const std::string& name, const bool uniform){
    //Not loaded or NULL_SHADER
    if (!isHWInitComplete() || _shaderProgramId == 0 || _shaderProgramId == Divide::GLUtil::_invalidObjectID) return -1;
    
    DIVIDE_ASSERT(_linked && _threadedLoadComplete, "glShaderProgram error: tried to query a shader program before linking!");
    const ShaderVarMap::const_iterator& it = _shaderVars.find(name);

    if(it != _shaderVars.end())	return it->second;

    GLint location = uniform ? glGetUniformLocation(_shaderProgramId, name.c_str()) : glGetAttribLocation(_shaderProgramId, name.c_str());

    _shaderVars[name] = location;
    return location;
}

bool glShaderProgram::bind() {
    if(_bound)
        return true;

    //If we did not create the hardware resource, do not try and bind it, as it is invalid
    if (!isHWInitComplete()){
        GL_API::setActiveProgram(nullptr);
        return false;
    }

    DIVIDE_ASSERT(_shaderProgramId != Divide::GLUtil::_invalidObjectID, "glShaderProgram error: tried to bind a shader program with an invalid handle!");

    GL_API::setActiveProgram(this);
    //send default uniforms to GPU for every shader
    return ShaderProgram::bind();
}

void glShaderProgram::unbind(bool resetActiveProgram) {
    if(!_bound) return;

    if(resetActiveProgram) GL_API::setActiveProgram(nullptr);

    ShaderProgram::unbind(resetActiveProgram);
}

void glShaderProgram::Attribute(I32 location, GLdouble value) const {
    if (location == -1) return;

    glVertexAttrib1d(location,value);
}

void glShaderProgram::Attribute(I32 location, GLfloat value) const {
    if (location == -1) return;

    glVertexAttrib1f(location,value);
}

void glShaderProgram::Attribute(I32 location, const vec2<GLfloat>& value) const {
    if (location == -1) return;

    glVertexAttrib2fv(location,value);
}

void glShaderProgram::Attribute(I32 location, const vec3<GLfloat>& value) const {
    if (location == -1) return;

    glVertexAttrib3fv(location,value);
}

void glShaderProgram::Attribute(I32 location, const vec4<GLfloat>& value) const {
    if (location == -1) return;

    glVertexAttrib4fv(location,value);
}

void glShaderProgram::SetSubroutines(ShaderType type, const vectorImpl<U32>& indices) const {
    DIVIDE_ASSERT(_bound && _linked, "glShaderProgram error: tried to set subroutines on an unbound or unlinked program!");
    if (!indices.empty() && indices[0] != GL_INVALID_INDEX)
        glUniformSubroutinesuiv(_shaderStageTable[type], (GLsizei)indices.size(), &indices.front());
    
}

void glShaderProgram::SetSubroutine(ShaderType type, U32 index) const {
    static U32 value[1];
    DIVIDE_ASSERT(_bound && _linked, "glShaderProgram error: tried to set subroutines on an unbound or unlinked program!");
    if (index != GL_INVALID_INDEX){
        value[0] = index;
        glUniformSubroutinesuiv(_shaderStageTable[type], 1, value);
    }
}

U32 glShaderProgram::GetSubroutineUniformCount(ShaderType type) const {
    DIVIDE_ASSERT(_linked, "glShaderProgram error: tried to query subroutines on an unlinked program!");
    
    I32 subroutineCount = 0;
    glGetProgramStageiv(_shaderProgramId, _shaderStageTable[type], GL_ACTIVE_SUBROUTINE_UNIFORMS, &subroutineCount);

    return std::max(subroutineCount, 0);
}

U32 glShaderProgram::GetSubroutineUniformIndex(ShaderType type, const std::string& name) const {
    DIVIDE_ASSERT(_linked, "glShaderProgram error: tried to query subroutines on an unlinked program!");

    return glGetSubroutineUniformLocation(_shaderProgramId, _shaderStageTable[type], name.c_str());
}

U32 glShaderProgram::GetSubroutineIndex(ShaderType type, const std::string& name) const {
    DIVIDE_ASSERT(_linked, "glShaderProgram error: tried to query subroutines on an unlinked program!");

    return glGetSubroutineIndex(_shaderProgramId, _shaderStageTable[type], name.c_str());
}

void glShaderProgram::Uniform(GLint location, GLuint value) const {
    if (location == -1) return;

    if (!_bound) glProgramUniform1ui(_shaderProgramId, location, value);
    else         glUniform1ui(location, value);
}

void glShaderProgram::Uniform(GLint location, GLint value) const {
    if (location == -1) return;
 
    if (!_bound) glProgramUniform1i(_shaderProgramId, location, value);
    else         glUniform1i(location, value);
}

void glShaderProgram::Uniform(GLint location, GLfloat value) const {
    if (location == -1) return;

    if (!_bound) glProgramUniform1f(_shaderProgramId, location, value);
    else         glUniform1f(location, value);
}

void glShaderProgram::Uniform(GLint location, const vec2<GLfloat>& value) const {
    if (location == -1) return;

    if (!_bound) glProgramUniform2fv(_shaderProgramId, location, 1, value);
    else         glUniform2fv(location, 1, value);
}

void glShaderProgram::Uniform(GLint location, const vec2<GLint>& value) const {
    if (location == -1) return;

    if (!_bound) glProgramUniform2iv(_shaderProgramId, location, 1, value);
    else         glUniform2iv(location, 1, value);
}

void glShaderProgram::Uniform(GLint location, const vec2<GLushort>& value) const {
    if (location == -1) return;

    if (!_bound) glProgramUniform2iv(_shaderProgramId, location, 1, vec2<I32>(value.x, value.y));
    else         glUniform2iv(location, 1, vec2<I32>(value.x, value.y));
}

void glShaderProgram::Uniform(GLint location, const vec3<GLfloat>& value) const {
    if (location == -1) return;

    if (!_bound) glProgramUniform3fv(_shaderProgramId, location, 1, value);
    else         glUniform3fv(location, 1, value);
}

void glShaderProgram::Uniform(GLint location, const vec4<GLfloat>& value) const {
    if (location == -1) return;

    if (!_bound) glProgramUniform4fv(_shaderProgramId, location, 1, value);
    else         glUniform4fv(location, 1, value);
}

void glShaderProgram::Uniform(GLint location, const mat3<GLfloat>& value, bool rowMajor) const {
    if (location == -1) return;

    if (!_bound) glProgramUniformMatrix3fv(_shaderProgramId, location, 1, rowMajor, value.mat);
    else         glUniformMatrix3fv(location, 1, rowMajor, value);
}

void glShaderProgram::Uniform(GLint location, const mat4<GLfloat>& value, bool rowMajor) const {
    if (location == -1) return;

    if (!_bound) glProgramUniformMatrix4fv(_shaderProgramId, location, 1, rowMajor, value.mat);
    else         glUniformMatrix4fv(location, 1, rowMajor, value.mat);
}

void glShaderProgram::Uniform(GLint location, const vectorImpl<GLint >& values) const {
    if (values.empty()) return;

    if (!_bound) glProgramUniform1iv(_shaderProgramId, location, (GLsizei)values.size(), &values.front());
    else         glUniform1iv(location, (GLsizei)values.size(), &values.front());
}

void glShaderProgram::Uniform(GLint location, const vectorImpl<GLfloat >& values) const {
    if (values.empty() || location == -1) return;

    if (!_bound) glProgramUniform1fv(_shaderProgramId, location, (GLsizei)values.size(), &values.front());
    else         glUniform1fv(location, (GLsizei)values.size(), &values.front());
}

void glShaderProgram::Uniform(GLint location, const vectorImpl<vec2<GLfloat> >& values) const {
    if (values.empty() || location == -1) return;

    if (!_bound) glProgramUniform2fv(_shaderProgramId, location, (GLsizei)values.size(), values.front());
    else         glUniform2fv(location, (GLsizei)values.size(), values.front());
}

void glShaderProgram::Uniform(GLint location, const vectorImpl<vec3<GLfloat> >& values) const {
    if (values.empty() || location == -1) return;

    if (!_bound) glProgramUniform3fv(_shaderProgramId, location, (GLsizei)values.size(), values.front());
    else         glUniform3fv(location, (GLsizei)values.size(), values.front());
}

void glShaderProgram::Uniform(GLint location, const vectorImpl<vec4<GLfloat> >& values) const {
    if (values.empty() || location == -1) return;

    if (!_bound) glProgramUniform4fv(_shaderProgramId, location, (GLsizei)values.size(), values.front());
    else         glUniform4fv(location, (GLsizei)values.size(), values.front());
}

void glShaderProgram::Uniform(GLint location, const vectorImpl<mat3<F32> >& values, bool rowMajor) const {
    if (values.empty() || location == -1) return;

    if (!_bound) glProgramUniformMatrix3fv(_shaderProgramId, location, (GLsizei)values.size(), rowMajor, values.front());
    else         glUniformMatrix3fv(location, (GLsizei)values.size(), rowMajor, values.front());
}

void glShaderProgram::Uniform(GLint location, const vectorImpl<mat4<GLfloat> >& values, bool rowMajor) const {
    if (values.empty() || location == -1) return;

    if (!_bound) glProgramUniformMatrix4fv(_shaderProgramId, location, (GLsizei)values.size(), rowMajor, values.front());
    else         glUniformMatrix4fv(location, (GLsizei)values.size(), rowMajor, values.front());
}

void glShaderProgram::UniformTexture(GLint location, GLushort slot) {
    if (location == -1) return;
    if (!checkSlotUsage(location, slot)) return;

    if(!_bound) glProgramUniform1i(_shaderProgramId, location, slot);
    else        glUniform1i(location, slot);
}

bool glShaderProgram::checkSlotUsage(GLint location, GLushort slot) {
#ifdef _DEBUG
    const TextureSlotMap::const_iterator& it = _textureSlots.find(slot);
    if (it == _textureSlots.end() || it->second == location){
        _textureSlots[slot] = location;
        return true;
    }
    return false;
#else
    return true;
#endif
}

Commits for Divide-Framework/trunk/Source Code/Hardware/Video/OpenGL/Shaders/glShaderProgram.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]]

285 Diff Diff IonutCava picture IonutCava Wed 02 Jul, 2014 18:33:25 +0000

[Ionut][[BR]]
- Per SGN shader data implementation part 1.75 / 2 [[BR]]
— Upload node data into a SSBO in one single call [[BR]]
- Re-factored LightManager to upload light info and shadow info in single upload calls [[BR]]
- Improved GUIConsole load performance by using a boost::circular_buffer for initial messages [[BR]]

278 Diff Diff IonutCava picture IonutCava Thu 19 Jun, 2014 18:09:59 +0000

[Ionut][[BR]]
- Preliminary work on generic shader function selection infrastructure [[BR]]

277 Diff Diff IonutCava picture IonutCava Tue 17 Jun, 2014 19:27:29 +0000

[Ionut] [[BR]]
- Change PostFX shader to be subroutine-based (instead of using if-else statements) [[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]]

269 Diff Diff IonutCava picture IonutCava Wed 04 Jun, 2014 12:56:45 +0000

[Ionut] [[BR]]
- All texture objects now properly allocate storage using glTextureStorage*D(w-w/o Multisampled) [[BR]]
- Removed useless “format” element from TextureDescriptor. Format is deduced from the internal format specified (RGBA8 uses RGBA. RG32F uses RG) [[BR]]
- Use GLM only with radians [[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]]

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