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

#include "config.h"

#include "Headers/GFXDevice.h"

#include "GUI/Headers/GUI.h"
#include "GUI/Headers/GUIText.h"
#include "GUI/Headers/GUIFlash.h"

#include "Rendering/Headers/Renderer.h"

#include "Managers/Headers/SceneManager.h"
#include "Managers/Headers/RenderPassManager.h"

#include "Core/Time/Headers/ProfileTimer.h"
#include "Platform/Video/Headers/IMPrimitive.h"
#include "Platform/Video/Textures/Headers/Texture.h"
#include "Platform/Video/Shaders/Headers/ShaderProgram.h"
#include "Platform/Video/Buffers/ShaderBuffer/Headers/ShaderBuffer.h"

namespace Divide {

void GFXDevice::uploadGPUBlock() {
    if (_gpuBlock._needsUpload) {
        // We flush the entire buffer on update to inform the GPU that we don't
        // need the previous data. Might avoid some driver sync
        _gfxDataBuffer->setData(&_gpuBlock._data);
        _gfxDataBuffer->bind(ShaderBufferLocation::GPU_BLOCK);
        _api->updateClipPlanes();
        _gpuBlock._needsUpload = false;
    }
}

void GFXDevice::renderQueueToSubPasses(RenderPassCmd& commandsInOut) {
    ReadLock lock(_renderQueueLock);
    for (RenderPackageQueue& renderQueue : _renderQueues) {
        if (!renderQueue.empty()) {
            U32 queueSize = renderQueue.size();
            for (U32 idx = 0; idx < queueSize; ++idx) {
                RenderSubPassCmd subPassCmd;
                RenderPackage& package = renderQueue.getPackage(idx);
                GenericDrawCommands& drawCommands = package._drawCommands;
                vectorAlg::vecSize commandCount = drawCommands.size();
                if (commandCount > 0) {
                    vectorAlg::vecSize previousCommandIndex = 0;
                    vectorAlg::vecSize currentCommandIndex = 1;
                    for (; currentCommandIndex < commandCount; ++currentCommandIndex) {
                        GenericDrawCommand& previousCommand = drawCommands[previousCommandIndex];
                        GenericDrawCommand& currentCommand = drawCommands[currentCommandIndex];
                        if (!batchCommands(previousCommand, currentCommand))
                        {
                            previousCommandIndex = currentCommandIndex;
                        }
                    }

                    std::for_each(std::begin(drawCommands),
                                  std::end(drawCommands),
                                  [&](GenericDrawCommand& cmd) -> void {
                                      cmd.enableOption(GenericDrawCommand::RenderOptions::RENDER_INDIRECT);
                                  });

                    for (ShaderBufferList::value_type& it : package._shaderBuffers) {
                        subPassCmd._shaderBuffers.emplace_back(it._buffer, it._slot, it._range);
                    }

                    subPassCmd._textures.set(package._textureData);
                    subPassCmd._commands.insert(std::cbegin(subPassCmd._commands),
                                                std::cbegin(drawCommands),
                                                std::cend(drawCommands));
                    commandsInOut._subPassCmds.push_back(subPassCmd);
                }
            }
            renderQueue.clear();
        }
        renderQueue.unlock();
    }
}

void GFXDevice::flushCommandBuffer(const CommandBuffer& commandBuffer) {
    uploadGPUBlock();
    _api->flushCommandBuffer(commandBuffer);
}

void GFXDevice::addToRenderQueue(U32 queueIndex, const RenderPackage& package) {
    if (!package.isRenderable()) {
        return;
    }

    ReadLock lock(_renderQueueLock);
    assert(_renderQueues.size() > queueIndex);
    RenderPackageQueue& queue = _renderQueues[queueIndex];

    if (!queue.empty()) {
        RenderPackage& previous = queue.back();

        if (previous.isCompatible(package)) {
            previous._drawCommands.insert(std::cend(previous._drawCommands),
                                          std::cbegin(package._drawCommands),
                                          std::cend(package._drawCommands));
            return;
        }
    } else {
        queue.reserve(Config::MAX_VISIBLE_NODES);
    }

    queue.push_back(package);
}

I32 GFXDevice::reserveRenderQueue() {
    UpgradableReadLock ur_lock(_renderQueueLock);
    //ToDo: Nothing about this bloody thing is threadsafe
    I32 queueCount = to_I32(_renderQueues.size());
    for (I32 i = 0; i < queueCount; ++i) {
        RenderPackageQueue& queue = _renderQueues[i];
        if (queue.empty() && !queue.locked()) {
            queue.lock();
            return i;
        }
    }

    UpgradeToWriteLock uw_lock(ur_lock);
    _renderQueues.emplace_back();
    _renderQueues[queueCount].lock();
    return queueCount;
}

/// Prepare the list of visible nodes for rendering
GFXDevice::NodeData& GFXDevice::processVisibleNode(const SceneGraphNode& node, U32 dataIndex) {
    NodeData& dataOut = _matricesData[dataIndex];

    RenderingComponent* const renderable = node.get<RenderingComponent>();
    AnimationComponent* const animComp = node.get<AnimationComponent>();
    PhysicsComponent* const transform = node.get<PhysicsComponent>();

    // Extract transform data (if available)
    // (Nodes without transforms are considered as using identity matrices)
    if (transform) {
        // ... get the node's world matrix properly interpolated
        dataOut._worldMatrix.set(transform->getWorldMatrix(getFrameInterpolationFactor()));

        dataOut._normalMatrixWV.set(dataOut._worldMatrix);
        if (!transform->isUniformScaled()) {
            // Non-uniform scaling requires an inverseTranspose to negate
            // scaling contribution but preserve rotation
            dataOut._normalMatrixWV.setRow(3, 0.0f, 0.0f, 0.0f, 1.0f);
            dataOut._normalMatrixWV.inverseTranspose();
            dataOut._normalMatrixWV.mat[15] = 0.0f;
        }
        dataOut._normalMatrixWV.setRow(3, 0.0f, 0.0f, 0.0f, 0.0f);

        // Calculate the normal matrix (world * view)
        dataOut._normalMatrixWV *= getMatrix(MATRIX::VIEW);
    }

    // Since the normal matrix is 3x3, we can use the extra row and column to store additional data
    dataOut._normalMatrixWV.element(0, 3) = to_F32(animComp ? animComp->boneCount() : 0);
    dataOut._normalMatrixWV.setRow(3, node.get<BoundsComponent>()->getBoundingSphere().asVec4());
    // Get the material property matrix (alpha test, texture count, texture operation, etc.)
    renderable->getRenderingProperties(dataOut._properties, dataOut._normalMatrixWV.element(1, 3), dataOut._normalMatrixWV.element(2, 3));
    // Get the colour matrix (diffuse, specular, etc.)
    renderable->getMaterialColourMatrix(dataOut._colourMatrix);

    return dataOut;
}

void GFXDevice::buildDrawCommands(RenderPassCuller::VisibleNodeList& visibleNodes,
                                  SceneRenderState& sceneRenderState,
                                  RenderPass::BufferData& bufferData,
                                  bool refreshNodeData)
{
    Time::ScopedTimer timer(_commandBuildTimer);
    // If there aren't any nodes visible in the current pass, don't update
    // anything (but clear the render queue

    U32 textureHandle = 0;
    U32 lastUnit0Handle = 0;
    U32 lastUnit1Handle = 0;
    U32 lastUsedSlot = 0;
    RenderStagePass currentStage = getRenderStage();
    if (refreshNodeData) {
        bufferData._lastCommandCount = 0;
        bufferData._lasNodeCount = 0;
    }

    if (currentStage.stage() == RenderStage::SHADOW) {
        Light* shadowLight = LightPool::currentShadowCastingLight();
        assert(shadowLight != nullptr);
        if (!COMPARE(_gpuBlock._data._renderProperties.x, shadowLight->getShadowProperties()._arrayOffset.x)) {
            _gpuBlock._data._renderProperties.x = to_F32(shadowLight->getShadowProperties()._arrayOffset.x);
            _gpuBlock._needsUpload = true;
        }
        U8 shadowPasses = shadowLight->getLightType() == LightType::DIRECTIONAL
                                                       ? shadowLight->getShadowMapInfo()->numLayers()
                                                       : 1;
        if (!COMPARE(_gpuBlock._data._renderProperties.y, to_F32(shadowPasses))) {
            _gpuBlock._data._renderProperties.y = to_F32(shadowPasses);
            _gpuBlock._needsUpload = true;
        }
    }

    std::for_each(std::begin(visibleNodes), std::end(visibleNodes),
                 [&](RenderPassCuller::VisibleNode& node) -> void
    {

        const SceneGraphNode* nodeRef = node.second;
        RenderingComponent* renderable = nodeRef->get<RenderingComponent>();
        Attorney::RenderingCompGFXDevice::prepareDrawPackage(*renderable, sceneRenderState, currentStage);
    });

    U32 nodeCount = 0;
    U32 cmdCount = 0;
    std::for_each(std::begin(visibleNodes), std::end(visibleNodes),
        [&](RenderPassCuller::VisibleNode& node) -> void
    {
        const SceneGraphNode* nodeRef = node.second;

        RenderingComponent* renderable = nodeRef->get<RenderingComponent>();
        RenderPackage& pkg = Attorney::RenderingCompGFXDevice::getDrawPackage(*renderable,
                                                                               sceneRenderState,
                                                                               currentStage,
                                                                               refreshNodeData ? cmdCount
                                                                                               : renderable->commandOffset(),
                                                                               refreshNodeData ? nodeCount
                                                                                               : renderable->commandIndex());

        if (pkg.isRenderable()) {
            if (refreshNodeData) {
                NodeData& dataOut = processVisibleNode(*nodeRef, nodeCount);
                if (isDepthStage()) {
                    for (TextureData& data : pkg._textureData.textures()) {
                        if (data.getHandleLow() == to_base(ShaderProgram::TextureUsage::UNIT0)) {
                            textureHandle = data.getHandleHigh();
                            if ((!(lastUnit0Handle == 0 || textureHandle == lastUnit0Handle) &&
                                  (lastUnit1Handle == 0 || textureHandle == lastUnit1Handle))                              
                                || (lastUsedSlot == 0 && lastUnit0Handle != 0))
                            {
                                data.setHandleLow(to_base(ShaderProgram::TextureUsage::UNIT1));
                                    // Set this to 1 if we need to use texture UNIT1 instead of UNIT0 as the main texture
                                    dataOut._properties.w = 1;
                                    lastUnit1Handle = textureHandle;
                                    lastUsedSlot = 1;
                            } else {
                                lastUnit0Handle = textureHandle;
                                lastUsedSlot = 0;
                            }
                        }
                    }
                } else {
                    //set properties.w to -1 to skip occlusion culling for the node
                    dataOut._properties.w = pkg.isOcclusionCullable() ? 1.0f : -1.0f;
                }

                if (refreshNodeData) {
                    for (GenericDrawCommand& cmd : pkg._drawCommands) {
                        for (U32 i = 0; i < cmd.drawCount(); ++i) {
                            _drawCommandsCache[cmdCount++].set(cmd.cmd());
                        }
                    }
                } else {
                    if (Config::Build::IS_DEBUG_BUILD) {
                        for (GenericDrawCommand& cmd : pkg._drawCommands) {
                            for (U32 i = 0; i < cmd.drawCount(); ++i) {
                                DIVIDE_ASSERT(_drawCommandsCache[cmdCount++] == cmd.cmd());
                            }
                        }
                    }
                }
            }
            nodeCount++;
        }
    });
    
    if (refreshNodeData) {
        bufferData._lastCommandCount = cmdCount;
        bufferData._lasNodeCount = nodeCount;

        assert(cmdCount >= nodeCount);
        // If the buffer update required is large enough, just replace the entire thing
        if (nodeCount > Config::MAX_VISIBLE_NODES / 2) {
            bufferData._renderData->setData(_matricesData.data());
        } else {
            // Otherwise, just update the needed range to save bandwidth
            bufferData._renderData->updateData(0, nodeCount, _matricesData.data());
        }

        ShaderBuffer& cmdBuffer = *bufferData._cmdBuffer;
        cmdBuffer.setData(_drawCommandsCache.data());
        _api->registerCommandBuffer(cmdBuffer);

        // This forces a sync for each buffer to make sure all data is properly uploaded in VRAM
        bufferData._renderData->bind(ShaderBufferLocation::NODE_INFO);
    } else {
        if (Config::Build::IS_DEBUG_BUILD) {
            assert(!bufferData._renderData->bind(ShaderBufferLocation::NODE_INFO));
        }
    }
}

void GFXDevice::occlusionCull(const RenderPass::BufferData& bufferData, const Texture_ptr& depthBuffer) {
    return;

    static const U32 GROUP_SIZE_AABB = 64;
    uploadGPUBlock();

    bufferData._cmdBuffer->bind(ShaderBufferLocation::GPU_COMMANDS);
    bufferData._cmdBuffer->bindAtomicCounter();

    depthBuffer->bind(to_U8(ShaderProgram::TextureUsage::DEPTH));
    U32 cmdCount = bufferData._lastCommandCount;

    _HIZCullProgram->bind();
    _HIZCullProgram->Uniform("dvd_numEntities", cmdCount);
    _HIZCullProgram->DispatchCompute((cmdCount + GROUP_SIZE_AABB - 1) / GROUP_SIZE_AABB, 1, 1);
    _HIZCullProgram->SetMemoryBarrier(ShaderProgram::MemoryBarrierType::COUNTER);
}

U32 GFXDevice::getLastCullCount() const {
    const RenderPass::BufferData& bufferData = parent().renderPassManager().getBufferData(RenderStage::DISPLAY, 0);

    U32 cullCount = bufferData._cmdBuffer->getAtomicCounter();
    if (cullCount > 0) {
        bufferData._cmdBuffer->resetAtomicCounter();
    }
    return cullCount;
}

bool GFXDevice::batchCommands(GenericDrawCommand& previousIDC,
                              GenericDrawCommand& currentIDC) const {
    if (previousIDC.compatible(currentIDC) &&
        // Batchable commands must share the same buffer
        previousIDC.sourceBuffer()->getGUID() ==
        currentIDC.sourceBuffer()->getGUID() &&
        // And the same shader program
        previousIDC.pipeline().shaderProgram()->getID() ==
        currentIDC.pipeline().shaderProgram()->getID())
    {
        U32 prevCount = previousIDC.drawCount();
        if (previousIDC.cmd().baseInstance + prevCount != currentIDC.cmd().baseInstance) {
            return false;
        }
        // If the rendering commands are batchable, increase the draw count for
        // the previous one
        previousIDC.drawCount(to_U16(prevCount + currentIDC.drawCount()));
        // And set the current command's draw count to zero so it gets removed
        // from the list later on
        currentIDC.drawCount(0);

        return true;
    }

    return false;
}

bool GFXDevice::draw(const GenericDrawCommand& cmd) {
    uploadGPUBlock();
    if (_api->draw(cmd)) {
        if (cmd.isEnabledOption(GenericDrawCommand::RenderOptions::RENDER_GEOMETRY)) {
            registerDrawCall();
        }
        if (cmd.isEnabledOption(GenericDrawCommand::RenderOptions::RENDER_WIREFRAME)) {
            registerDrawCall();
        }
        return true;
    }

    return false;
}


void GFXDevice::flushDisplay(const vec4<I32>& targetViewport) {
    PipelineDescriptor pipelineDescriptor;
    pipelineDescriptor._stateHash = getDefaultStateBlock(true);
    pipelineDescriptor._shaderProgram = _displayShader;

    GenericDrawCommand triangleCmd;
    triangleCmd.primitiveType(PrimitiveType::TRIANGLES);
    triangleCmd.drawCount(1);
    triangleCmd.pipeline(newPipeline(pipelineDescriptor));

    RenderTarget& screen = renderTarget(RenderTargetID(RenderTargetUsage::SCREEN));
    screen.bind(to_U8(ShaderProgram::TextureUsage::UNIT0),
                RTAttachment::Type::Colour,
                to_U8(ScreenTargets::ALBEDO));


    GFX::ScopedViewport targetArea(*this, targetViewport);

    // Blit render target to screen
    draw(triangleCmd);


    // Render all 2D debug info and call API specific flush function
    if (Application::instance().mainLoopActive()) {
        GFX::Scoped2DRendering scoped2D(*this);
        ReadLock r_lock(_2DRenderQueueLock);
        for (std::pair<U32, GUID2DCbk>& callbackFunction : _2dRenderQueue) {
            callbackFunction.second.second();
        }
    }
}

};

