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
#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"

ParticleEmitterDescriptor::ParticleEmitterDescriptor() {
   _particleCount = 1000;
   _spread = 1.5f;
   _emissionInterval = 400;
   _emissionIntervalVariance = 75;
   _velocity           = 10.0f;
   _velocityVariance   = 1.0f;
   _lifetime           = getSecToMs(5.0f);
   _lifetimeVariance   = 25.0f;
   _textureFileName    = "particle.DDS";
}

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

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

bool ParticleEmitter::initData(){
    // assert if double init!
    assert(_particleGPUBuffer != nullptr);

    _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), particleQuad, false, false);
    _particleGPUBuffer->getDrawAttribDescriptor(Divide::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 = New Impostor(_name);
    _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);
   
    SAFE_DELETE(_particleGPUBuffer);
    
    _particles.clear();
    _particlePositionData.clear();
    _particleColorData.clear();
    _created = false;
    return SceneNode::unload();
}

void ParticleEmitter::postLoad(SceneGraphNode* const sgn){
    ///Hold a pointer to the trigger's location in the SceneGraph
    _particleEmitterSGN = sgn;
    
    _impostor->getSceneNodeRenderState().setDrawState(false);
    _impostorSGN = _particleEmitterSGN->addNode(_impostor);
    _impostorSGN->setActive(false);
    _impostor->getMaterial()->setDiffuse(vec4<F32>(0.0f, 0.0f, 1.0f, 1.0f));
    _impostor->getMaterial()->setAmbient(vec4<F32>(0.0f, 0.0f, 1.0f, 1.0f));
    
    _updateParticleEmitterBB = true;

    setState(RES_LOADED);

    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]));
}

ShaderProgram* const ParticleEmitter::getDrawShader(RenderStage renderStage){
    return renderStage == FINAL_STAGE ? _particleShader : _particleDepthShader;
}

///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(Material::TEXTURE_UNIT0);
        GFX_DEVICE.getRenderTarget(GFXDevice::RENDER_TARGET_DEPTH)->Bind(1, TextureDescriptor::Depth);

        _drawCommand.setStateHash(_particleStateBlockHash);
        _drawCommand.setInstanceCount(_particlesCurrentCount);
        _drawCommand.setDrawIDs(GFX_DEVICE.getDrawIDs(sgn->getGUID()));
        _drawCommand.setShaderProgram(getDrawShader(currentRenderStage));
        GFX_DEVICE.submitRenderCommand(_particleGPUBuffer, _drawCommand);
    }
}

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

    _particleGPUBuffer->getDrawAttribDescriptor(13).set(1, 1, 4, false, 0, 0, FLOAT_32);
    _particleGPUBuffer->getDrawAttribDescriptor(Divide::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].distanceToCamera = -1.0f;
    }

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

    SamplerDescriptor textureSampler;
    ResourceDescriptor texture(descriptor._textureFileName);
    texture.setResourceLocation(ParamHandler::getInstance().getParam<std::string>("assetsLocation")+"/"+
                                ParamHandler::getInstance().getParam<std::string>("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, &_particlePositionData[0], writeOffset, true, true);
    _particleGPUBuffer->UpdateBuffer(2, _particlesCurrentCount, &_particleColorData[0],    writeOffset, true, true);
        
    _particleGPUBuffer->getDrawAttribDescriptor(13).set(1, 1, 4, false, 0, readOffset, FLOAT_32);
    _particleGPUBuffer->getDrawAttribDescriptor(Divide::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;

    if (_updateParticleEmitterBB) {
        sgn->updateBoundingBoxTransform(sgn->getTransform()->getGlobalMatrix());
        _updateParticleEmitterBB = false;
    }

    F32 delta = getUsToSec(deltaTime);

    I32 newParticles = _descriptor._emissionInterval + random(-_descriptor._emissionIntervalVariance, _descriptor._emissionIntervalVariance);
    newParticles = (I32)(newParticles * delta) / (_lodLevel + 1);

    const vec3<F32>& eyePos = sceneState.getRenderState().getCameraConst().getEye();
    const vec3<F32>& origin = sgn->getTransform()->getPosition();
    const Quaternion<F32>& orientation = sgn->getTransform()->getOrientation();
    F32 spread = _descriptor._spread;
    vec3<F32> mainDir = orientation * vec3<F32>(0, (_descriptor._velocity + random(-_descriptor._velocityVariance, _descriptor._velocityVariance)), 0);
    
    for(I32 i = 0; i < newParticles; ++i){
        ParticleDescriptor& currentParticle = _particles[findUnusedParticle()];
        currentParticle.life = _descriptor._lifetime + getMsToSec(random(-_descriptor._lifetimeVariance, _descriptor._lifetimeVariance));
        currentParticle.pos.set(origin);
        // 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  = mainDir + vec3<F32>((rand()%2000 - 1000.0f)/1000.0f,
                                                     (rand()%2000 - 1000.0f)/1000.0f,
                                                     (rand()%2000 - 1000.0f)/1000.0f) * spread;
         // Very bad way to generate a random color
        currentParticle.rgba.set(rand() % 256, rand() % 256, rand() % 256, (rand() % 256) / 3);
        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
                p.speed += half_gravity;
                p.pos += p.speed * delta;
                p.distanceToCamera = p.pos.distanceSquared(eyePos);
 
                _particlePositionData[4*particlesCount+0] = p.pos.x;
                _particlePositionData[4*particlesCount+1] = p.pos.y;
                _particlePositionData[4*particlesCount+2] = p.pos.z;
                _particlePositionData[4*particlesCount+3] = p.size;
 
                _particleColorData[4*particlesCount+0] = p.rgba.r;
                _particleColorData[4*particlesCount+1] = p.rgba.g;
                _particleColorData[4*particlesCount+2] = p.rgba.b;
                _particleColorData[4*particlesCount+3] = p.rgba.a;
 
            }else{
                // Particles that just died will be put at the end of the buffer in SortParticles();
                p.distanceToCamera = -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;
        }
    }
 
    return 0; // All particles are taken, override the first one
}

