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
/*
   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 _MATERIAL_H_
#define _MATERIAL_H_

#include "core.h"
#include "Utility/Headers/XMLParser.h"
#include "Utility/Headers/StateTracker.h"
#include "Core/Resources/Headers/Resource.h"
#include "Core/Resources/Headers/ResourceDescriptor.h"

#include "Hardware/Video/Headers/RenderAPIEnums.h"
#include "Hardware/Video/Shaders/Headers/ShaderProgram.h"

namespace Divide {

class Texture;
class RenderStateBlock;
class ResourceDescriptor;
class RenderStateBlockDescriptor;
enum RenderStage;
enum BlendProperty;

class Material : public Resource {
public:
  enum BumpMethod {
        BUMP_NONE = 0,   //<Use phong
        BUMP_NORMAL = 1, //<Normal mapping
        BUMP_PARALLAX = 2,
        BUMP_RELIEF = 3,
        BumpMethod_PLACEHOLDER = 4
    };

    /// How should each texture be added
    enum TextureOperation {
        TextureOperation_Multiply = 0x0,
        TextureOperation_Add = 0x1,
        TextureOperation_Subtract = 0x2,
        TextureOperation_Divide = 0x3,
        TextureOperation_SmoothAdd = 0x4,
        TextureOperation_SignedAdd = 0x5,
        TextureOperation_Decal = 0x6,
        TextureOperation_Replace = 0x7,
        TextureOperation_PLACEHOLDER = 0x8
    };

    enum TranslucencySource {
        TRANSLUCENT_DIFFUSE = 0,
        TRANSLUCENT_OPACITY_MAP,
        TRANSLUCENT_DIFFUSE_MAP,
        TRANSLUCENT_NONE
    };
    /// Not used yet but implemented for shading model selection in shaders
    /// This enum matches the ASSIMP one on a 1-to-1 basis
    enum ShadingMode {
        SHADING_FLAT = 0x1,
        SHADING_PHONG = 0x2,
        SHADING_BLINN_PHONG = 0x3,
        SHADING_TOON = 0x4,
        SHADING_OREN_NAYAR = 0x5,
        SHADING_COOK_TORRANCE = 0x6,
        ShadingMode_PLACEHOLDER = 0xb
    };

    /// ShaderData stores information needed by the shader code to properly shade objects
    struct ShaderData{
        vec4<F32> _diffuse;  /* diffuse component */
        vec4<F32> _ambient;  /* ambient component */
        vec4<F32> _specular; /* specular component*/
        vec4<F32> _emissive; /* emissive component*/
        F32 _shininess;      /* specular exponent */
        I32 _textureCount;

        ShaderData() : _textureCount(0),
            _ambient(vec4<F32>(vec3<F32>(1.0f) / 5.0f, 1)),
            _diffuse(vec4<F32>(vec3<F32>(1.0f) / 1.5f, 1)),
            _specular(0.8f, 0.8f, 0.8f, 1.0f),
            _emissive(0.6f, 0.6f, 0.6f, 1.0f),
            _shininess(5)
        {
        }

        ShaderData& operator=(const ShaderData& other) {
            _diffuse.set(other._diffuse);
            _ambient.set(other._ambient); 
            _specular.set(other._specular);
            _emissive.set(other._emissive);
            _shininess = other._shininess;     
            _textureCount = other._textureCount;
            return *this;
        }
    };

    /// ShaderInfo stores information about the shader programs used by this material
    struct ShaderInfo {

        enum ShaderCompilationStage {
            SHADER_STAGE_REQUESTED = 0,
            SHADER_STAGE_QUEUED = 1,
            SHADER_STAGE_COMPUTED = 2,
            SHADER_STAGE_ERROR = 3,
            ShaderCompilationStage_PLACEHOLDER = 4
        };

        ShaderProgram* _shaderRef;
        stringImpl _shader;
        ShaderCompilationStage _shaderCompStage;
        bool _isCustomShader;
        vectorImpl<stringImpl> _shaderDefines;

        ShaderProgram* const getProgram() const;

        inline StateTracker<bool>& getTrackedBools() { return _trackedBools; }

        ShaderInfo()
        {
            _shaderRef = nullptr;
            _shader = "";
            _shaderCompStage = ShaderCompilationStage_PLACEHOLDER;
            _isCustomShader = false;
            for (U8 i = 0; i < ShaderType_PLACEHOLDER; ++i){
                memset(_shadingFunction[i], 0, BumpMethod_PLACEHOLDER * sizeof(U32));
            }
        }

        ShaderInfo& operator=(const ShaderInfo& other){
            _shaderRef = other.getProgram();
            _shaderRef->AddRef();
            _shader = other._shader;
            _shaderCompStage = other._shaderCompStage;
            _isCustomShader = other._isCustomShader;
            for (U8 i = 0; i < ShaderType_PLACEHOLDER; ++i){
                for (U8 j = 0; j < BumpMethod_PLACEHOLDER; ++j){
                    _shadingFunction[i][j] = other._shadingFunction[i][j];
                }
            }
            _trackedBools = other._trackedBools;
            return *this;
        }

        U32 _shadingFunction[ShaderType_PLACEHOLDER][BumpMethod_PLACEHOLDER];

    protected:
        StateTracker<bool> _trackedBools;
    };
  
