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
#include "Headers/ParticleEmitter.h"

#include "Core/Headers/Application.h"
#include "Hardware/Video/Headers/GFXDevice.h"
#include "Core/Resources/Headers/ResourceCache.h"
#include "Core/Headers/ParamHandler.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Core/Math/Headers/Transform.h"
#include "Scenes/Headers/SceneState.h"
#include "Geometry/Material/Headers/Material.h"

namespace Divide {
    ParticleEmitterDescriptor::ParticleEmitterDescriptor() : PropertyDescriptor(PropertyDescriptor::DESCRIPTOR_PARTICLE)
    {
        setDefaultValues();
    }

    ParticleEmitter::ParticleEmitter() : SceneNode(TYPE_PARTICLE_EMITTER),
        _drawImpostor(false),
        _updateParticleEmitterBB(true),
        _lastUsedParticle(0),
        _particlesCurrentCount(0),
        _particleStateBlockHash(0),
        _enabled(false),
        _uploaded(false),
        _created(false),
        _particleTexture(nullptr),
        _particleShader(nullptr),
        _particleGPUBuffer(nullptr),
        _particleDepthShader(nullptr)
    {
        _drawCommand = GenericDrawCommand(TRIANGLE_STRIP, 0, 4, 1);
        _readOffset = 0;
        _writeOffset = 2;
    }

    ParticleEmitter::~ParticleEmitter()
    {
        unload();
    }

    bool ParticleEmitter::initData(){
        // assert if double init!
        DIVIDE_ASSERT(_particleGPUBuffer == nullptr, "ParticleEmitter error: Double initData detected!");

        _particleGPUBuffer = GFX_DEVICE.newGVD(/*true*/false);
        _particleGPUBuffer->Create(3);

        // Not using Quad3D to improve performance
        static F32 particleQuad[] = {
            -0.5f, -0.5f, 0.0f,
            0.5f, -0.5f, 0.0f,
            -0.5f, 0.5f, 0.0f,
            0.5f, 0.5f, 0.0f,
        };

        _particleGPUBuffer->SetBuffer(0, 12, sizeof(F32), 1, particleQuad, false, false);
        _particleGPUBuffer->getDrawAttribDescriptor(VERTEX_POSITION_LOCATION).set(0, 0, 3, false, 0, 0, FLOAT_32);

        //Generate a render state
        RenderStateBlockDescriptor particleStateDesc;
        particleStateDesc.setCullMode(CULL_MODE_NONE);
        particleStateDesc.setBlend(true, BLEND_PROPERTY_SRC_ALPHA, BLEND_PROPERTY_INV_SRC_ALPHA);
        _particleStateBlockHash = GFX_DEVICE.getOrCreateStateBlock(particleStateDesc);

        ResourceDescriptor particleShaderDescriptor("particles");
        _particleShader = CreateResource<ShaderProgram>(particleShaderDescriptor);
        _particleShader->UniformTexture("depthBuffer", 1);
        REGISTER_TRACKED_DEPENDENCY(_particleShader);
        ResourceDescriptor particleDepthShaderDescriptor("particles.Depth");
        _particleDepthShader = CreateResource<ShaderProgram>(particleDepthShaderDescriptor);
        REGISTER_TRACKED_DEPENDENCY(_particleDepthShader);
        _impostor = CreateResource<Impostor>(ResourceDescriptor(_name + "_impostor"));
        _impostor->renderState().setDrawState(false);
        _impostor->getMaterialTpl()->setDiffuse(vec4<F32>(0.0f, 0.0f, 1.0f, 1.0f));
        _impostor->getMaterialTpl()->setAmbient(vec4<F32>(0.0f, 0.0f, 1.0f, 1.0f));
        _renderState.addToDrawExclusionMask(SHADOW_STAGE);
        return (_particleShader != nullptr);
    }

    bool ParticleEmitter::unload(){
        if (getState() != RES_LOADED && getState() != RES_LOADING) {
            return true;
        }
        UNREGISTER_TRACKED_DEPENDENCY(_particleTexture);
        UNREGISTER_TRACKED_DEPENDENCY(_particleShader);
        UNREGISTER_TRACKED_DEPENDENCY(_particleDepthShader);
        RemoveResource(_particleTexture);
        RemoveResource(_particleShader);
        RemoveResource(_particleDepthShader);

        MemoryManager::DELETE(_particleGPUBuffer);

        _particles.clear();
        _particlePositionData.clear();
        _particleColorData.clear();
        _created = false;
        return SceneNode::unload();
    }

