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
/*
   Copyright (c) 2016 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 _HANDLER_H_
#define _HANDLER_H_

#include "config.h"

#include "Core/Resources/Headers/Resource.h"
#include "Platform/Video/Shaders/Headers/Shader.h"

namespace Divide {

class Camera;
class Material;
class Shader;
class ShaderBuffer;
struct GenericDrawCommand;

FWD_DECLARE_MANAGED_CLASS(ShaderProgram);

class NOINITVTABLE ShaderProgram : public Resource, 
                                   protected GraphicsResource,
                                   public std::enable_shared_from_this<ShaderProgram> {
   public:
    typedef hashMapImpl<ULL, ShaderProgram_ptr> ShaderProgramMap;
    typedef hashMapImpl<ULL, stringImpl> AtomMap;
    typedef std::stack<ShaderProgram_ptr, vectorImpl<ShaderProgram_ptr> > ShaderQueue;
    /// A list of built-in sampler slots. Use these if possible
    enum class TextureUsage : U32 {
        UNIT0 = 0,
        UNIT1 = 1,
        NORMALMAP = 2,
        OPACITY = 3,
        SPECULAR = 4,
        PROJECTION = 5,
        DEPTH = 6,
        REFLECTION = 7,
        REFRACTION = 8,
        COUNT,

        GLOSS = SPECULAR,
        ROUGHNESS = GLOSS
    };

    enum class MemoryBarrierType : U32 {
        BUFFER = 0,
        TEXTURE = 1,
        RENDER_TARGET = 2,
        TRANSFORM_FEEDBACK = 3,
        COUNTER = 4,
        QUERY = 5,
        SHADER_BUFFER = 6,
        ALL = 7,
        COUNT
    };

    explicit ShaderProgram(GFXDevice& context,
                           const stringImpl& name,
                           const stringImpl& resourceLocation,
                           bool asyncLoad);
    virtual ~ShaderProgram();

    virtual bool bind() = 0;
    /// Currently active
    virtual bool isBound() const = 0;
    /// Is the shader ready for drawing?
    virtual bool isValid() const = 0;

    virtual bool update(const U64 deltaTime);
    virtual bool load() override;
    virtual bool unload() override;

    /// Uniforms (update constant buffer for D3D. Use index as location in
    /// buffer)
    virtual void Uniform(const char* ext, U32 value) = 0;
    virtual void Uniform(const char* ext, I32 value) = 0;
    virtual void Uniform(const char* ext, F32 value) = 0;
    virtual void Uniform(const char* ext, const vec2<F32>& value) = 0;
    virtual void Uniform(const char* ext, const vec2<I32>& value) = 0;
    virtual void Uniform(const char* ext, const vec3<F32>& value) = 0;
    virtual void Uniform(const char* ext, const vec3<I32>& value) = 0;
    virtual void Uniform(const char* ext, const vec4<F32>& value) = 0;
    virtual void Uniform(const char* ext, const vec4<I32>& value) = 0;
    virtual void Uniform(const char* ext, const mat3<F32>& value, bool rowMajor = false) = 0;
    virtual void Uniform(const char* ext, const mat4<F32>& value, bool rowMajor = false) = 0;
    virtual void Uniform(const char* ext, const vectorImpl<I32>& values) = 0;
    virtual void Uniform(const char* ext, const vectorImpl<F32>& values) = 0;
    virtual void Uniform(const char* ext, const vectorImpl<vec2<F32> >& values) = 0;
    virtual void Uniform(const char* ext, const vectorImpl<vec3<F32> >& values) = 0;
    virtual void Uniform(const char* ext, const vectorImplAligned<vec4<F32> >& values) = 0;
    virtual void Uniform(const char* ext, const vectorImpl<mat3<F32> >& values, bool rowMajor = false) = 0;
    virtual void Uniform(const char* ext, const vectorImplAligned<mat4<F32> >& values, bool rowMajor = false) = 0;

    inline void Uniform(const char* ext, TextureUsage slot) {
        Uniform(ext, to_int(slot));
    }
        
    inline void Uniform(const char* ext, bool value) {
        Uniform(ext, value ? 1 : 0);
    }

    virtual I32 getUniformLocation(const char* name) = 0;
    /// Subroutine
    virtual void SetSubroutines(ShaderType type, const vectorImpl<U32>& indices) const = 0;
    virtual void SetSubroutine(ShaderType type, U32 index) const = 0;
    virtual U32 GetSubroutineIndex(ShaderType type, const char* name) const = 0;
    virtual U32 GetSubroutineUniformLocation(ShaderType type, const char* name) const = 0;
    virtual U32 GetSubroutineUniformCount(ShaderType type) const = 0;
    /// Uniform+UniformTexture implementation
    virtual void Uniform(I32 location, U32 value) = 0;
    virtual void Uniform(I32 location, I32 value) = 0;
    virtual void Uniform(I32 location, F32 value) = 0;
    virtual void Uniform(I32 location, const vec2<F32>& value) = 0;
    virtual void Uniform(I32 location, const vec2<I32>& value) = 0;
    virtual void Uniform(I32 location, const vec3<F32>& value) = 0;
    virtual void Uniform(I32 location, const vec3<I32>& value) = 0;
    virtual void Uniform(I32 location, const vec4<F32>& value) = 0;
    virtual void Uniform(I32 location, const vec4<I32>& value) = 0;
    virtual void Uniform(I32 location,
                         const mat3<F32>& value,
                         bool rowMajor = false) = 0;
    virtual void Uniform(I32 location,
                         const mat4<F32>& value,
                         bool rowMajor = false) = 0;
    virtual void Uniform(I32 location, const vectorImpl<I32>& values) = 0;
    virtual void Uniform(I32 location, const vectorImpl<F32>& values) = 0;
    virtual void Uniform(I32 location,
                         const vectorImpl<vec2<F32> >& values) = 0;
    virtual void Uniform(I32 location,
                         const vectorImpl<vec3<F32> >& values) = 0;
    virtual void Uniform(I32 location,
                         const vectorImplAligned<vec4<F32> >& values) = 0;
    virtual void Uniform(I32 location,
                         const vectorImpl<mat3<F32> >& values,
                         bool rowMajor = false) = 0;
    virtual void Uniform(I32 location,
                         const vectorImplAligned<mat4<F32> >& values,
                         bool rowMajor = false) = 0;

    virtual void DispatchCompute(U32 xGroups, U32 yGroups, U32 zGroups) = 0;

    virtual void SetMemoryBarrier(MemoryBarrierType type) = 0;

    inline void Uniform(I32 location, TextureUsage slot) {
        Uniform(location, to_ubyte(slot));
    }

    inline void Uniform(I32 location, bool value) {
        Uniform(location, value ? 1 : 0);
    }

    virtual void attachShader(Shader* const shader,
                              const bool refresh = false) = 0;
    virtual void detachShader(Shader* const shader) = 0;
    /// ShaderProgram object id (i.e.: for OGL _shaderProgramID =
    /// glCreateProgram())
    inline U32 getID() const { return _shaderProgramID; }
    ///  Calling recompile will re-create the marked shaders from source files
    ///  and update them in the ShaderManager if needed
    void recompile(const bool vertex,
                   const bool fragment,
                   const bool geometry = false,
                   const bool tessellation = false,
                   const bool compute = false);
    /// Add a define to the shader. The defined must not have been added
    /// previously
    void addShaderDefine(const stringImpl& define);
    /// Remove a define from the shader. The defined must have been added
    /// previously
    void removeShaderDefine(const stringImpl& define);

    /** ------ BEGIN EXPERIMENTAL CODE ----- **/
    inline vectorAlg::vecSize getFunctionCount(ShaderType shader, U8 LoD) {
        return _functionIndex[to_uint(shader)][LoD].size();
    }

    inline void setFunctionCount(ShaderType shader,
                                 U8 LoD,
                                 vectorAlg::vecSize count) {
        _functionIndex[to_uint(shader)][LoD].resize(count, 0);
    }

    inline void setFunctionCount(ShaderType shader, vectorAlg::vecSize count) {
        for (U8 i = 0; i < Config::SCENE_NODE_LOD; ++i) {
            setFunctionCount(shader, i, count);
        }
    }

    inline void setFunctionIndex(ShaderType shader,
                                 U8 LoD,
                                 U32 index,
                                 U32 functionEntry) {
        U32 shaderTypeValue = to_uint(shader);

        if (_functionIndex[shaderTypeValue][LoD].empty()) {
            return;
        }

        DIVIDE_ASSERT(index < _functionIndex[shaderTypeValue][LoD].size(),
                      "ShaderProgram error: Invalid function index specified "
                      "for update!");
        if (_availableFunctionIndex[shaderTypeValue].empty()) {
            return;
        }

        DIVIDE_ASSERT(
            functionEntry < _availableFunctionIndex[shaderTypeValue].size(),
            "ShaderProgram error: Specified function entry does not exist!");
        _functionIndex[shaderTypeValue][LoD][index] =
            _availableFunctionIndex[shaderTypeValue][functionEntry];
    }

    inline U32 addFunctionIndex(ShaderType shader, U32 index) {
        U32 shaderTypeValue = to_uint(shader);

        _availableFunctionIndex[shaderTypeValue].push_back(index);
        return U32(_availableFunctionIndex[shaderTypeValue].size() - 1);
    }
    /** ------ END EXPERIMENTAL CODE ----- **/

    //==================== static methods ===============================//
    static void idle();
    static void initStaticData();
    static void destroyStaticData();
    static bool updateAll(const U64 deltaTime);
    /// Queue a shaderProgram recompile request
    static bool recompileShaderProgram(const stringImpl& name);
    static const stringImpl& shaderFileRead(const stringImpl& atomName, const stringImpl& location);
    static void shaderFileRead(const stringImpl& filePath, bool buildVariant, stringImpl& sourceCodeOut);
    static void shaderFileWrite(const stringImpl& atomName, const char* sourceCode);
    /// Remove a shaderProgram from the program cache
    static bool unregisterShaderProgram(const stringImpl& name);
    /// Add a shaderProgram to the program cache
    static void registerShaderProgram(const stringImpl& name, const ShaderProgram_ptr& shaderProgram);
    /// Bind the null shader
    static bool unbind();
    /// Return a default shader used for general purpose rendering
    static const ShaderProgram_ptr& defaultShader();

   protected:
    /// Shaders loaded from files are kept as atoms
    static AtomMap _atoms;
    /// Used to render geometry without valid materials.
    /// Should emulate the basic fixed pipeline functions (no lights, just color and texture)
    static ShaderProgram_ptr _imShader;
    /// Pointer to a shader that we will perform operations on
    static ShaderProgram_ptr _nullShader;
    /// Only 1 shader program per frame should be recompiled to avoid a lot of stuttering
    static ShaderQueue _recompileQueue;
    /// Shader program cache
    static ShaderProgramMap _shaderPrograms;

    static SharedLock _programLock;
   protected:
    template <typename T>
    friend class ImplResourceLoader;

    bool _asyncLoad;
    std::atomic_bool _linked;
    U32 _shaderProgramID;  //<not thread-safe. Make sure assignment is protected
    // with a mutex or something
    /// A list of preprocessor defines
    vectorImpl<stringImpl> _definesList;
    /// ID<->shaders pair
    typedef hashMapImpl<U32, Shader*> ShaderIDMap;
    ShaderIDMap _shaderIDMap;
    std::array<bool, to_const_uint(ShaderType::COUNT)> _refreshStage;

   private:
    std::array<std::array<vectorImpl<U32>, Config::SCENE_NODE_LOD>, to_const_uint(ShaderType::COUNT)> _functionIndex;
    std::array<vectorImpl<U32>, to_const_uint(ShaderType::COUNT)>  _availableFunctionIndex;
};

};  // namespace Divide
#endif