Commits for Divide-Framework/trunk/Source Code/Platform/Video/GFXDeviceDraw.cpp

Diff revisions: vs.
Revision Author Commited Message
893 Diff Diff IonutCava picture IonutCava Sun 18 Jun, 2017 17:33:07 +0000

[Ionut]
- Initial implementation of a PipelineStateObject (holds shader program, rasterizer state, etc)
- Rework PCH implementation a bit because VS2017 no longer has a /ZM option

890 Diff Diff IonutCava picture IonutCava Sun 14 May, 2017 20:54:59 +0000

[Ionut]
- Add pre-compiled header support
- Initial code for per-stage tessellation computation

881 Diff Diff IonutCava picture IonutCava Tue 21 Mar, 2017 22:07:37 +0000

[IonutCava]
- Multi draw command bug fix: drawCount > 1 should properly register all commands in the command buffer
- More tessellated terrain updates and fixes (still Work In Progress)

877 Diff Diff IonutCava picture IonutCava Thu 16 Mar, 2017 21:55:59 +0000

[IonutCava]
- Reflection updates
- Sky parallax fixes
- Initial support for Tessellation patches (used by the new terrain system – W.I.P.)

872 Diff Diff IonutCava picture IonutCava Mon 06 Mar, 2017 23:23:20 +0000

