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

#include "Headers/GFXDevice.h"

#include "Core/Headers/Kernel.h"
#include "Core/Headers/Application.h"
#include "Core/Headers/ParamHandler.h"
#include "Core/Headers/StringHelper.h"
#include "Core/Headers/Configuration.h"
#include "Core/Headers/PlatformContext.h"
#include "Core/Resources/Headers/ResourceCache.h"

#include "Rendering/Headers/Renderer.h"
#include "Rendering/Camera/Headers/Camera.h"
#include "Rendering/PostFX/Headers/PostFX.h"
#include "Rendering/Headers/EnvironmentProbe.h"

#include "Managers/Headers/RenderPassManager.h"

#include "Platform/Video/Headers/IMPrimitive.h"
#include "Platform/Video/Headers/RenderStateBlock.h"
#include "Platform/Video/Textures/Headers/Texture.h"
#include "Platform/Video/Shaders/Headers/ShaderProgram.h"
#include "Platform/Video/Buffers/RenderTarget/Headers/RenderTarget.h"
#include "Platform/Video/Buffers/ShaderBuffer/Headers/ShaderBuffer.h"

#include "Geometry/Material/Headers/ShaderComputeQueue.h"

#include "Platform/Video/OpenGL/Headers/GLWrapper.h"
#include "Platform/Video/Direct3D/Headers/DXWrapper.h"

#include "RenderDoc-Manager/RenderDocManager.h"

