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

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

#include "Managers/Headers/FrameListenerManager.h"

#include "Platform/Video/Headers/RenderAPIEnums.h"
#include "Platform/Video/Textures/Headers/Texture.h"
#include "Platform/Video/Shaders/Headers/ShaderProgram.h"

namespace Divide {

class RenderStateBlock;
class ResourceDescriptor;
class RenderStateBlock;
enum class RenderStage : U32;
enum class BlendProperty : U32;

class Material : public Resource, public FrameListener {
   public:
    enum class BumpMethod : U32 {
        NONE = 0,    //<Use phong
        NORMAL = 1,  //<Normal mapping
        PARALLAX = 2,
        RELIEF = 3,
        COUNT
    };

    /// How should each texture be added
    enum class TextureOperation : U32 {
        MULTIPLY = 0,
        ADD = 1,
        SUBTRACT = 2,
        DIVIDE = 3,
        SMOOTH_ADD = 4,
        SIGNED_ADD = 5,
        DECAL = 6,
        REPLACE = 7,
        COUNT
    };

    enum class TranslucencySource : U32 {
        DIFFUSE = 0,
        OPACITY_MAP,
        DIFFUSE_MAP,
        NONE,
        COUNT
    };
    /// Not used yet but implemented for shading model selection in shaders
    /// This enum matches the ASSIMP one on a 1-to-1 basis
    enum class ShadingMode : U32 {
        FLAT = 0x1,
        PHONG = 0x2,
        BLINN_PHONG = 0x3,
        TOON = 0x4,
        OREN_NAYAR = 0x5,
        COOK_TORRANCE = 0x6,
        COUNT
    };

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

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

        ShaderData& operator=(const ShaderData& other) {
            _diffuse.set(other._diffuse);
            _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 class ShaderCompilationStage : U32 {
            REQUESTED = 0,
            QUEUED = 1,
            COMPUTED = 2,
            UNHANDLED = 3,
            PENDING = 4,
            COUNT
        };

        bool _customShader;
        ShaderProgram_ptr _shaderRef;
        stringImpl _shader;
        RenderStage _stage;
        std::atomic<ShaderCompilationStage> _shaderCompStage;
        vectorImplAligned<stringImpl> _shaderDefines;

        const ShaderProgram_ptr& getProgram() const;

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

        ShaderInfo()
        {
            _customShader = false;
            _shaderRef = nullptr;
            _shader.clear();
            _shaderCompStage = ShaderCompilationStage::UNHANDLED;
            _stage = RenderStage::COUNT;

            for (U32 i = 0; i < to_const_uint(ShaderType::COUNT); ++i) {
                _shadingFunction[i].fill(0);
            }
        }

        ShaderInfo& operator=(const ShaderInfo& other) {
            _customShader = other._customShader;
            _shaderRef = other._shaderRef;
            _shader = other._shader;
            _shaderCompStage.store(other._shaderCompStage);
            for (U32 i = 0; i < to_const_uint(ShaderType::COUNT); ++i) {
                for (U32 j = 0; j < to_const_uint(BumpMethod::COUNT); ++j) {
                    _shadingFunction[i][j] = other._shadingFunction[i][j];
                }
            }
            _trackedBools = other._trackedBools;
            return *this;
        }

        std::array<std::array<U32, to_const_uint(BumpMethod::COUNT)>,
                   to_const_uint(ShaderType::COUNT)> _shadingFunction;

       protected:
        StateTracker<bool> _trackedBools;
    };

   public:
    explicit Material(const stringImpl& name);
    ~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_ptr clone(const stringImpl& nameSuffix);
    bool unload();
    void update(const U64 deltaTime);

    inline void setShaderData(const ShaderData& other) {
        _dirty = true;
        _shaderData = other;
        _translucencyCheck = true;
    }

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

    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 = true;
    }

    inline void setShininess(F32 value) {
        _dirty = true;
        _shaderData._shininess = value;
    }

    void setShadingMode(const ShadingMode& mode);

    inline void useAlphaTest(const bool state) { _useAlphaTest = state; }
    
    // Should the shaders be computed on add? Should reflections be always parsed? Etc
    inline void setHighPriority(const bool state) { _highPriority = state; }