    void ParticleEmitter::postLoad(SceneGraphNode* const sgn){
        sgn->addNode(_impostor)->setActive(false);
        SceneNode::postLoad(sgn);
    }

    bool ParticleEmitter::computeBoundingBox(SceneGraphNode* const sgn){
        if (!_enabled || !_created) {
            return false;
        }

        _updateParticleEmitterBB = true;
        sgn->getBoundingBox().set(vec3<F32>(-5), vec3<F32>(5));
        return SceneNode::computeBoundingBox(sgn);
    }

    void ParticleEmitter::onCameraChange(SceneGraphNode* const sgn){
        const mat4<F32>& viewMatrixCache = GFX_DEVICE.getMatrix(VIEW_MATRIX);
        _particleShader->Uniform("CameraRight_worldspace", vec3<F32>(viewMatrixCache.m[0][0], 
                                                                     viewMatrixCache.m[1][0],
                                                                     viewMatrixCache.m[2][0]));
        _particleShader->Uniform("CameraUp_worldspace", vec3<F32>(viewMatrixCache.m[0][1],
                                                                  viewMatrixCache.m[1][1],
                                                                  viewMatrixCache.m[2][1]));
        _particleDepthShader->Uniform("CameraRight_worldspace", vec3<F32>(viewMatrixCache.m[0][0],
                                                                          viewMatrixCache.m[1][0], 
                                                                          viewMatrixCache.m[2][0]));
        _particleDepthShader->Uniform("CameraUp_worldspace", vec3<F32>(viewMatrixCache.m[0][1],
                                                                       viewMatrixCache.m[1][1],
                                                                       viewMatrixCache.m[2][1]));
    }

    void ParticleEmitter::getDrawCommands(SceneGraphNode* const sgn, 
                                          const RenderStage& currentRenderStage, 
                                          SceneRenderState& sceneRenderState,
                                          vectorImpl<GenericDrawCommand>& drawCommandsOut) 
    {

        if (!(_particlesCurrentCount > 0 && _enabled && _created)) {
            return;
        }

        _drawCommand.renderWireframe(sgn->getComponent<RenderingComponent>()->renderWireframe());
        _drawCommand.stateHash(_particleStateBlockHash);
        _drawCommand.instanceCount(_particlesCurrentCount);
        _drawCommand.shaderProgram(currentRenderStage == FINAL_STAGE ? _particleShader : _particleDepthShader);
        _drawCommand.sourceBuffer(_particleGPUBuffer);
        drawCommandsOut.push_back(_drawCommand);
    }

    ///When the SceneGraph calls the particle emitter's render function, we draw the impostor if needed
    void ParticleEmitter::render(SceneGraphNode* const sgn,
                                 const SceneRenderState& sceneRenderState, 
                                 const RenderStage& currentRenderStage) {
        if (_particlesCurrentCount > 0 && _enabled && _created){
            _particleTexture->Bind(ShaderProgram::TEXTURE_UNIT0);
            GFX_DEVICE.getRenderTarget(GFXDevice::RENDER_TARGET_DEPTH)->Bind(ShaderProgram::TEXTURE_UNIT1,
                                                                             TextureDescriptor::Depth);
            GFX_DEVICE.submitRenderCommand(sgn->getComponent<RenderingComponent>()->getDrawCommands());
        }
    }

    ///The descriptor defines the particle properties
    void ParticleEmitter::setDescriptor(const ParticleEmitterDescriptor& descriptor){
        _descriptor = descriptor;
        _particleGPUBuffer->SetBuffer(1, descriptor._particleCount * 3, 4 * sizeof(F32), 1, NULL, true, true, /*true*/false);
        _particleGPUBuffer->SetBuffer(2, descriptor._particleCount * 3, 4 * sizeof(U8), 1, NULL, true, true, /*true*/false);

        _particleGPUBuffer->getDrawAttribDescriptor(13).set(1, 1, 4, false, 0, 0, FLOAT_32);
        _particleGPUBuffer->getDrawAttribDescriptor(VERTEX_COLOR_LOCATION).set(2, 1, 4, true, 0, 0, UNSIGNED_BYTE);

        _particles.resize(descriptor._particleCount);
        _particlePositionData.resize(descriptor._particleCount * 4);
        _particleColorData.resize(descriptor._particleCount * 4);

        for (U32 i = 0; i < descriptor._particleCount; ++i) {
            _particles[i].life = -1.0f;
            _particles[i].distanceToCameraSq = -1.0f;
        }

        if (_particleTexture) {
            UNREGISTER_TRACKED_DEPENDENCY(_particleTexture);
            RemoveResource(_particleTexture);
        }

        SamplerDescriptor textureSampler;
        textureSampler.toggleSRGBColorSpace(true);
        ResourceDescriptor texture(descriptor._textureFileName);
        texture.setResourceLocation(ParamHandler::getInstance().getParam<stringImpl>("assetsLocation") + "/" +
                                    ParamHandler::getInstance().getParam<stringImpl>("defaultTextureLocation") + "/" +
                                    descriptor._textureFileName);
        texture.setFlag(true);
        texture.setPropertyDescriptor<SamplerDescriptor>(textureSampler);
        _particleTexture = CreateResource<Texture>(texture);
        REGISTER_TRACKED_DEPENDENCY(_particleTexture);
        _created = true;
    }