Commits for Divide-Framework/trunk/Source Code/Dynamics/Entities/Particles/ParticleEmitter.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]]

284 Diff Diff IonutCava picture IonutCava Tue 01 Jul, 2014 20:54:08 +0000

[Ionut][[BR]]
- Per SGN shader data implementation part 1 / 2 [[BR]]
— Gather node info and transforms into custom struct for visible nodes and store them in a GFXDevice local vector [[BR]]
- Removed “prepareDepthMaterial” and added depthPass flag to “prepareMaterial” [[BR]]

280 Diff Diff IonutCava picture IonutCava Sat 28 Jun, 2014 19:11:37 +0000

[Ionut] [[BR]]
- Improve ClipPlane management (bunch equations into the matrix shader buffer) [[BR]]
- Immediate mode emulation primitives set their own state based on specified hash instead of relying on state functions to be defined [[BR]]
- updateStates() function is now called right before the actual draw call to facilitate future batching work [[BR]]
- added tracked bool values (similar to those in ShaderInfo) to SGN class to fix selection bug. [[BR]]
— will probably create a “stateTracker” class to allow multiple classes to use tracked variables without all of the code duplication [[BR]]

279 Diff Diff IonutCava picture IonutCava Sat 28 Jun, 2014 16:20:46 +0000

[Ionut][[BR]]
- Unified draw command system into GenericDrawCommand [[BR]]
- Fixed double VB creation in Object3D [[BR]]
- Reworked triangle data computation (now Object3D’s responsibility) [[BR]]
- VertexArrays can now render using the primitive type specified in the draw command instead of the fixed type specified at creation [[BR]]
- Optimized terrain shader [[BR]]

276 Diff Diff IonutCava picture IonutCava Fri 13 Jun, 2014 18:23:32 +0000

[Ionut][[BR]]
- Terrain now inherits from Object3D (instead of directly from SceneNode) [[BR]]
- Restructured RenderInstance to support multiple draw commands [[BR]]
— Multiple draw commands per instance are separated to different LoD batches automatically on render [[BR]]

274 Diff Diff IonutCava picture IonutCava Fri 13 Jun, 2014 12:56:03 +0000

[Ionut] [[BR]]
- Simplified buffer based rendering (VertexBuffer & GenericVertexData are now exclusively command based) [[BR]]
- Update bone buffer to persistent mapped-SSBO system with double-buffering [[BR]]
- Simplified sky rendering and (finally) reduced the sun’s radius [[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]]

271 Diff Diff IonutCava picture IonutCava Fri 06 Jun, 2014 19:27:02 +0000

[Ionut] [[BR]]
- Preparing GVD class to support persistent mapping [[BR]]
- Updates to grass buffer. Better eat up the cost of waiting for culling result than going through the severe visual artifacts cause by skipping draws [[BR]]

267 k1ngp1n picture k1ngp1n Wed 28 May, 2014 11:08:12 +0000

[Ionut] [[BR]]
- Improved texture handling: [[BR]]
— No more texture unbind (except when clearing the frame state) [[BR]]
— Moved texture bind checking to the GL_API class [[BR]]
- Fixed a crash related to vegetation loading due to compiler optimizations [[BR]]
- removed all “releaseMaterial” functions as they are no longer needed [[BR]]