    void setDoubleSided(const bool state, const bool useAlphaTest = true);
    bool setTexture(ShaderProgram::TextureUsage textureUsageSlot,
                    const Texture_ptr& tex,
                    const TextureOperation& op = TextureOperation::REPLACE);
    /// Add a texture <-> bind slot pair to be bound with the default textures
    /// on each "bindTexture" call
    void addCustomTexture(const Texture_ptr& texture, U8 offset);

    /// Remove the custom texture assigned to the specified offset
    bool removeCustomTexture(U8 index);

    /// 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(RenderStage renderStage, const stringImpl& shaderModifier) {
        _shaderModifier[to_uint(renderStage)] = shaderModifier;
    }
    inline void addShaderModifier(const stringImpl& shaderModifier) {
        addShaderModifier(RenderStage::DISPLAY, shaderModifier);
        addShaderModifier(RenderStage::Z_PRE_PASS, shaderModifier);
        addShaderModifier(RenderStage::SHADOW, shaderModifier);
        addShaderModifier(RenderStage::REFLECTION, 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 setShaderDefines(RenderStage renderStage,
                                 const stringImpl& shaderDefines) {
        vectorImplAligned<stringImpl>& defines =
            _shaderInfo[to_uint(renderStage)]._shaderDefines;
        if (std::find(std::begin(defines), std::end(defines), shaderDefines) ==
            std::end(defines)) {
            defines.push_back(shaderDefines);
        }
    }

    inline void setShaderDefines(const stringImpl& shaderDefines) {
        setShaderDefines(RenderStage::DISPLAY, shaderDefines);
        setShaderDefines(RenderStage::Z_PRE_PASS, shaderDefines);
        setShaderDefines(RenderStage::SHADOW, shaderDefines);
        setShaderDefines(RenderStage::REFLECTION, 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,
        RenderStage renderStage,
        const bool computeOnAdd);

    inline void setShaderProgram(
        const stringImpl& shader,
        const bool computeOnAdd) {
        setShaderProgram(shader, RenderStage::DISPLAY, computeOnAdd);
        setShaderProgram(shader, RenderStage::Z_PRE_PASS, computeOnAdd);
        setShaderProgram(shader, RenderStage::SHADOW, computeOnAdd);
        setShaderProgram(shader, RenderStage::REFLECTION, computeOnAdd);
    }

    inline void setRenderStateBlock(size_t renderStateBlockHash,
                                    RenderStage renderStage,
                                    I32 variant = -1) {
        if (variant < 0 || variant >= _defaultRenderStates[to_uint(renderStage)].size()) {
            for (size_t& state : _defaultRenderStates[to_uint(renderStage)]) {
              state  = renderStateBlockHash;
            }
        } else {
            _defaultRenderStates[to_uint(renderStage)][variant] = renderStateBlockHash;
        }
    }

    inline void setParallaxFactor(F32 factor) {
        _parallaxFactor = std::min(0.01f, factor);
    }

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

    void getMaterialMatrix(mat4<F32>& retMatrix) const;

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

    size_t getRenderStateBlock(RenderStage currentStage, I32 variant = 0);
    inline std::weak_ptr<Texture> getTexture(ShaderProgram::TextureUsage textureUsage) const {
        return _textures[to_uint(textureUsage)];
    }
    ShaderInfo& getShaderInfo(RenderStage renderStage = RenderStage::DISPLAY);

    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 getTextureData(TextureDataContainer& textureData);

    void clean();
    bool isTranslucent();
    inline bool isTranslucent() const { return !_translucencySource.empty(); }

    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(RenderStage renderStage, const bool computeOnAdd);

    bool canDraw(RenderStage renderStage);

    void updateReflectionIndex(I32 index);
    void updateRefractionIndex(I32 index);

   protected:
    bool frameStarted(const FrameEvent& evt) override;
    bool frameEnded(const FrameEvent& evt) override;

   private:
    void getTextureData(ShaderProgram::TextureUsage slot,
                        TextureDataContainer& container);

    void recomputeShaders();
    void computeShaderInternal();
    void setShaderProgramInternal(const stringImpl& shader,
                                  RenderStage renderStage,
                                  const bool computeOnAdd);

    inline bool isExternalTexture(ShaderProgram::TextureUsage slot) const {
        return _textureExtenalFlag[to_uint(slot)];
    }

   private:
    typedef std::pair<U32, ResourceDescriptor> ShaderQueueElement;
    std::deque<ShaderQueueElement> _shaderComputeQueue;
    ShadingMode _shadingMode;
    /// use for special shader tokens, such as "Tree"
    std::array<stringImpl, to_const_uint(RenderStage::COUNT)> _shaderModifier;
    vectorImpl<TranslucencySource> _translucencySource;
    /// parallax/relief factor (higher value > more pronounced effect)
    F32 _parallaxFactor;
    bool _dirty;
    bool _dumpToFile;
    bool _translucencyCheck;
    /// use discard if true / blend if otherwise
    bool _useAlphaTest;
    bool _doubleSided;
    /// Use shaders that have bone transforms implemented
    bool _hardwareSkinning;
    std::array<ShaderInfo, to_const_uint(RenderStage::COUNT)> _shaderInfo;
    std::array<std::array<size_t, 3>,  to_const_uint(RenderStage::COUNT)> _defaultRenderStates;

    bool _shaderThreadedLoad;
    bool _highPriority;
    /// use this map to add textures to the material
    std::array<Texture_ptr, to_const_uint(ShaderProgram::TextureUsage::COUNT)> _textures;
    std::array<bool, to_const_uint(ShaderProgram::TextureUsage::COUNT)> _textureExtenalFlag;
    vectorImpl<std::pair<Texture_ptr, U8>> _customTextures;

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

    BumpMethod _bumpMethod;

    ShaderData _shaderData;

    /// used to keep track of what GFXDevice::reflectionTarget we are using for this rendering pass
    I32 _reflectionIndex;
    I32 _refractionIndex;

    static bool _shadersComputedThisFrame;
    static U32  _totalShaderComputeCountThisFrame;
    static U32 _totalShaderComputeCount;
};

TYPEDEF_SMART_POINTERS_FOR_CLASS(Material);

};  // namespace Divide

#endif

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

Diff revisions: vs.
Revision Author Commited Message
727 Diff Diff IonutCava picture IonutCava Tue 14 Jun, 2016 16:01:38 +0000

[IonutCava]
- Remove node and cmd buffers from GFXDevice and add them as a new BufferData struct to RenderPass class.
— Each render pass holds its own buffers
- Improvements / fixes to the CSM code
- Added a global toggle to enable/disable custom memory allocators

726 Diff Diff IonutCava picture IonutCava Fri 10 Jun, 2016 16:13:52 +0000

[IonutCava]
- More static analysis based corrections
- Added initial stub code for a command pool system for GenericDrawCommands

722 Diff Diff IonutCava picture IonutCava Thu 09 Jun, 2016 16:15:33 +0000

[IonutCava]
- Restructure RenderTarget system:
— Separate attachments, use an attachment pool, use draw descriptors, require explicit information for RT calls, etc

720 Diff Diff IonutCava picture IonutCava Mon 06 Jun, 2016 15:51:06 +0000

[IonutCava]
- PVS-Studio guided static analysis fixes and optimizations
- Added a flag to SceneState to bypass the Save/Load system not needed for certain types of scenes (menus, cinematics, etc)

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

703 Diff Diff IonutCava picture IonutCava Wed 11 May, 2016 15:44:57 +0000

[IonutCava]
- Finish XML-based control bindings:
— Allow per bind input params (key id, mouse button index, joystick control data, etc)
— Allow mouse binding (with up to 7 buttons)
— Allow up to 4 joysticks (for now) with 120+ button, POV, Axis, Slider and Vector binding support for each
- Change all hashes in code from U32 to size_t for compatibility with STL/Boost

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

691 IonutCava picture IonutCava Tue 26 Apr, 2016 16:14:43 +0000

[IonutCava]
- Cleanup hash map template code (and allow creation of hash maps using the default allocator)
- Speedup text label multi-line parsing (now done on setText instead of drawText)
- Fix some reflection-related material crashes