    void ParticleEmitter::uploadToGPU(){
        static const size_t attribSize_float = 4 * sizeof(F32);
        static const size_t attribSize_char = 4 * sizeof(U8);
        if (_uploaded || !_created)
            return;

        U32 writeOffset = _writeOffset * (U32)_particles.size();
        U32 readOffset = _readOffset  * (U32)_particles.size();

        _particleGPUBuffer->UpdateBuffer(1, _particlesCurrentCount, writeOffset, &_particlePositionData[0]);
        _particleGPUBuffer->UpdateBuffer(2, _particlesCurrentCount, writeOffset, &_particleColorData[0]);

        _particleGPUBuffer->getDrawAttribDescriptor(13).set(1, 1, 4, false, 0, readOffset, FLOAT_32);
        _particleGPUBuffer->getDrawAttribDescriptor(VERTEX_COLOR_LOCATION).set(2, 1, 4, true, 0, readOffset, UNSIGNED_BYTE);

        _writeOffset = (_writeOffset + 1) % 3;
        _readOffset = (_readOffset + 1) % 3;

        _uploaded = true;
    }

    ///The onDraw call will emit particles
    bool ParticleEmitter::onDraw(SceneGraphNode* const sgn, const RenderStage& currentStage) {

        if (!_enabled || _particlesCurrentCount == 0 || !_created) {
            return false;
        }
        std::sort(_particles.begin(), _particles.end());
        uploadToGPU();

        return true;
    }

    /// Pre-process particles
    void ParticleEmitter::sceneUpdate(const U64 deltaTime, SceneGraphNode* const sgn, SceneState& sceneState) {

        if (!_enabled || !_created) {
            return;
        }

        PhysicsComponent* const transform = sgn->getComponent<PhysicsComponent>();

        if (_updateParticleEmitterBB) {
            sgn->updateBoundingBoxTransform(transform->getWorldMatrix());
            _updateParticleEmitterBB = false;
        }


        F32 delta = getUsToSec(deltaTime);
        F32 emissionVariance = random(-_descriptor._emissionIntervalVariance, _descriptor._emissionIntervalVariance);
        I32 newParticles = _descriptor._emissionInterval + emissionVariance;
        newParticles = (I32)(newParticles * delta) / (sgn->getComponent<RenderingComponent>()->lodLevel() + 1);

        
        const vec3<F32>& eyePos = sceneState.getRenderState().getCameraConst().getEye();
        const vec3<F32>& origin = transform->getPosition();
        const Quaternion<F32>& orientation = transform->getOrientation();

        F32 spread = _descriptor._spread;
        F32 velVariance = random(-_descriptor._velocityVariance, _descriptor._velocityVariance);
        vec3<F32> mainDir = orientation * (WORLD_Y_AXIS * (_descriptor._velocity + velVariance));

        for (I32 i = 0; i < newParticles; ++i) {
            ParticleDescriptor& currentParticle = _particles[findUnusedParticle()];
            F32 lifetimeVariance = random(-_descriptor._lifetimeVariance, _descriptor._lifetimeVariance);
            currentParticle.life = _descriptor._lifetime + getMsToSec(lifetimeVariance);
            memcpy(currentParticle.pos, origin._v, 3 * sizeof(F32));
            // Very bad way to generate a random direction;
            // See for instance http://stackoverflow.com/questions/5408276/python-uniform-spherical-distribution instead,
            // combined with some user-controlled parameters (main direction, spread, etc)
            currentParticle.speed[0] = mainDir.x + (rand() % 2000 - 1000.0f) / 1000.0f * spread;
            currentParticle.speed[1] = mainDir.y + (rand() % 2000 - 1000.0f) / 1000.0f * spread;
            currentParticle.speed[2] = mainDir.z + (rand() % 2000 - 1000.0f) / 1000.0f * spread;
            // Very bad way to generate a random color
            memcpy(currentParticle.rgba, DefaultColors::RANDOM()._v, 3 * sizeof(U8));
            currentParticle.rgba[3] = (rand() % 256) / 2;

            currentParticle.size = (rand() % 1000) / 2000.0f + 0.1f;
        }

        // Simulate all particles
        I32 particlesCount = 0;
        vec3<F32> half_gravity = DEFAULT_GRAVITY * delta * 0.5f;
        for (ParticleDescriptor& p : _particles) {
            if (p.life > 0.0f) {
                // Decrease life
                p.life -= delta;
                if (p.life > 0.0f) {
                    // Simulate simple physics : gravity only, no collisions
                    for (U8 i = 0; i < 3; ++i) {
                        p.speed[i] += half_gravity[i];
                        p.pos[i] += p.speed[i] * delta;
                    }
                    p.distanceToCameraSq = vec3<F32>(p.pos).distanceSquared(eyePos);

                    
                    _particlePositionData[4 * particlesCount + 0] = p.pos[0];
                    _particlePositionData[4 * particlesCount + 1] = p.pos[1];
                    _particlePositionData[4 * particlesCount + 2] = p.pos[2];
                    _particlePositionData[4 * particlesCount + 3] = p.size;

                    _particleColorData[4 * particlesCount + 0] = p.rgba[0];
                    _particleColorData[4 * particlesCount + 1] = p.rgba[1];
                    _particleColorData[4 * particlesCount + 2] = p.rgba[2];
                    _particleColorData[4 * particlesCount + 3] = p.rgba[3];
                } else {
                    // Particles that just died will be put at the end of the buffer in SortParticles();
                    p.distanceToCameraSq = -1.0f;
                }

                particlesCount++;
            }
        }

        _particlesCurrentCount = particlesCount;
        _uploaded = false;

        SceneNode::sceneUpdate(deltaTime, sgn, sceneState);
    }