Commits for Divide-Framework/trunk/Source Code/Platform/Video/Shaders/Headers/ShaderProgram.h

Diff revisions: vs.
Revision Author Commited Message
712 Diff Diff IonutCava picture IonutCava Tue 24 May, 2016 16:18:37 +0000

[IonutCava]
- Added the concept of “buffer” to be used by GenericVertexData and ShaderBuffer without caring if it’s persistent or not.
— Persistent buffers handle their own locking instead of relying on the parent class
- HiZ occlusion culling fixes and optimizations

710 Diff Diff IonutCava picture IonutCava Fri 20 May, 2016 16:24:40 +0000

[IonutCava]
- Code cleanup
- Initial work on Scene loading and unloading with and without unloading assets:
— Need to change AIManager from a Singleton to a per-scene component

709 Diff Diff IonutCava picture IonutCava Thu 19 May, 2016 16:21:46 +0000

[IonutCava]
- Massive rewrite of the resource system:
— ResourceCache now uses a map of weak pointers and passes shared pointers to the call point of CreateResource
— RemoveResource is no longer needed, but resource based smart pointers use a custom deleter that calls unload()
— Keep a shared_ptr of the resource in the entity that needs it and pass shared_ptr references from getter methods
-— All of this removed the need for calls to RemoveResource, REGISTER_TRACKED_DEPENDENCY and UNREGISTER_TRACKED_DEPENDENCY reducing the number of mutex locks and atomic exchanges
- Singleton cleanup:
— Removed ShaderManager singleton and merged it’s data and responsibilities in static methods in both ShaderProgram and Shader classes.
Explanation: Due to the complex interdependency chains in the system, copying, updating, tracking the cache in a thread safe way became a lot more slower than a straight forward smart pointer based implementation. (e.g. scene graph nodes have 3d objects and material instances, 3d objects have materials, materials have textures and shaders, etc)