public:
    Material();
    ~Material();

    /// Return a new instance of this material with the name composed of the base material's name and the give name suffix.
    /// Call RemoveResource on the returned pointer to free memory. (clone calls CreateResource internally!)
    Material* clone(const stringImpl& nameSuffix);
    bool unload();
    void update(const U64 deltaTime);

    inline void setDiffuse(const vec4<F32>& value)  { 
        _dirty = true; 
        _shaderData._diffuse = value;  
        if (value.a < 0.95f) {
            _translucencyCheck  = false;
        }
    }

    inline void setAmbient(const vec4<F32>& value)  { _dirty = true; _shaderData._ambient = value;  }
    inline void setSpecular(const vec4<F32>& value) { _dirty = true; _shaderData._specular = value; }
    inline void setEmissive(const vec3<F32>& value) { _dirty = true; _shaderData._emissive = value; }

    inline void setHardwareSkinning(const bool state) { _dirty = true; _hardwareSkinning = state; }
    inline void setOpacity(F32 value)   { _dirty = true; _shaderData._diffuse.a = value; _translucencyCheck = false; }
    inline void setShininess(F32 value) { _dirty = true; _shaderData._shininess = value; }

    inline void useAlphaTest(const bool state)          { _useAlphaTest = state; }
    inline void setShadingMode(const ShadingMode& mode) { _shadingMode = mode; }

    void setDoubleSided(const bool state, const bool useAlphaTest = true);
    void setTexture(ShaderProgram::TextureUsage textureUsageSlot, 
                    Texture* const texture, 
                    const TextureOperation& op = TextureOperation_Replace);
    /// Add a texture <-> bind slot pair to be bound with the default textures on each "bindTexture" call
    inline void addCustomTexture(Texture* texture, U32 offset) {
        // custom textures are not material dependencies!
        _customTextures.push_back(std::make_pair(texture, offset));
    }

    /// Remove the custom texture assigned to the specified offset
    inline bool removeCustomTexture(U32 index) {
        vectorImpl<std::pair<Texture*, U32 > >::iterator it = std::find_if(_customTextures.begin(), _customTextures.end(), 
                                                                            [&index]( const std::pair<Texture*, U32>& tex )->bool {
                                                                                return tex.second == index;
                                                                            });
        if(it == _customTextures.end())
            return false;

        _customTextures.erase(it);

        return true;
    }
        
    ///Set the desired bump mapping method.
    void setBumpMethod(const BumpMethod& newBumpMethod);
    ///Shader modifiers add tokens to the end of the shader name.
    ///Add as many tokens as needed but separate them with a ".". i.e: "Tree.NoWind.Glow"
    inline void addShaderModifier(const stringImpl& shaderModifier) { _shaderModifier = shaderModifier; }
    ///Shader defines, separated by commas, are added to the generated shader
    ///The shader generator appends "#define " to the start of each define
    ///For example, to define max light count and max shadow casters add this string:
    ///"MAX_LIGHT_COUNT 4, MAX_SHADOW_CASTERS 2"
    ///The above strings becomes, in the shader:
    ///#define MAX_LIGHT_COUNT 4
    ///#define MAX_SHADOW_CASTERS 2
    inline void addShaderDefines(RenderStage renderStage, const stringImpl& shaderDefines) {
        _shaderInfo[renderStage]._shaderDefines.push_back(shaderDefines);
    }

    inline void addShaderDefines(const stringImpl& shaderDefines)	{
        addShaderDefines(FINAL_STAGE, shaderDefines);
        addShaderDefines(Z_PRE_PASS_STAGE, shaderDefines);
        addShaderDefines(SHADOW_STAGE, shaderDefines);
        addShaderDefines(REFLECTION_STAGE, shaderDefines);
    }

    ///toggle multi-threaded shader loading on or off for this material
    inline void setShaderLoadThreaded(const bool state) {_shaderThreadedLoad = state;}
    void setShaderProgram(const stringImpl& shader, 
                          const RenderStage& renderStage, 
                          const bool computeOnAdd, 
                          const DELEGATE_CBK<>& shaderCompileCallback = DELEGATE_CBK<>());
    inline void setShaderProgram(const stringImpl& shader, 
                                 const bool computeOnAdd, 
                                 const DELEGATE_CBK<>& shaderCompileCallback = DELEGATE_CBK<>()){
        setShaderProgram(shader, FINAL_STAGE, computeOnAdd, shaderCompileCallback);
        setShaderProgram(shader, Z_PRE_PASS_STAGE, computeOnAdd, shaderCompileCallback);
        setShaderProgram(shader, SHADOW_STAGE, computeOnAdd, shaderCompileCallback);
        setShaderProgram(shader, REFLECTION_STAGE, computeOnAdd, shaderCompileCallback);
    }
    size_t setRenderStateBlock(const RenderStateBlockDescriptor& descriptor, const RenderStage& renderStage);
    
    inline void setParallaxFactor(F32 factor) { _parallaxFactor = std::min(0.01f, factor); }

    void getSortKeys(I32& shaderKey, I32& textureKey) const;

    inline void getMaterialMatrix(mat4<F32>& retMatrix) const {
        retMatrix.setCol(0,_shaderData._ambient);
        retMatrix.setCol(1,_shaderData._diffuse);
        retMatrix.setCol(2,_shaderData._specular);
        retMatrix.setCol(3,vec4<F32>(_shaderData._emissive, _shaderData._shininess));
    }

    inline F32 getParallaxFactor() const { return _parallaxFactor;}
    inline U8  getTextureCount()   const { return _shaderData._textureCount;}

                    size_t            getRenderStateBlock(RenderStage currentStage);
    inline       Texture*	 const getTexture(ShaderProgram::TextureUsage textureUsage) {return _textures[textureUsage];}
                ShaderInfo&           getShaderInfo(RenderStage renderStage = FINAL_STAGE);
    
    inline const TextureOperation& getTextureOperation() const { return _operation; }
    inline const ShaderData&       getShaderData()       const { return _shaderData; }
    inline const ShadingMode&      getShadingMode()      const { return _shadingMode; }
    inline const BumpMethod&       getBumpMethod()       const { return _bumpMethod; }

    void bindTextures();

    void clean();
    bool isTranslucent();

    inline void dumpToFile(bool state) { _dumpToFile  = state;}
    inline bool isDirty()       const {return _dirty;}
    inline bool isDoubleSided() const {return _doubleSided;}
    inline bool useAlphaTest()  const {return _useAlphaTest;}

    // Checks if the shader needed for the current stage is already constructed. Returns false if the shader was already ready.
    bool computeShader(const RenderStage& renderStage, const bool computeOnAdd, const DELEGATE_CBK<>& shaderCompileCallback); 
    
    static void unlockShaderQueue()   {_shaderQueueLocked = false; }
    static void serializeShaderLoad(const bool state) { _serializeShaderLoad = state; }