    // Finds a Particle in ParticlesContainer which isn't used yet. (i.e. life < 0);
    I32 ParticleEmitter::findUnusedParticle() {
        for (U32 i = _lastUsedParticle; i < _particles.size(); ++i) {
            if (_particles[i].life < 0.0f) {
                _lastUsedParticle = i;
                return i;
            }
        }

        for (I32 i = 0; i < _lastUsedParticle; ++i) {
            if (_particles[i].life < 0.0f) {
                _lastUsedParticle = i;
                return i;
            }
        }

        // All particles are taken, override the first one
        return 0; 
    }
};

Commits for Divide-Framework/trunk/Source Code/Dynamics/Entities/Particles/ParticleEmitter.cpp

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)

330 Diff Diff IonutCava picture IonutCava Fri 10 Oct, 2014 17:19:11 +0000

[Ionut]
- New rendering algorithm :
— Perform second pass for visible nodes gathering all render commands and uploading them to an indirect draw buffer
— Render geometry with indirect draw commands
— Removed per-node range binding of the node buffer. Instead, bind the entire buffer once and index data in shaders
— Use “baseInstance” parameter from IndirectDrawCommand as a node buffer index
— Prefer DSA extensions for updating buffer data where applicable
- Moved all rendering specific code from SceneGraphNode to a new RenderingComponent
- Optimized “toString” utility function

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

327 Diff Diff IonutCava picture IonutCava Thu 02 Oct, 2014 12:32:15 +0000

[Ionut]
- Removed specular color from lights (specular color should be identical to light’s diffuse color anyway)
- Doublesided materials use their own shader defines now
- Fixed a bug in the particle shader related to screen dimensions never being passed
- Disabled material loading from XML for Primitive type geometry

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)

324 Diff Diff IonutCava picture IonutCava Sun 14 Sep, 2014 14:01:39 +0000

[Ionut]
- New memory management system (no custom allocators in this commit)
— Memory tracer to detect memory leaks on shutdown (from: https://www.relisoft.com/book/tech/9new.html)
— SAFE_DELETE_XYZ are now inline template functions not macros
— ASSERTION system now supports logging and message boxes and continue on error configurable for each build type
— Fixed a lot of memory leaks detected by the new system (some still remain)

- Added SRGB support (part 1)
— Albedo textures are loaded as SRGB (make sure resources are SRGB)
— Shaders output gamma corrected colors
— Moved terrain textures back to 2 array system (albedo and normal maps, albedo maps using a SRGB sampler)

- Sky is now loaded via the ResourceCache system
- Added include safeguards in shader atoms

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)

319 Diff Diff IonutCava picture IonutCava Sat 30 Aug, 2014 21:37:57 +0000

[Ionut]
- Performance tweaks based on profiling data

318 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)