namespace Divide {

/// Create a display context using the selected API and create all of the needed
/// primitives needed for frame rendering
ErrorCode GFXDevice::initRenderingAPI(I32 argc, char** argv, const vec2<U16>& renderResolution) {
    ErrorCode hardwareState = createAPIInstance();
    const Configuration& config = _parent.platformContext().config();

    if (hardwareState == ErrorCode::NO_ERR) {
        // Initialize the rendering API
        if (Config::ENABLE_GPU_VALIDATION) {
           //_renderDocManager = 
           //   std::make_shared<RenderDocManager>(const_sysInfo()._windowHandle,
           //                                      ".\\RenderDoc\\renderdoc.dll",
           //                                      L"\\RenderDoc\\Captures\\");
        }
        hardwareState = _api->initRenderingAPI(argc, argv, config);
    }

    if (hardwareState != ErrorCode::NO_ERR) {
        // Validate initialization
        return hardwareState;
    }

    stringImpl refreshRates;
    vectorAlg::vecSize displayCount = gpuState().getDisplayCount();
    for (vectorAlg::vecSize idx = 0; idx < displayCount; ++idx) {
        const vectorImpl<GPUState::GPUVideoMode>& registeredModes = gpuState().getDisplayModes(idx);
        Console::printfn(Locale::get(_ID("AVAILABLE_VIDEO_MODES")), idx, registeredModes.size());

        for (const GPUState::GPUVideoMode& mode : registeredModes) {
            // Optionally, output to console/file each display mode
            refreshRates = Util::StringFormat("%d", mode._refreshRate.front());
            vectorAlg::vecSize refreshRateCount = mode._refreshRate.size();
            for (vectorAlg::vecSize i = 1; i < refreshRateCount; ++i) {
                refreshRates += Util::StringFormat(", %d", mode._refreshRate[i]);
            }
            Console::printfn(Locale::get(_ID("CURRENT_DISPLAY_MODE")),
                mode._resolution.width,
                mode._resolution.height,
                mode._bitDepth,
                mode._formatName.c_str(),
                refreshRates.c_str());
        }
    }

    ResourceCache& cache = parent().resourceCache();
    _rtPool = MemoryManager_NEW GFXRTPool(*this);

    // Initialize the shader manager
    ShaderProgram::onStartup(cache);
    EnvironmentProbe::onStartup(*this);
    PostFX::createInstance();
    // Create a shader buffer to store the GFX rendering info (matrices, options, etc)
    ShaderBufferParams params;
    params._primitiveCount = 1;
    params._primitiveSizeInBytes = sizeof(GFXShaderData::GPUData);
    params._ringBufferLength = 1;
    params._unbound = false;
    params._updateFrequency = BufferUpdateFrequency::OFTEN;
    params._initialData = &_gpuBlock._data;
    _gfxDataBuffer = newSB(params);

    _shaderComputeQueue = MemoryManager_NEW ShaderComputeQueue(cache);

    // Utility cameras
    _2DCamera = Camera::createCamera("2DRenderCamera", Camera::CameraType::FREE_FLY);
    _cubeCamera = Camera::createCamera("_gfxCubeCamera", Camera::CameraType::FREE_FLY);
    _dualParaboloidCamera = Camera::createCamera("_gfxParaboloidCamera", Camera::CameraType::FREE_FLY);

    _2DCamera->lockView(true);

    // Create general purpose render state blocks
    RenderStateBlock::init();
    RenderStateBlock defaultState;
    _defaultStateBlockHash = defaultState.getHash();

    RenderStateBlock defaultStateNoDepth;
    defaultStateNoDepth.setZRead(false);
    _defaultStateNoDepthHash = defaultStateNoDepth.getHash();

    RenderStateBlock state2DRendering;
    state2DRendering.setCullMode(CullMode::NONE);
    state2DRendering.setZRead(false);
    _state2DRenderingHash = state2DRendering.getHash();

    RenderStateBlock stateDepthOnlyRendering;
    stateDepthOnlyRendering.setColourWrites(false, false, false, false);
    stateDepthOnlyRendering.setZFunc(ComparisonFunction::ALWAYS);
    _stateDepthOnlyRenderingHash = stateDepthOnlyRendering.getHash();

    // The general purpose render state blocks are both mandatory and must
    // differ from each other at a state hash level
    assert(_stateDepthOnlyRenderingHash != _state2DRenderingHash &&
           "GFXDevice error: Invalid default state hash detected!");
    assert(_state2DRenderingHash != _defaultStateNoDepthHash &&
           "GFXDevice error: Invalid default state hash detected!");
    assert(_defaultStateNoDepthHash != _defaultStateBlockHash &&
           "GFXDevice error: Invalid default state hash detected!");
    // Activate the default render states
    _api->setStateBlock(_defaultStateBlockHash);
    // Our default render targets hold the screen buffer, depth buffer, and a
    // special, on demand,
    // down-sampled version of the depth buffer
    // Screen FB should use MSAA if available
    allocateRT(RenderTargetUsage::SCREEN, "Screen");
    // We need to create all of our attachments for the default render targets
    // Start with the screen render target: Try a half float, multisampled
    // buffer (MSAA + HDR rendering if possible)
    TextureDescriptor screenDescriptor(TextureType::TEXTURE_2D_MS,
                                       GFXImageFormat::RGBA16F,
                                       GFXDataFormat::FLOAT_16);

    TextureDescriptor hiZDescriptor(TextureType::TEXTURE_2D_MS,
                                    GFXImageFormat::DEPTH_COMPONENT32F,
                                    GFXDataFormat::FLOAT_32);

    SamplerDescriptor hiZSampler;
    hiZSampler.setFilters(TextureFilter::NEAREST_MIPMAP_NEAREST);
    hiZSampler.setWrapMode(TextureWrap::CLAMP_TO_EDGE);
    hiZSampler.toggleMipMaps(true);
    hiZDescriptor.setSampler(hiZSampler);
    hiZDescriptor.toggleAutomaticMipMapGeneration(false);

    SamplerDescriptor screenSampler;
    screenSampler.setFilters(TextureFilter::NEAREST);
    screenSampler.setWrapMode(TextureWrap::CLAMP_TO_EDGE);
    screenSampler.toggleMipMaps(false);
    screenDescriptor.setSampler(screenSampler);

    TextureDescriptor normalDescriptor(TextureType::TEXTURE_2D,
                                       GFXImageFormat::RG16F,
                                       GFXDataFormat::FLOAT_16);
    normalDescriptor.setSampler(screenSampler);
    
    TextureDescriptor velocityDescriptor(TextureType::TEXTURE_2D,
                                         GFXImageFormat::RG16F,
                                         GFXDataFormat::FLOAT_16);
    velocityDescriptor.setSampler(screenSampler);

    // Add the attachments to the render targets
    RenderTarget& screenTarget = renderTarget(RenderTargetID(RenderTargetUsage::SCREEN));
    screenTarget.addAttachment(screenDescriptor, RTAttachment::Type::Colour, to_const_ubyte(ScreenTargets::ALBEDO));
    screenTarget.addAttachment(normalDescriptor, RTAttachment::Type::Colour, to_const_ubyte(ScreenTargets::NORMALS));
    screenTarget.addAttachment(velocityDescriptor, RTAttachment::Type::Colour, to_const_ubyte(ScreenTargets::VELOCITY));
    screenTarget.addAttachment(hiZDescriptor,  RTAttachment::Type::Depth, 0);
    screenTarget.setClearColour(RTAttachment::Type::Colour, to_const_ubyte(ScreenTargets::ALBEDO), DefaultColours::DIVIDE_BLUE());
    screenTarget.setClearColour(RTAttachment::Type::Colour, to_const_ubyte(ScreenTargets::NORMALS), DefaultColours::WHITE());
    screenTarget.setClearColour(RTAttachment::Type::Colour, to_const_ubyte(ScreenTargets::VELOCITY), DefaultColours::WHITE());

    // Reflection Targets
    SamplerDescriptor reflectionSampler;
    reflectionSampler.setFilters(TextureFilter::NEAREST);
    reflectionSampler.setWrapMode(TextureWrap::CLAMP_TO_EDGE);
    reflectionSampler.toggleMipMaps(false);
    TextureDescriptor environmentDescriptor(TextureType::TEXTURE_CUBE_MAP,
                                            GFXImageFormat::RGBA16F,
                                            GFXDataFormat::FLOAT_16);
    environmentDescriptor.setSampler(reflectionSampler);

    TextureDescriptor depthDescriptor(TextureType::TEXTURE_CUBE_MAP,
                                      GFXImageFormat::DEPTH_COMPONENT32F,
                                      GFXDataFormat::FLOAT_32);

    depthDescriptor.setSampler(reflectionSampler);

    RenderTargetHandle tempHandle;
    for (U32 i = 0; i < Config::MAX_REFLECTIVE_NODES_IN_VIEW; ++i) {
        tempHandle = allocateRT(RenderTargetUsage::REFLECTION, Util::StringFormat("Reflection_%d", i));
        tempHandle._rt->addAttachment(environmentDescriptor, RTAttachment::Type::Colour, 0);
        tempHandle._rt->addAttachment(depthDescriptor, RTAttachment::Type::Depth, 0);
        tempHandle._rt->create(Config::REFLECTION_TARGET_RESOLUTION);
        tempHandle._rt->setClearColour(RTAttachment::Type::COUNT, 0, DefaultColours::WHITE());
    }

    for (U32 i = 0; i < Config::MAX_REFRACTIVE_NODES_IN_VIEW; ++i) {
        tempHandle = allocateRT(RenderTargetUsage::REFRACTION, Util::StringFormat("Refraction_%d", i));
        tempHandle._rt->addAttachment(environmentDescriptor, RTAttachment::Type::Colour, 0);
        tempHandle._rt->addAttachment(depthDescriptor, RTAttachment::Type::Depth, 0);
        tempHandle._rt->create(Config::REFRACTION_TARGET_RESOLUTION);
        tempHandle._rt->setClearColour(RTAttachment::Type::COUNT, 0, DefaultColours::WHITE());
    }

    // Initialized our HierarchicalZ construction shader (takes a depth
    // attachment and down-samples it for every mip level)
    _HIZConstructProgram = CreateResource<ShaderProgram>(cache, ResourceDescriptor("HiZConstruct"));
    _HIZCullProgram = CreateResource<ShaderProgram>(cache, ResourceDescriptor("HiZOcclusionCull"));
    _displayShader = CreateResource<ShaderProgram>(cache, ResourceDescriptor("display"));

    PostFX& postFX = PostFX::instance();

    // Register a 2D function used for previewing the depth buffer.
    if (Config::Build::IS_DEBUG_BUILD) {
        add2DRenderFunction(GUID_DELEGATE_CBK([this]() { previewDepthBuffer(); }), 0);
    }
    
    ParamHandler::instance().setParam<bool>(_ID("rendering.previewDepthBuffer"), false);
    // If render targets ready, we initialize our post processing system
    postFX.init(*this, cache);
    if (config.rendering.postAASamples > 0) {
        postFX.pushFilter(FilterType::FILTER_SS_ANTIALIASING);
    }
    if (false) {
        postFX.pushFilter(FilterType::FILTER_SS_REFLECTIONS);
    }
    if (config.rendering.enableSSAO) {
        postFX.pushFilter(FilterType::FILTER_SS_AMBIENT_OCCLUSION);
    }
    if (config.rendering.enableDepthOfField) {
        postFX.pushFilter(FilterType::FILTER_DEPTH_OF_FIELD);
    }
    if (false) {
        postFX.pushFilter(FilterType::FILTER_MOTION_BLUR);
    }
    if (config.rendering.enableBloom) {
        postFX.pushFilter(FilterType::FILTER_BLOOM);
    }
    if (false) {
        postFX.pushFilter(FilterType::FILTER_LUT_CORECTION);
    }

    _axisGizmo = newIMP();
    _axisGizmo->name("GFXDeviceAxisGizmo");
    RenderStateBlock primitiveDescriptor(RenderStateBlock::get(getDefaultStateBlock(true)));
    _axisGizmo->stateHash(primitiveDescriptor.getHash());

    _debugFrustumPrimitive = newIMP();
    _debugFrustumPrimitive->name("DebugFrustum");
    _debugFrustumPrimitive->stateHash(primitiveDescriptor.getHash());

    ResourceDescriptor previewNormalsShader("fbPreview");
    previewNormalsShader.setThreadedLoading(false);
    _renderTargetDraw = CreateResource<ShaderProgram>(cache, previewNormalsShader);
    assert(_renderTargetDraw != nullptr);

    // Create initial buffers, cameras etc for this resolution. It should match window size
    WindowManager& winMgr = Application::instance().windowManager();
    winMgr.handleWindowEvent(WindowEvent::RESOLUTION_CHANGED,
                             winMgr.getActiveWindow().getGUID(),
                             to_int(renderResolution.width),
                             to_int(renderResolution.height));
    setBaseViewport(vec4<I32>(0, 0, to_int(renderResolution.width), to_int(renderResolution.height)));

    // Everything is ready from the rendering point of view
    return ErrorCode::NO_ERR;
}

/// Revert everything that was set up in initRenderingAPI()
void GFXDevice::closeRenderingAPI() {
    assert(_api != nullptr && "GFXDevice error: closeRenderingAPI called without init!");
    _axisGizmo->clear();
    _debugFrustumPrimitive->clear();
    // Destroy our post processing system
    Console::printfn(Locale::get(_ID("STOP_POST_FX")));
    PostFX::destroyInstance();
    // Delete the renderer implementation
    Console::printfn(Locale::get(_ID("CLOSING_RENDERER")));
    RenderStateBlock::clear();

    EnvironmentProbe::onShutdown(*this);
    MemoryManager::DELETE(_rtPool);

    _previewDepthMapShader = nullptr;
    _renderTargetDraw = nullptr;
    _HIZConstructProgram = nullptr;
    _HIZCullProgram = nullptr;
    _displayShader = nullptr;

    MemoryManager::DELETE(_renderer);

    // Close the shader manager
    MemoryManager::DELETE(_shaderComputeQueue);
    ShaderProgram::onShutdown();
    _gpuObjectArena.clear();
    // Close the rendering API
    _api->closeRenderingAPI();
    _api.release();
    if (!_graphicResources.empty()) {
        Console::errorfn(Locale::get(_ID("ERROR_GFX_LEAKED_RESOURCES")), _graphicResources.size());
    }
}

/// After a swap buffer call, the CPU may be idle waiting for the GPU to draw to
/// the screen, so we try to do some processing
void GFXDevice::idle() {
    static const Task idleTask;
    _shaderComputeQueue->idle();
    // Pass the idle call to the post processing system
    PostFX::instance().idle(_parent.platformContext().config());
    // And to the shader manager
    ShaderProgram::idle();

    UpgradableReadLock r_lock(_GFXLoadQueueLock);
    if (!_GFXLoadQueue.empty()) {
        for(DELEGATE_CBK<void, const Task&>& cbk : _GFXLoadQueue) {
            cbk(idleTask);
        }
        UpgradeToWriteLock w_lock(r_lock);
        _GFXLoadQueue.clear();
    }
}

void GFXDevice::beginFrame() {
    if (Config::ENABLE_GPU_VALIDATION) {
        if (_renderDocManager) {
            _renderDocManager->StartFrameCapture();
        }
    }

    _api->beginFrame();
    _api->setStateBlock(_defaultStateBlockHash);
}

void GFXDevice::endFrame(bool swapBuffers) {
    FRAME_COUNT++;
    FRAME_DRAW_CALLS_PREV = FRAME_DRAW_CALLS;
    FRAME_DRAW_CALLS = 0;
    
    // Activate the default render states
    _api->setStateBlock(_defaultStateBlockHash);
    // Unbind shaders
    ShaderProgram::unbind();
    _api->endFrame(swapBuffers);

    if (Config::ENABLE_GPU_VALIDATION) {
        if (_renderDocManager) {
            _renderDocManager->EndFrameCapture();
        }
    }
}

void GFXDevice::resizeHistory(U8 historySize) {
    while (_prevDepthBuffers.size() > historySize) {
        _prevDepthBuffers.pop_back();
    }

    while (_prevDepthBuffers.size() < historySize) {
        const Texture_ptr& src = renderTarget(RenderTargetID(RenderTargetUsage::SCREEN)).getAttachment(RTAttachment::Type::Depth, 0).asTexture();
        const TextureDescriptor& srcDesc = src->getDescriptor();

        ResourceDescriptor prevDepthTex(Util::StringFormat("PREV_DEPTH_%d", _prevDepthBuffers.size()));
        prevDepthTex.setPropertyDescriptor(srcDesc.getSampler());
        prevDepthTex.setEnumValue(to_uint(srcDesc._type));
        Texture_ptr tex = CreateResource<Texture>(parent().resourceCache(), prevDepthTex);
        assert(tex);
        Texture::TextureLoadInfo info;
        info._type = srcDesc._type;
        tex->setNumLayers(srcDesc._layerCount);
        tex->lockAutomaticMipMapGeneration(!srcDesc.automaticMipMapGeneration());
        tex->loadData(info, srcDesc, NULL, vec2<U16>(src->getWidth(), src->getHeight()), vec2<U16>(src->getMinMipLevel(), src->getMaxMipLevel()));

        _prevDepthBuffers.push_back(tex);
    }
}

void GFXDevice::historyIndex(U8 index, bool copyPrevious) {
    if (copyPrevious) {
        getPrevDepthBuffer()->copy(renderTarget(RenderTargetID(RenderTargetUsage::SCREEN)).getAttachment(RTAttachment::Type::Depth, 0).asTexture());
    }

    _historyIndex = index;
}

ErrorCode GFXDevice::createAPIInstance() {
    assert(_api == nullptr && "GFXDevice error: initRenderingAPI called twice!");

    ErrorCode err = ErrorCode::NO_ERR;
    switch (_API_ID) {
        case RenderAPI::OpenGL:
        case RenderAPI::OpenGLES: {
            _api = std::make_unique<GL_API>(*this);
        } break;
        case RenderAPI::Direct3D: {
            _api = std::make_unique<DX_API>(*this);
        } break;

        default:
        case RenderAPI::None:
        case RenderAPI::Vulkan: {
            err = ErrorCode::GFX_NON_SPECIFIED;
        } break;
    };

    DIVIDE_ASSERT(_api != nullptr, Locale::get(_ID("ERROR_GFX_DEVICE_API")));
    return err;
}

};

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