706 Diff Diff IonutCava picture IonutCava Fri 13 May, 2016 16:29:40 +0000

[IonutCava]
- Renamed LightManager to LightPool and changed it from a Singleton to a scene specific pointer
- More scene load / unload updates (changing scenes now works properly!)
- Allowed GUI interface to hold per-scene elements and only render relevant ones
- Reduced dependencies between nodes, scenemanager, scene, loaders and kernel
- Removed Reflector base class as it was useless and integrate Water class with the Reflection system already in place
- Extended RenderingComponent’s reflection system to allow refraction as well

692 Diff Diff IonutCava picture IonutCava Wed 27 Apr, 2016 16:24:26 +0000

[IonutCava]
- Resource system cleanup:
— Resource name and resource file location (if any) is now passed only via explicit constructors! (ResourceDescriptors already contain this data, so why use setters?)
- Fix a bug with ortho projection matrix calculation (set m[3][3] to 1. this was skipped when the identity() call was changed to zero() in the ortho() function)
— This also fixed text rendering

671 Diff Diff IonutCava picture IonutCava Fri 08 Apr, 2016 16:26:49 +0000

[Ionut]
- Custom memory allocation system part 1:
— Add http://www.codeproject.com/Articles/1089905/A-Custom-STL-std-allocator-Replacement-Improves-Pe
— Add custom allocators to strings and vectors
— Add custom allocators to a few test classes
— No support for aligned memory yet, so vec4<F32> and mat4<F32> vectors use the old allocation system
- Replace more std::async call with our custom task system

648 Diff Diff IonutCava picture IonutCava Sun 21 Feb, 2016 16:32:52 +0000

[IonutCava]
- Update copyright notice
- Move BoundingBox and BoundingSphere to a new BoundsComponent
— Add a temp hack in SceneGraphNode to update these

622 Diff Diff IonutCava picture IonutCava Thu 14 Jan, 2016 17:18:49 +0000

[IonutCava]
- Remove onCameraUpdate call from LightManager and SceneGraph as it’s not needed
- Remove special threading handlers from Resource class as very few derived classes use them for now
— Use ResourceState to check current loading state
- Use insertion sort for particles as most entries should already be sorted from the previous frame
- Use async RenderBin sorting system

619 Diff Diff IonutCava picture IonutCava Fri 08 Jan, 2016 16:23:28 +0000

[IonutCava]
- Memory allocation optimizations
- Large VBO allocation system
- More terrain fixes
- Temporarily disable water and vegetation systems

591 IonutCava picture IonutCava Wed 02 Dec, 2015 17:17:23 +0000

[IonutCava]
- More work on the ForwardPlus renderer
- Singleton cleanup
- First steps for reducing scope of GFXDevice class