private:
    void recomputeShaders();
    void computeShaderInternal();
    void setShaderProgramInternal(const stringImpl& shader, 
                                  const RenderStage& renderStage, 
                                  const bool computeOnAdd, 
                                  const DELEGATE_CBK<>& shaderCompileCallback);

    static bool isShaderQueueLocked() {
        return _shaderQueueLocked; 
    }

    static void lockShaderQueue() {
        if(_serializeShaderLoad) {
        _shaderQueueLocked = true; 
        }
    }
    
private:
    static bool _shaderQueueLocked;
    static bool _serializeShaderLoad;

    std::queue<std::tuple<RenderStage, ResourceDescriptor, DELEGATE_CBK<> >> _shaderComputeQueue;
    ShadingMode _shadingMode;
    stringImpl _shaderModifier; //<use for special shader tokens, such as "Tree"
    vectorImpl<TranslucencySource > _translucencySource;
    F32 _parallaxFactor; //< parallax/relief factor (higher value > more pronounced effect)
    bool _dirty;
    bool _dumpToFile;
    bool _translucencyCheck;
    bool _useAlphaTest; //< use discard if true / blend if otherwise
    bool _doubleSided;
    bool _hardwareSkinning;     ///< Use shaders that have bone transforms implemented
    typedef hashMapImpl<RenderStage, ShaderInfo, hashAlg::hash<I32>> shaderInfoMap;
    shaderInfoMap _shaderInfo;

    bool        _shaderThreadedLoad;
    bool        _computedShaderTextures;//<if we should recompute only fragment shader on texture change
    /// use this map to add more render states mapped to a specific state
    /// 3 render state's: Normal, reflection and shadow
    typedef hashMapImpl<RenderStage, size_t /*renderStateBlockHash*/, hashAlg::hash<I32>> renderStateBlockMap;
    renderStateBlockMap _defaultRenderStates;

    /// use this map to add textures to the material
    vectorImpl<Texture* > _textures;
    vectorImpl<std::pair<Texture*, U32> > _customTextures;

    /// use the below map to define texture operation
    TextureOperation _operation;

    BumpMethod _bumpMethod;

    ShaderData _shaderData;
};

}; //namespace Divide