Diff revisions: vs.
Revision Author Commited Message
842 Diff Diff IonutCava picture IonutCava Wed 01 Feb, 2017 17:25:15 +0000

[IonutCava]
- Start to implement scripting support via ChaiScript: http://chaiscript.com/
- Cleanup DELEGATE_CBK alias

837 Diff Diff IonutCava picture IonutCava Sun 29 Jan, 2017 15:45:58 +0000

[IonutCava]
- File system updates

830 Diff Diff IonutCava picture IonutCava Wed 25 Jan, 2017 17:29:44 +0000

[IonutCava]
- Add a new Platform element: File
— Move all predefined paths to FileManagement System
- Split MathHelper into MathHelper and StringHelper

829 Diff Diff IonutCava picture IonutCava Tue 24 Jan, 2017 17:28:39 +0000

[IonutCava]
- Separate resourceLocation for resources into resourceLocation and resourceName.
- More XML config loading refactoring

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

826 Diff Diff IonutCava picture IonutCava Fri 20 Jan, 2017 17:11:41 +0000

[IonutCava]
- Persistent buffer optimisations

824 Diff Diff IonutCava picture IonutCava Thu 19 Jan, 2017 17:18:03 +0000

[IonutCava]
- Prev Frame attachment system removed from RenderTargets
— Concept too high level for RT. Moved prev depth buffer to GFX class
- Other small optimizations.

822 Diff Diff IonutCava picture IonutCava Tue 17 Jan, 2017 22:47:06 +0000

[IonutCava]
- Fix postFX per player rendering
- Fix player remove code (wasn’t removing nodes)

818 Diff Diff IonutCava picture IonutCava Mon 16 Jan, 2017 17:23:20 +0000

[IonutCava]
- Units get their bound node setup by the SGN UnitComponent and not during creation
- Profile guided optimizations

815 IonutCava picture IonutCava Thu 12 Jan, 2017 23:33:01 +0000

[IonutCava]
- Fixed viewport alignment issue
- Added per-player RenderTargets (added index support to GFXRTPool)
- Initial implementation of per-player cameras
— Removed defaultCamera
— Scenes now use a baseCamera as a template for new player cameras