[IonutCava]
- Optimise static casts

867 Diff Diff IonutCava picture IonutCava Mon 20 Feb, 2017 17:01:12 +0000

[IonutCava]
- Rename to_XNN and to_const_XNN functions to reflect the target data type they are converting to.
- Cleanup Angle namespace and remove all “inDegrees” parameters from rotation functions. Use aliases to differentiate between Degree and Radian parameters.
- Profile guided optimizations.

864 Diff Diff IonutCava picture IonutCava Thu 16 Feb, 2017 17:29:19 +0000

[IonutCava]
- Profile guided optimizations

863 Diff Diff IonutCava picture IonutCava Wed 15 Feb, 2017 16:27:26 +0000

[IonutCava]
- Split Resource class into Resource and CachedResource
— CachedResource is the only resource held in a ResourceCache and loaded from a ResourceDescriptor
— CachedResource is mapped by its creation descriptor’s hash value, instead of the resource name
-— Multiple cached resources can now exist with the same name if the have different properties, for example.

851 Diff Diff IonutCava picture IonutCava Mon 06 Feb, 2017 23:38:14 +0000

[IonutCava]
- Replaced most RenderStage params with RenderStagePass types
- More work on water rendering

847 IonutCava picture IonutCava Sun 05 Feb, 2017 21:16:24 +0000

[IonutCava]
- Code rot fixes:
— Terrain loading (8 bit heightmap only for now)
— Terrain rendering
— Water Plane loading and rendering
— Reflection and Refraction rendering passes (hack for now: need environment cubemaps as separate from reflect/refract maps for planar rendering)
-— ToDo: Separate Reflection / Refraction render targets to Planar R/R and Cube R/R. Environment probes should use Cube Reflections, Water should use planar reflection targets.
- Added a way to register debug views: texture, shader and params. Viewports get automatically scaled and positioned
— ToDo: Add a hover-preview feature
— ToDo: Add a click-lock preview feature