#endif

Commits for Divide-Framework/trunk/Source Code/Geometry/Material/Headers/Material.h

Diff revisions: vs.
Revision Author Commited Message
331 Diff Diff IonutCava picture IonutCava Sat 06 Dec, 2014 20:53:45 +0000

[Ionut]
- Limited line length to 132 characters to improve readability and diff-comparisons
- Refactored memory allocation/deallocation functions
- Fixed a few compatibility issues with HashMap.h
- Fixed a bug in GPU Skinning shaders (cast a float to int)

329 Diff Diff IonutCava picture IonutCava Tue 07 Oct, 2014 12:51:37 +0000

[Ionut]
- Modified material class and shaders to support multiple BRDFs (currently, only Flat, Phong and Blinn-Phong supported with Cook-Torrance and Oren-Nayar in future commits)
- Optimized transform updates and queries
- Fixed an indirect draw command (no buffer was bound to GL_DRAW_INDIRECT_BUFFER, violating a core requirement)

328 Diff Diff IonutCava picture IonutCava Sat 04 Oct, 2014 18:03:36 +0000

[Ionut]
- Added per SceneGraphNode material instances. (Cloned from the SceneNode’s material)
- Improved shader loading for materials

325 Diff Diff IonutCava picture IonutCava Wed 17 Sep, 2014 20:06:13 +0000

[Ionut]
- Reworked transform system:
— Parent transform chain system moved from Transform class to the PhysicsComponent
— PhysicsComponent now returns all transform values needed both global and local (still needs heavy optimization and caching)

- Reworked SceneGraph node management:
— Proper ref counting of SceneNodes and proper removing of resource (ResourceCache is now empty on destruction, as it should be)
— Removed parent transform tracking as that’s the PhysicsComponent’s responsibility
— Only nodes loaded via the ResourceCache are allowed to be added to the SceneGraph (added proper loaders for Impostors, Sky, etc)

- Optimized some of the math classes (mat4, mat3)

321 Diff Diff IonutCava picture IonutCava Wed 03 Sep, 2014 22:05:15 +0000

[Ionut]
- Added support (and enabled by default) for the EASTL library (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html / https://github.com/paulhodge/EASTL)
— Strings, vectors and hash_maps can be combined from EASTL, STL and Boost (not all combinations work. e.g. EASTL strings with STL/Boost containers due to the lack of a proper hash function)

318 Diff Diff IonutCava picture IonutCava Sat 30 Aug, 2014 17:35:53 +0000

[Ionut]
- Wrapped the entire code in a “Divide” namespace
- VertexBuffers now call “shrink_to_fit” on all internal data storage
- Improved some vector performance by preferring “emplace_back” instead of “push_back” + proepr usage of reserve / resize
- Wrapped OIS specific types and classes in Divide::Input namespace
- Added the messageBox.layout file (forgot it in the previous few commits)

296 Diff Diff k1ngp1n picture k1ngp1n Sun 03 Aug, 2014 14:54:21 +0000

[Ionut]
- nVidia compatibility fixes (GUI, shadows, post-processing)
- Texture bind slots are now part of ShaderProgram class
- Renamed ForwardRenderer class to ForwardPlusRenderer and moved ligh grid creation to it
- More code cleanups and comments

292 Diff Diff k1ngp1n picture k1ngp1n Mon 28 Jul, 2014 20:23:56 +0000

[Ionut]
- More nVidia compatibility issues (including the ability to disable persistent mapped buffer altogether. Thanks nsight ....)
- Cross-platform compatibility fixes for types (custom types now mirror types in stdint.h and are now typdefed instead of defined)
- Removed redundant files

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

281 IonutCava picture IonutCava Sat 28 Jun, 2014 20:55:30 +0000

[Ionut] [[BR]]
- Added a basic and primitive state tracking class [[BR]]