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
#include "config.h"

#include "Headers/ParticleEmitter.h"

#include "Core/Headers/TaskPool.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Headers/RenderStateBlock.h"
#include "Core/Resources/Headers/ResourceCache.h"
#include "Core/Headers/ParamHandler.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Core/Math/Headers/Transform.h"
#include "Core/Time/Headers/ApplicationTimer.h"
#include "Scenes/Headers/SceneState.h"
#include "Geometry/Material/Headers/Material.h"
#include "Rendering/Camera/Headers/Camera.h"
#include "Platform/Video/Buffers/RenderTarget/Headers/RenderTarget.h"
#include "Platform/Video/Buffers/VertexBuffer/GenericBuffer/Headers/GenericVertexData.h"

namespace Divide {
namespace {
    // 3 should always be enough for round-robin GPU updates to avoid stalls:
    // 1 in ram, 1 in driver and 1 in VRAM
    static const U32 g_particleBufferSizeFactor = 3;
    static const U32 g_particleGeometryBuffer = 0;
    static const U32 g_particlePositionBuffer = g_particleGeometryBuffer + 1;
    static const U32 g_particleColourBuffer = g_particlePositionBuffer* + 2;

    static const U64 g_updateInterval = Time::MillisecondsToMicroseconds(33);
};

ParticleEmitter::ParticleEmitter(GFXDevice& context, ResourceCache& parentCache, const stringImpl& name)
    : SceneNode(parentCache, name, SceneNodeType::TYPE_PARTICLE_EMITTER),
      _context(context),
      _drawImpostor(false),
      _particleStateBlockHash(0),
      _particleStateBlockHashDepth(0),
      _enabled(false),
      _particleTexture(nullptr),
      _particleShader(nullptr),
      _particleDepthShader(nullptr)
{
    _tempBB.set(-VECTOR3_UNIT, VECTOR3_UNIT);
    for (U8 i = 0; i < s_MaxPlayerBuffers; ++i) {
        for (U8 j = 0; j < to_const_uint(RenderStage::COUNT) - 1; ++j) {
            _particleGPUBuffers[i][j] = _context.newGVD(g_particleBufferSizeFactor);
        }
    }

    _buffersDirty.fill(false);
}

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

GenericVertexData& ParticleEmitter::getDataBuffer(RenderStage stage, U8 playerIndex) {
    return *_particleGPUBuffers[playerIndex % s_MaxPlayerBuffers][getIndexForStage(stage)];
}

bool ParticleEmitter::initData(const std::shared_ptr<ParticleData>& particleData) {
    // assert if double init!
    DIVIDE_ASSERT(particleData.get() != nullptr, "ParticleEmitter::updateData error: Invalid particle data!");
    _particles = particleData;
    const vectorImpl<vec3<F32>>& geometry = particleData->particleGeometryVertices();
    const vectorImpl<U32>& indices = particleData->particleGeometryIndices();

    for (U8 i = 0; i < s_MaxPlayerBuffers; ++i) {
        for (U8 j = 0; j < to_const_uint(RenderStage::COUNT) - 1; ++j) {
            GenericVertexData& buffer = getDataBuffer(static_cast<RenderStage>(j), i);

            buffer.create(3);
            buffer.setBuffer(g_particleGeometryBuffer,
                             to_uint(geometry.size()),
                             sizeof(vec3<F32>),
                             false,
                             (bufferPtr)geometry.data(),
                             false,
                             false);
            if (!indices.empty()) {
                buffer.setIndexBuffer(to_uint(indices.size()), false, false, indices);
            }

            AttributeDescriptor& desc = buffer.attribDescriptor(to_const_uint(AttribLocation::VERTEX_POSITION));
            desc.set(g_particleGeometryBuffer, 0, 3, false, 0, GFXDataFormat::FLOAT_32);
        }
    }

    updateData(particleData);

    // Generate a render state
    RenderStateBlock particleRenderState;
    particleRenderState.setCullMode(CullMode::NONE);
    particleRenderState.setBlend(true,
                                 BlendProperty::SRC_ALPHA,
                                 BlendProperty::INV_SRC_ALPHA);
    particleRenderState.setZFunc(ComparisonFunction::LEQUAL);
    _particleStateBlockHash = particleRenderState.getHash();

    particleRenderState.setZFunc(ComparisonFunction::LESS);
    _particleStateBlockHashDepth = particleRenderState.getHash();

    bool useTexture = _particleTexture != nullptr;
    ResourceDescriptor particleShaderDescriptor(useTexture ? "particles.WithTexture" : "particles.NoTexture");
    if (useTexture){
        particleShaderDescriptor.setPropertyList("HAS_TEXTURE");
    }
    _particleShader = CreateResource<ShaderProgram>(_parentCache, particleShaderDescriptor);

    ResourceDescriptor particleDepthShaderDescriptor("particles.Depth");
    _particleDepthShader = CreateResource<ShaderProgram>(_parentCache, particleDepthShaderDescriptor);

    return (_particleShader != nullptr);
}

bool ParticleEmitter::updateData(const std::shared_ptr<ParticleData>& particleData) {
    static const U32 positionAttribLocation = 13;
    static const U32 colourAttribLocation = to_const_uint(AttribLocation::VERTEX_COLOR);

    U32 particleCount = _particles->totalCount();

    for (U8 i = 0; i < s_MaxPlayerBuffers; ++i) {
        for (U8 j = 0; j < to_const_uint(RenderStage::COUNT) - 1; ++j) {
            GenericVertexData& buffer = getDataBuffer(static_cast<RenderStage>(j), i);

            buffer.setBuffer(g_particlePositionBuffer,
                             particleCount,
                             sizeof(vec4<F32>),
                             true,
                             NULL,
                             true,
                             true);
            buffer.setBuffer(g_particleColourBuffer,
                             particleCount,
                             sizeof(vec4<U8>),
                             true,
                             NULL,
                             true,
                             true);

            buffer.attribDescriptor(positionAttribLocation).set(g_particlePositionBuffer, 1, 4, false, 0, GFXDataFormat::FLOAT_32);

            buffer.attribDescriptor(colourAttribLocation).set(g_particleColourBuffer, 1, 4, true, 0, GFXDataFormat::UNSIGNED_BYTE);
        }
    }

    for (U32 i = 0; i < particleCount; ++i) {
        // Distance to camera (squared)
        _particles->_misc[i].w = -1.0f;
    }

    if (!_particles->_textureFileName.empty()) {
        SamplerDescriptor textureSampler;
        textureSampler.toggleSRGBColourSpace(true);

        ResourceDescriptor texture(_particles->_textureFileName);

        texture.setResourceLocation(
            ParamHandler::instance().getParam<stringImpl>(_ID("assetsLocation")) + "/" +
            ParamHandler::instance().getParam<stringImpl>(_ID("defaultTextureLocation")) + "/" +
            _particles->_textureFileName);

        texture.setPropertyDescriptor<SamplerDescriptor>(textureSampler);
        texture.setEnumValue(to_const_uint(TextureType::TEXTURE_2D));
        _particleTexture = CreateResource<Texture>(_parentCache, texture);
    }

    return true;
}

bool ParticleEmitter::unload() {
    if (getState() != ResourceState::RES_LOADED &&
        getState() != ResourceState::RES_LOADING) {
        return true;
    }
    
    _particles.reset();

    return SceneNode::unload();
}

void ParticleEmitter::postLoad(SceneGraphNode& sgn) {
if (_particleTexture && _particleTexture->flushTextureState()) {
        TextureData particleTextureData = _particleTexture->getData();
        particleTextureData.setHandleLow(to_const_uint(ShaderProgram::TextureUsage::UNIT0));
        sgn.get<RenderingComponent>()->registerTextureDependency(particleTextureData);
    }


    RenderingComponent* const renderable = sgn.get<RenderingComponent>();
    assert(renderable != nullptr);

    Attorney::RenderingCompSceneNode::setCustomShader(*renderable, _particleShader);
    Attorney::RenderingCompSceneNode::setCustomShader(*renderable, RenderStage::SHADOW, _particleDepthShader);
    
    setFlag(UpdateFlag::BOUNDS_CHANGED);

    sgn.get<BoundsComponent>()->lockBBTransforms(true);

    SceneNode::postLoad(sgn);
}

void ParticleEmitter::initialiseDrawCommands(SceneGraphNode& sgn,
                                             RenderStage renderStage,
                                             GenericDrawCommands& drawCommandsInOut) {
    U32 indexCount = to_uint(_particles->particleGeometryIndices().size());
    if (indexCount == 0) {
        indexCount = to_uint(_particles->particleGeometryVertices().size());
    }

    GenericDrawCommand cmd(_particles->particleGeometryType(), 0, indexCount);
    drawCommandsInOut.push_back(cmd);

    SceneNode::initialiseDrawCommands(sgn, renderStage, drawCommandsInOut);
}

U32 ParticleEmitter::getIndexForStage(RenderStage stage) const {
    if (stage == RenderStage::DISPLAY || stage == RenderStage::Z_PRE_PASS) {
        return to_uint(RenderStage::DISPLAY);
    }

    return to_uint(stage);
}

void ParticleEmitter::prepareForRender(RenderStage renderStage, const Camera& crtCamera) {
    if (renderStage == RenderStage::DISPLAY) {
        return;
    }

    const vec3<F32>& eyePos = crtCamera.getEye();
    U32 aliveCount = getAliveParticleCount();

    vectorImplAligned<vec4<F32>>& misc = _particles->_misc;
    vectorImplAligned<vec4<F32>>& pos = _particles->_position;

    auto updateDistToCamera = [&eyePos, &misc, &pos](const Task& parent, U32 start, U32 end) {
        for (U32 i = start; i < end; ++i) {
            misc[i].w = pos[i].xyz().distanceSquared(eyePos);
        }
    };

    parallel_for(updateDistToCamera, aliveCount, 1000);

    _bufferUpdate.emplace_back(CreateTask(
        [this, aliveCount, renderStage](const Task& parentTask) {
            // invalidateCache means that the existing particle data is no longer partially sorted
            _particles->sort(true);
            _buffersDirty[getIndexForStage(renderStage)] = true;
        }));
    
    _bufferUpdate.back().startTask(Task::TaskPriority::HIGH);
}

void ParticleEmitter::updateDrawCommands(SceneGraphNode& sgn,
                                         RenderStage renderStage,
                                         const SceneRenderState& sceneRenderState,
                                         GenericDrawCommands& drawCommandsInOut) {
    for(TaskHandle& task : _bufferUpdate) {
        task.wait();
    }
    _bufferUpdate.clear();

    if (_buffersDirty[getIndexForStage(renderStage)]) {
        GenericVertexData& buffer = getDataBuffer(renderStage, sceneRenderState.playerPass());
        buffer.updateBuffer(g_particlePositionBuffer, to_uint(_particles->_renderingPositions.size()), 0, _particles->_renderingPositions.data());
        buffer.updateBuffer(g_particleColourBuffer, to_uint(_particles->_renderingColours.size()), 0, _particles->_renderingColours.data());
        buffer.incQueue();
        _buffersDirty[getIndexForStage(renderStage)] = false;
    }

    GenericDrawCommand& cmd = drawCommandsInOut.front();
    cmd.cmd().primCount = to_uint(_particles->_renderingPositions.size());
    cmd.stateHash(_context.isDepthStage() ? _particleStateBlockHashDepth
                                          : _particleStateBlockHash);

    cmd.shaderProgram(renderStage != RenderStage::SHADOW
                                   ? _particleShader
                                   : _particleDepthShader);
    cmd.sourceBuffer(&getDataBuffer(renderStage, sceneRenderState.playerPass()));
    SceneNode::updateDrawCommands(sgn, renderStage, sceneRenderState, drawCommandsInOut);
}

/// The onDraw call will emit particles
bool ParticleEmitter::onRender(RenderStage currentStage) {
    if ( _enabled &&  getAliveParticleCount() > 0) {
        for (TaskHandle& task : _bufferUpdate) {
            task.wait();
        }
        _bufferUpdate.clear();
        prepareForRender(currentStage, *Camera::activeCamera());

        return true;
    }

    return false;
}


/// Pre-process particles
void ParticleEmitter::sceneUpdate(const U64 deltaTime,
                                  SceneGraphNode& sgn,
                                  SceneState& sceneState) {
    if (_enabled) {
        U32 aliveCount = getAliveParticleCount();
        renderState().setDrawState(aliveCount > 0);

        PhysicsComponent* transform = sgn.get<PhysicsComponent>();

        const vec3<F32>& pos = transform->getPosition();
        const Quaternion<F32>& rot = transform->getOrientation();

        F32 averageEmitRate = 0;
        for (std::shared_ptr<ParticleSource>& source : _sources) {
            source->updateTransform(pos, rot);
            source->emit(g_updateInterval, _particles);
            averageEmitRate += source->emitRate();
        }
        averageEmitRate /= _sources.size();

        aliveCount = getAliveParticleCount();

        for (U32 i = 0; i < aliveCount; ++i) {
            _particles->_position[i].w = _particles->_misc[i].z;
            _particles->_acceleration[i].set(0.0f);
        }

        ParticleData& data = *_particles;
        for (std::shared_ptr<ParticleUpdater>& up : _updaters) {
            up->update(g_updateInterval, data);
        }

        for (TaskHandle& task : _bbUpdate) {
            task.wait();
        }
        _bufferUpdate.clear();
        _bbUpdate.emplace_back(CreateTask([this, aliveCount, averageEmitRate](const Task& parentTask) {
            _tempBB.reset();
            for (U32 i = 0; i < aliveCount; i += to_uint(averageEmitRate) / 4) {
                _tempBB.add(_particles->_position[i]);
            }
            setFlag(UpdateFlag::BOUNDS_CHANGED);
        }));
        _bbUpdate.back().startTask(Task::TaskPriority::HIGH);
    }

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

U32 ParticleEmitter::getAliveParticleCount() const {
    if (!_particles.get()) {
        return 0;
    }
    return _particles->aliveCount();
}

void ParticleEmitter::updateBoundsInternal(SceneGraphNode& sgn) {
    for (TaskHandle& task : _bbUpdate) {
        task.wait();
    }
    _bufferUpdate.clear();

    U32 aliveCount = getAliveParticleCount();
    if (aliveCount > 2) {
        _boundingBox.set(_tempBB);
    } else {
        _boundingBox.set(-VECTOR3_UNIT, VECTOR3_UNIT);
    }

    SceneNode::updateBoundsInternal(sgn);
}

};

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

Diff revisions: vs.
Revision Author Commited Message
827 Diff Diff IonutCava picture IonutCava Sun 22 Jan, 2017 21:59:36 +0000

[IonutCava]
- ShaderBuffers now decide heuristically if they get persistently mapped or not (depends on size. Current limit is 512Kb for subData calls.
- Separate visible node command generation into 2 steps: onRender and getDrawPackage. onRender allows the creation of parallel tasks that should finish by the time the second call, getDrawPackage reaches the same node
- Update ParticleEmitter to take into account multiple players and increase parallelism at the cost of memory consumption and complexity.
- Add a default bounding box for Players (add extents to SceneTransform nodes)
- All buffers (ShaderBuffer, d3dConstantBuffer, glUniformBuffer, glBufferImpl, glGenericBuffer, etc) use BufferParams for creation.
— Constructor and create calls have been merged together

817 Diff Diff IonutCava picture IonutCava Sun 15 Jan, 2017 21:29:59 +0000

[IonutCava]
- Add a new Unit component to SGNs that holds NPC/Player/etc. objects
- Add support for multiple keyboard+mouse combos and joysticks and add mapping between these and players

811 Diff Diff IonutCava picture IonutCava Wed 11 Jan, 2017 17:26:49 +0000

[IonutCava]
- Fix some threadpool cleanup bugs
- Fix terrain rendering (except underwater caustics)
- Fix terrain loading
- Fix terrain unloading

807 Diff Diff IonutCava picture IonutCava Mon 09 Jan, 2017 17:06:26 +0000

[IonutCava]
- Split PlatformDefines.h into 2. Move data type defines to PlatformDataTypes.h
- Continue to improve velocity map calculation
- Remove “destroy()” calls from most classes. Attempt to move as many classes to the RAII system.

806 Diff Diff IonutCava picture IonutCava Sun 08 Jan, 2017 22:00:48 +0000

[IonutCava]
- Finish implementing per-fragment velocity computation using a compute shader
— Further tuning still needed
- Add VS2017 build targets

804 Diff Diff IonutCava picture IonutCava Thu 01 Dec, 2016 17:20:59 +0000

[IonutCava]
- Singleton elimination update Part I: get it to compile
— The following classes are no longer Singletons: GFXDevice, GL_API, DX_API, SFXWrapper, FmodWrapper, SDLWrapper, ALWrapper, PXDevice, InputInterface, RenderPassManager, SceneManager and ResourceManager;
— Refactor system to a Context / Component based implementation (Pass relevant context to objects: e.g. GFXDevice object to Textures, GUI to GUIElements, etc)
— Make devices and managers components of the kernel
— Allow multiple Resource caches to co-exist. This may prove useful for later when a more fragmented memory model is need (per frame / per scene / global caches / etc)

  • next steps: part II – cleanup/refactor new code, part III – optimise code, part IV – remove remaining Singletons (e.g. Application, ParamHandler, FrameListenerManager, Recast, PostFX and DebugInterface)
801 Diff Diff IonutCava picture IonutCava Sun 27 Nov, 2016 21:28:01 +0000

[IonutCava]
- More performance analysis guided optimizations.
- Some refactoring to allow later removal of Singletons status for: GFXDevice, SFXDevice, PXDevice, GUI and Input.
— Pass a PlatformContext around objects to access these classes.

788 Diff Diff IonutCava picture IonutCava Fri 21 Oct, 2016 16:11:37 +0000

[IonutCava]
- Added support for the Arena Allocator by Mamasha Knows (http://www.codeproject.com/Articles/44850/Arena-Allocator-DTOR-and-Embedded-Preallocated-Buf)
— Used for GFX Related objects: Textures, shaders, etc

784 Diff Diff IonutCava picture IonutCava Mon 17 Oct, 2016 16:20:49 +0000

[IonutCava]
- Removed the CameraManager and move most of its functionality into static members of the Camera class
- Removed Camera push/pop system in favour of a stateless ptr based system to better fit the RenderPass structure

776 IonutCava picture IonutCava Thu 06 Oct, 2016 15:57:56 +0000

[IonutCava]
- Improve the CommandBuffer system to include the notion of a RenderPass /RenderSubPass with output render target info stored in them (not used yet)