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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
#include "config.h"

#include "Headers/RenderingComponent.h"

#include "Core/Headers/ParamHandler.h"
#include "Scenes/Headers/SceneState.h"
#include "Graphs/Headers/SceneGraphNode.h"
#include "Platform/Video/Headers/GFXDevice.h"
#include "Platform/Video/Headers/IMPrimitive.h"
#include "Platform/Video/Headers/RenderStateBlock.h"
#include "Geometry/Shapes/Headers/Mesh.h"
#include "Geometry/Material/Headers/Material.h"
#include "Dynamics/Entities/Headers/Impostor.h"
#include "Rendering/Lighting/Headers/LightPool.h"

namespace Divide {

RenderingComponent::RenderingComponent(Material_ptr materialInstance,
                                       SceneGraphNode& parentSGN)
    : SGNComponent(SGNComponent::ComponentType::RENDERING, parentSGN),
      _lodLevel(0),
      _drawOrder(0),
      _commandIndex(0),
      _commandOffset(0),
      _castsShadows(true),
      _receiveShadows(true),
      _renderWireframe(false),
      _renderGeometry(true),
      _renderBoundingBox(false),
      _renderBoundingSphere(false),
      _renderSkeleton(false),
      _materialInstance(materialInstance),
      _skeletonPrimitive(nullptr)
{
    Object3D_ptr node = parentSGN.getNode<Object3D>();
    Object3D::ObjectType type = node->getObjectType();
    SceneNodeType nodeType = node->getType();

    bool isSubMesh = type == Object3D::ObjectType::SUBMESH;
    bool nodeSkinned = parentSGN.getNode<Object3D>()->getObjectFlag(Object3D::ObjectFlag::OBJECT_FLAG_SKINNED);

    if (_materialInstance) {
        assert(!_materialInstance->getName().empty());
        if (!isSubMesh) {
            _materialInstance->addShaderModifier(RenderStage::SHADOW, "TriangleStrip");
            _materialInstance->setShaderDefines(RenderStage::SHADOW, "USE_TRIANGLE_STRIP");
        }
    }

    for (GFXDevice::RenderPackage& pkg : _renderData) {
        pkg._textureData.reserve(ParamHandler::instance().getParam<I32>(_ID("rendering.maxTextureSlots"), 16));
        pkg.isOcclusionCullable(nodeType != SceneNodeType::TYPE_SKY);
    }

    // Prepare it for rendering lines
    RenderStateBlock primitiveStateBlock;

    _boundingBoxPrimitive[0] = GFX_DEVICE.getOrCreatePrimitive(false);
    _boundingBoxPrimitive[0]->name("BoundingBox_" + parentSGN.getName());
    _boundingBoxPrimitive[0]->stateHash(primitiveStateBlock.getHash());
    _boundingBoxPrimitive[0]->paused(true);

    _boundingBoxPrimitive[1] = GFX_DEVICE.getOrCreatePrimitive(false);
    _boundingBoxPrimitive[1]->name("BoundingBox_Parent_" + parentSGN.getName());
    _boundingBoxPrimitive[1]->stateHash(primitiveStateBlock.getHash());
    _boundingBoxPrimitive[1]->paused(true);

    _boundingSpherePrimitive = GFX_DEVICE.getOrCreatePrimitive(false);
    _boundingSpherePrimitive->name("BoundingSphere_" + parentSGN.getName());
    _boundingSpherePrimitive->stateHash(primitiveStateBlock.getHash());
    _boundingSpherePrimitive->paused(true);

    if (nodeSkinned) {
        primitiveStateBlock.setZRead(false);
        _skeletonPrimitive = GFX_DEVICE.getOrCreatePrimitive(false);
        _skeletonPrimitive->name("Skeleton_" + parentSGN.getName());
        _skeletonPrimitive->stateHash(primitiveStateBlock.getHash());
        _skeletonPrimitive->paused(true);
    }
    
    if (Config::Build::IS_DEBUG_BUILD) {
        // Red X-axis
        _axisLines.push_back(
            Line(VECTOR3_ZERO, WORLD_X_AXIS * 2, vec4<U8>(255, 0, 0, 255), 5.0f));
        // Green Y-axis
        _axisLines.push_back(
            Line(VECTOR3_ZERO, WORLD_Y_AXIS * 2, vec4<U8>(0, 255, 0, 255), 5.0f));
        // Blue Z-axis
        _axisLines.push_back(
            Line(VECTOR3_ZERO, WORLD_Z_AXIS * 2, vec4<U8>(0, 0, 255, 255), 5.0f));
        _axisGizmo = GFX_DEVICE.getOrCreatePrimitive(false);
        // Prepare it for line rendering
        size_t noDepthStateBlock = GFX_DEVICE.getDefaultStateBlock(true);
        RenderStateBlock stateBlock(RenderStateBlock::get(noDepthStateBlock));
        _axisGizmo->name("AxisGizmo_" + parentSGN.getName());
        _axisGizmo->stateHash(stateBlock.getHash());
        _axisGizmo->paused(true);
        // Create the object containing all of the lines
        _axisGizmo->beginBatch(true, to_uint(_axisLines.size()) * 2, 1);
        _axisGizmo->attribute4f(to_const_uint(AttribLocation::VERTEX_COLOR), Util::ToFloatColour(_axisLines[0]._colourStart));
        // Set the mode to line rendering
        _axisGizmo->begin(PrimitiveType::LINES);
        // Add every line in the list to the batch
        for (const Line& line : _axisLines) {
            _axisGizmo->attribute4f(to_const_uint(AttribLocation::VERTEX_COLOR), Util::ToFloatColour(line._colourStart));
            _axisGizmo->vertex(line._startPoint);
            _axisGizmo->vertex(line._endPoint);
        }
        _axisGizmo->end();
        // Finish our object
        _axisGizmo->endBatch();
    } else {
        _axisGizmo = nullptr;
    }
}

RenderingComponent::~RenderingComponent()
{
    _boundingBoxPrimitive[0]->_canZombify = true;
    _boundingBoxPrimitive[1]->_canZombify = true;
    _boundingSpherePrimitive->_canZombify = true;
    if (_skeletonPrimitive) {
        _skeletonPrimitive->_canZombify = true;
    }
    if (Config::Build::IS_DEBUG_BUILD) {
        _axisGizmo->_canZombify = true;
    }
}

void RenderingComponent::update(const U64 deltaTime) {
    const Material_ptr& mat = getMaterialInstance();
    if (mat) {
        mat->update(deltaTime);
    }

    Object3D::ObjectType type = _parentSGN.getNode<Object3D>()->getObjectType();
    // Continue only for skinned submeshes
    if (type == Object3D::ObjectType::SUBMESH)
    {
        _parentSGN.getParent().lock()->getTrackedBools().setTrackedValue(StateTracker<bool>::State::BOUNDING_BOX_RENDERED, false);

        if (_parentSGN.getNode<Object3D>()->getObjectFlag(Object3D::ObjectFlag::OBJECT_FLAG_SKINNED)) {
            _parentSGN.getParent().lock()->getTrackedBools().setTrackedValue(StateTracker<bool>::State::SKELETON_RENDERED, false);
            _skeletonPrimitive->paused(true);
        }
    }

}

bool RenderingComponent::canDraw(const SceneRenderState& sceneRenderState,
                                 RenderStage renderStage) {
    bool canDraw = _parentSGN.getNode()->getDrawState(renderStage);
    if (canDraw) {
        const Material_ptr& mat = getMaterialInstance();
        if (mat) {
            if (!mat->canDraw(renderStage)) {
                return false;
            }
        }
    }

    return canDraw;
}

void RenderingComponent::rebuildMaterial() {
    const Material_ptr& mat = getMaterialInstance();
    if (mat) {
       mat->rebuild();
    }

    U32 childCount = _parentSGN.getChildCount();
    for (U32 i = 0; i < childCount; ++i) {
        RenderingComponent* const renderable =
            _parentSGN.getChild(i, childCount).get<RenderingComponent>();
        if (renderable) {
            renderable->rebuildMaterial();
        }
    }
}

void RenderingComponent::registerTextureDependency(const TextureData& additionalTexture) {
    size_t inputHash = additionalTexture.getHash();
    TextureDataContainer::const_iterator it;
    it = std::find_if(std::begin(_textureDependencies), std::end(_textureDependencies),
                      [&inputHash](const TextureData& textureData) { 
                            return (textureData.getHash() == inputHash); 
                      });

    if (it == std::end(_textureDependencies)) {
        _textureDependencies.push_back(additionalTexture);
    }
}

void RenderingComponent::removeTextureDependency(const TextureData& additionalTexture) {
    size_t inputHash = additionalTexture.getHash();
    TextureDataContainer::iterator it;
    it = std::find_if(std::begin(_textureDependencies), std::end(_textureDependencies),
                      [&inputHash](const TextureData& textureData) { 
                            return (textureData.getHash() == inputHash); 
                      });

    if (it != std::end(_textureDependencies)) {
        _textureDependencies.erase(it);
    }
}

bool RenderingComponent::onRender(RenderStage currentStage) {
    // Call any pre-draw operations on the SceneNode (refresh VB, update
    // materials, get list of textures, etc)

    GFXDevice::RenderPackage& pkg = _renderData[to_uint(currentStage)];

    pkg._textureData.resize(0);
    const Material_ptr& mat = getMaterialInstance();
    if (mat) {
        mat->getTextureData(pkg._textureData);
    }

    for (const TextureData& texture : _textureDependencies) {
        pkg._textureData.push_back(texture);
    }

    return _parentSGN.getNode()->onRender(_parentSGN, currentStage);
}

void RenderingComponent::renderGeometry(const bool state) {
    if (_renderGeometry != state) {
        _renderGeometry = state;

        U32 childCount = _parentSGN.getChildCount();
        for (U32 i = 0; i < childCount; ++i) {
            RenderingComponent* const renderable = 
                _parentSGN.getChild(i, childCount).get<RenderingComponent>();
            if (renderable) {
                renderable->renderGeometry(state);
            }
        }
    }
}

void RenderingComponent::renderWireframe(const bool state) {
    if (_renderWireframe != state) {
        _renderWireframe = state;
    
        U32 childCount = _parentSGN.getChildCount();
        for (U32 i = 0; i < childCount; ++i) {
            RenderingComponent* const renderable = _parentSGN.getChild(i, childCount).get<RenderingComponent>();
            if (renderable) {
                renderable->renderWireframe(state);
            }
        }
    }
}

void RenderingComponent::renderBoundingBox(const bool state) {
    if (_renderBoundingBox != state) {
        _renderBoundingBox = state;
        if (!state) {
            _boundingBoxPrimitive[0]->paused(true);
            _boundingBoxPrimitive[1]->paused(true);
        }
        U32 childCount = _parentSGN.getChildCount();
        for (U32 i = 0; i < childCount; ++i) {
            RenderingComponent* const renderable = _parentSGN.getChild(i, childCount).get<RenderingComponent>();
            if (renderable) {
                renderable->renderBoundingBox(state);
            }
        }
    }
}

void RenderingComponent::renderBoundingSphere(const bool state) {
    if (_renderBoundingSphere != state) {
        _renderBoundingSphere = state;
        if (!state) {
            _boundingSpherePrimitive->paused(true);
        }
        U32 childCount = _parentSGN.getChildCount();
        for (U32 i = 0; i < childCount; ++i) {
            RenderingComponent* const renderable = _parentSGN.getChild(i, childCount).get<RenderingComponent>();
            if (renderable) {
                renderable->renderBoundingSphere(state);
            }
        }
    }
}

void RenderingComponent::renderSkeleton(const bool state) {
    if (_renderSkeleton != state) {
        _renderSkeleton = state;
        if (!state && _skeletonPrimitive) {
            _skeletonPrimitive->paused(true);
        }
        U32 childCount = _parentSGN.getChildCount();
        for (U32 i = 0; i < childCount; ++i) {
            RenderingComponent* const renderable = _parentSGN.getChild(i, childCount).get<RenderingComponent>();
            if (renderable) {
                renderable->renderSkeleton(state);
            }
        }
    }
}

void RenderingComponent::castsShadows(const bool state) {
    if (_castsShadows != state) {
        _castsShadows = state;
    
        U32 childCount = _parentSGN.getChildCount();
        for (U32 i = 0; i < childCount; ++i) {
            RenderingComponent* const renderable = _parentSGN.getChild(i, childCount).get<RenderingComponent>();
            if (renderable) {
                renderable->castsShadows(_castsShadows);
            }
        }
    }
}

void RenderingComponent::receivesShadows(const bool state) {
    if (_receiveShadows != state) {
        _receiveShadows = state;
    
        U32 childCount = _parentSGN.getChildCount();
        for (U32 i = 0; i < childCount; ++i) {
            RenderingComponent* const renderable = _parentSGN.getChild(i, childCount).get<RenderingComponent>();
            if (renderable) {
                renderable->receivesShadows(_receiveShadows);
            }
        }
    }
}

bool RenderingComponent::castsShadows() const {
    return _castsShadows;
}

bool RenderingComponent::receivesShadows() const {
    return _receiveShadows;
}

void RenderingComponent::getMaterialColourMatrix(mat4<F32>& matOut) const {
    matOut.zero();

    const Material_ptr& mat = getMaterialInstance();
    if (mat) {
        mat->getMaterialMatrix(matOut);
    }
}

void RenderingComponent::getRenderingProperties(vec4<F32>& propertiesOut, vec4<F32>& extraPropertiesOut) const {
    propertiesOut.set(_parentSGN.getSelectionFlag() == SceneGraphNode::SelectionFlag::SELECTION_SELECTED
                                                     ? -1.0f
                                                     : _parentSGN.getSelectionFlag() == SceneGraphNode::SelectionFlag::SELECTION_HOVER
                                                                                      ? 1.0f
                                                                                      : 0.0f,
                      receivesShadows() ? 1.0f : 0.0f,
                      _lodLevel,
                      0.0);
    const Material_ptr& mat = getMaterialInstance();
    if (mat) {
        extraPropertiesOut.x = to_float(mat->defaultReflectionTextureIndex());
        extraPropertiesOut.y = to_float(mat->defaultRefractionTextureIndex());
    }
}

bool RenderingComponent::preDraw(const SceneRenderState& renderState,
                                 RenderStage renderStage) const {
    return _parentSGN.prepareDraw(renderState, renderStage);
}

/// Called after the current node was rendered
void RenderingComponent::postRender(const SceneRenderState& sceneRenderState, RenderStage renderStage) {
    
    if (renderStage != RenderStage::DISPLAY || GFX_DEVICE.isPrePass()) {
        return;
    }

    const SceneNode_ptr& node = _parentSGN.getNode();

    if (Config::Build::IS_DEBUG_BUILD) {
        switch(sceneRenderState.gizmoState()){
            case SceneRenderState::GizmoState::ALL_GIZMO: {
                if (node->getType() == SceneNodeType::TYPE_OBJECT3D) {
                    if (_parentSGN.getNode<Object3D>()->getObjectType() == Object3D::ObjectType::SUBMESH) {
                        drawDebugAxis();
                    }
                }
            } break;
            case SceneRenderState::GizmoState::SELECTED_GIZMO: {
                switch (_parentSGN.getSelectionFlag()) {
                    case SceneGraphNode::SelectionFlag::SELECTION_SELECTED : {
                        drawDebugAxis();
                    } break;
                    default: {
                        _axisGizmo->paused(true);
                    } break;
                }
            } break;
            default: {
                _axisGizmo->paused(true);
            } break;
        }
    }

    SceneGraphNode_ptr grandParent = _parentSGN.getParent().lock();
    StateTracker<bool>& parentStates = grandParent->getTrackedBools();

    // Draw bounding box if needed and only in the final stage to prevent
    // Shadow/PostFX artifacts
    if (renderBoundingBox() || sceneRenderState.isEnabledOption(SceneRenderState::RenderOptions::RENDER_AABB)) {
        const BoundingBox& bb = _parentSGN.get<BoundsComponent>()->getBoundingBox();
        _boundingBoxPrimitive[0]->fromBox(bb.getMin(), bb.getMax(), vec4<U8>(0, 0, 255, 255));

        if (_parentSGN.getSelectionFlag() == SceneGraphNode::SelectionFlag::SELECTION_SELECTED) {
            renderBoundingSphere(true);
        } else {
            renderBoundingSphere(false);
        }

        Object3D::ObjectType type = _parentSGN.getNode<Object3D>()->getObjectType();
        bool isSubMesh = type == Object3D::ObjectType::SUBMESH;
        if (isSubMesh) {
            bool renderParentBBFlagInitialized = false;
            bool renderParentBB = parentStates.getTrackedValue(StateTracker<bool>::State::BOUNDING_BOX_RENDERED,
                                   renderParentBBFlagInitialized);
            if (!renderParentBB || !renderParentBBFlagInitialized) {
                const BoundingBox& bbGrandParent = grandParent->get<BoundsComponent>()->getBoundingBox();
                _boundingBoxPrimitive[1]->fromBox(
                                     bbGrandParent.getMin() - vec3<F32>(0.0025f),
                                     bbGrandParent.getMax() + vec3<F32>(0.0025f),
                                     vec4<U8>(0, 128, 128, 255));
            }
        }
    } else {
        _boundingBoxPrimitive[0]->paused(true);
        _boundingBoxPrimitive[1]->paused(true);
        renderBoundingSphere(false);
    }

    
    if (renderBoundingSphere()) {
        const BoundingSphere& bs = _parentSGN.get<BoundsComponent>()->getBoundingSphere();
        _boundingSpherePrimitive->fromSphere(bs.getCenter(), bs.getRadius(), vec4<U8>(0, 255, 0, 255));
    } else {
        _boundingSpherePrimitive->paused(true);
    }

    if (_renderSkeleton || sceneRenderState.isEnabledOption(SceneRenderState::RenderOptions::RENDER_SKELETONS)) {
        // Continue only for skinned submeshes
        Object3D::ObjectType type = _parentSGN.getNode<Object3D>()->getObjectType();
        bool isSubMesh = type == Object3D::ObjectType::SUBMESH;
        if (isSubMesh && _parentSGN.getNode<Object3D>()->getObjectFlag(Object3D::ObjectFlag::OBJECT_FLAG_SKINNED))
        {
            bool renderSkeletonFlagInitialized = false;
            bool renderSkeleton = parentStates.getTrackedValue(StateTracker<bool>::State::SKELETON_RENDERED,
                                                               renderSkeletonFlagInitialized);
            if (!renderSkeleton || !renderSkeletonFlagInitialized) {
                // Get the animation component of any submesh. They should be synced anyway.
                AnimationComponent* childAnimComp =
                    _parentSGN.get<AnimationComponent>();
                // Get the skeleton lines from the submesh's animation component
                const vectorImpl<Line>& skeletonLines = childAnimComp->skeletonLines();
                _skeletonPrimitive->worldMatrix(_parentSGN.get<PhysicsComponent>()->getWorldMatrix());
                // Submit the skeleton lines to the GPU for rendering
                _skeletonPrimitive->fromLines(skeletonLines);
                parentStates.setTrackedValue(
                    StateTracker<bool>::State::SKELETON_RENDERED, true);
            }
        }
    } else {
        if (_skeletonPrimitive) {
            _skeletonPrimitive->paused(true);
        }
    }

    node->postRender(_parentSGN);
}

void RenderingComponent::registerShaderBuffer(ShaderBufferLocation slot,
                                              vec2<U32> bindRange,
                                              ShaderBuffer& shaderBuffer) {

    GFXDevice::ShaderBufferList::iterator it;
    for (GFXDevice::RenderPackage& pkg : _renderData) {
        GFXDevice::ShaderBufferList::iterator itEnd = std::end(pkg._shaderBuffers);
        it = std::find_if(std::begin(pkg._shaderBuffers), itEnd,
            [slot](const GFXDevice::ShaderBufferBinding& binding)
                    -> bool { return binding._slot == slot; });

        if (it == itEnd) {
           vectorAlg::emplace_back(pkg._shaderBuffers, slot, &shaderBuffer, bindRange);
        } else {
            it->set(slot, &shaderBuffer, bindRange);
        }
    }
}

void RenderingComponent::unregisterShaderBuffer(ShaderBufferLocation slot) {
    for (GFXDevice::RenderPackage& pkg : _renderData) {
        pkg._shaderBuffers.erase(
            std::remove_if(std::begin(pkg._shaderBuffers), std::end(pkg._shaderBuffers),
                [&slot](const GFXDevice::ShaderBufferBinding& binding)
                    -> bool { return binding._slot == slot; }),
            std::end(pkg._shaderBuffers));
    }
}

ShaderProgram_ptr RenderingComponent::getDrawShader(RenderStage renderStage) {
    return (getMaterialInstance()
                ? _materialInstance->getShaderInfo(renderStage).getProgram()
                : nullptr);
}

size_t RenderingComponent::getDrawStateHash(RenderStage renderStage) {
    if (!getMaterialInstance()) {
        return 0;
    }
    
    bool shadowStage = renderStage == RenderStage::SHADOW;
    bool depthPass = renderStage == RenderStage::Z_PRE_PASS || shadowStage;
    bool reflectionStage = renderStage == RenderStage::REFLECTION;
    bool refractionStage = renderStage == RenderStage::REFRACTION;

    if (!_materialInstance && depthPass) {
        
        return shadowStage
                   ? _parentSGN.getNode()->renderState().getShadowStateBlock()
                   : _parentSGN.getNode()->renderState().getDepthStateBlock();
    }

    RenderStage blockStage = depthPass ? (shadowStage ? RenderStage::SHADOW
                                                      : RenderStage::Z_PRE_PASS)
                                       : (reflectionStage ? RenderStage::REFLECTION
                                                          : refractionStage ? RenderStage::REFRACTION
                                                                            : RenderStage::DISPLAY);
    I32 variant = 0;
    if (shadowStage) {
        LightType type = LightPool::currentShadowCastingLight()->getLightType();
        variant = (type == LightType::DIRECTIONAL
                         ? 0
                         : type == LightType::POINT 
                                 ? 1
                                 : 2);
    }

    return _materialInstance->getRenderStateBlock(blockStage, variant);
    
}


GFXDevice::RenderPackage&
RenderingComponent::getDrawPackage(const SceneRenderState& sceneRenderState,
                                   RenderStage renderStage) {

    static const U32 SCENE_NODE_LOD0_SQ = Config::SCENE_NODE_LOD0 * Config::SCENE_NODE_LOD0;
    static const U32 SCENE_NODE_LOD1_SQ = Config::SCENE_NODE_LOD1 * Config::SCENE_NODE_LOD1;
    

    GFXDevice::RenderPackage& pkg = _renderData[to_uint(renderStage)];
    pkg.isRenderable(false);
    if (canDraw(sceneRenderState, renderStage) &&
        preDraw(sceneRenderState, renderStage))
    {
        if (_parentSGN.getNode()->getDrawCommands(_parentSGN,
                                                  renderStage,
                                                  sceneRenderState,
                                                  pkg._drawCommands)) {
            F32 cameraDistanceSQ =
                _parentSGN
                    .get<BoundsComponent>()
                    ->getBoundingSphere()
                    .getCenter()
                    .distanceSquared(sceneRenderState
                                     .getCameraConst()
                                     .getEye());

            U8 lodLevelTemp = cameraDistanceSQ > SCENE_NODE_LOD0_SQ
                                    ? cameraDistanceSQ > SCENE_NODE_LOD1_SQ ? 2 : 1
                                    : 0;
            U8 minLoD = to_ubyte(_parentSGN.getNode()->getLODcount() - 1);
            _lodLevel = (renderStage == RenderStage::REFLECTION || renderStage == RenderStage::REFRACTION)
                                    ? minLoD
                                    : std::min(minLoD, std::max(lodLevelTemp, to_ubyte(0)));

            U32 offset = commandOffset();
            for (GenericDrawCommand& cmd : pkg._drawCommands) {
                bool renderWireframe = cmd.isEnabledOption(GenericDrawCommand::RenderOptions::RENDER_WIREFRAME) ||
                                       sceneRenderState.isEnabledOption(SceneRenderState::RenderOptions::RENDER_WIREFRAME);
                cmd.toggleOption(GenericDrawCommand::RenderOptions::RENDER_WIREFRAME, renderWireframe);
                cmd.commandOffset(offset++);
                cmd.cmd().baseInstance = commandIndex();
                cmd.LoD(_lodLevel);
            }
            pkg.isRenderable(!pkg._drawCommands.empty());
        }
    }

    return pkg;
}

GFXDevice::RenderPackage& 
RenderingComponent::getDrawPackage(RenderStage renderStage) {
    return _renderData[to_uint(renderStage)];
}

void RenderingComponent::setActive(const bool state) {
    if (!state) {
        renderSkeleton(false);
        renderBoundingBox(false);
        renderBoundingSphere(false);
    }
    SGNComponent::setActive(state);
}

bool RenderingComponent::clearReflection() {
    // If we lake a material, we don't use reflections
    const Material_ptr& mat = getMaterialInstance();
    if (mat == nullptr) {
        return false;
    }

    mat->updateReflectionIndex(-1);
    return true;
}

bool RenderingComponent::updateReflection(U32 reflectionIndex,
                                          const vec3<F32>& camPos,
                                          const SceneRenderState& renderState)
{
    // Low lod entities don't need up to date reflections
    if (_lodLevel > 1) {
        return false;
    }
    // If we lake a material, we don't use reflections
    const Material_ptr& mat = getMaterialInstance();
    if (mat == nullptr) {
        return false;
    }

    mat->updateReflectionIndex(reflectionIndex);

    RenderTarget& reflectionTarget = GFX_DEVICE.renderTarget(RenderTargetID::REFLECTION, reflectionIndex);

    if (_reflectionCallback) {
        _reflectionCallback(_parentSGN, renderState, reflectionTarget, reflectionIndex);
    } else {
        const vec2<F32>& camZPlanes = renderState.getCameraConst().getZPlanes();

        GFX_DEVICE.generateCubeMap(reflectionTarget,
                                   0,
                                   camPos,
                                   vec2<F32>(camZPlanes.x, camZPlanes.y * 0.25f),
                                   RenderStage::REFLECTION,
                                   reflectionIndex);
    }

    return true;
}

bool RenderingComponent::clearRefraction() {
    const Material_ptr& mat = getMaterialInstance();
    if (mat == nullptr) {
        return false;
    }
    if (!mat->isTranslucent()) {
        return false;
    }
    mat->updateRefractionIndex(-1);
    return true;
}

bool RenderingComponent::updateRefraction(U32 refractionIndex,
                                          const vec3<F32>& camPos,
                                          const SceneRenderState& renderState) {
    // no default refraction system!
    if (!_refractionCallback) {
        return false;
    }
    // Low lod entities don't need up to date reflections
    if (_lodLevel > 1) {
        return false;
    }
    const Material_ptr& mat = getMaterialInstance();
    if (mat == nullptr) {
        return false;
    }
    // If shininess is below a certain threshold, we don't have any reflections 
    if (!mat->isTranslucent()) {
        return false;
    }

    mat->updateRefractionIndex(refractionIndex);

    _refractionCallback(_parentSGN,
                        renderState,
                        GFX_DEVICE.renderTarget(RenderTargetID::REFRACTION, refractionIndex),
                        refractionIndex);

    return true;
}

void RenderingComponent::updateEnvProbeList(const EnvironmentProbeList& probes) {
    _envProbes.resize(0);
    if (probes.empty()) {
        return;
    }

    _envProbes.insert(std::cend(_envProbes), std::cbegin(probes), std::cend(probes));

    PhysicsComponent* const transform = _parentSGN.get<PhysicsComponent>();
    if (transform) {
        const vec3<F32>& nodePos = transform->getPosition();
        auto sortFunc = [&nodePos](EnvironmentProbe* a, EnvironmentProbe* b) -> bool {
            return a->distanceSqTo(nodePos) < b->distanceSqTo(nodePos);
        };

        std::sort(std::begin(_envProbes), std::end(_envProbes), sortFunc);
    }
    const Material_ptr& mat = getMaterialInstance();
    if (mat == nullptr) {
        return;
    }

    RenderTarget* rt = EnvironmentProbe::reflectionTarget()._rt;
    mat->defaultReflectionTexture(rt->getAttachment(RTAttachment::Type::Colour, 0).asTexture(),
                                  _envProbes.front()->getRTIndex());
}

/// Draw the axis arrow gizmo
void RenderingComponent::drawDebugAxis() {
    if (!Config::Build::IS_DEBUG_BUILD) {
        return;
    }

    PhysicsComponent* const transform = _parentSGN.get<PhysicsComponent>();
    if (transform) {
        mat4<F32> tempOffset(GetMatrix(transform->getOrientation()));
        tempOffset.setTranslation(transform->getPosition());
        _axisGizmo->worldMatrix(tempOffset);
    } else {
        _axisGizmo->resetWorldMatrix();
    }
    _axisGizmo->paused(false);
}

};

Commits for Divide-Framework/trunk/Source Code/Graphs/Components/RenderingComponent.cpp

Diff revisions: vs.
Revision Author Commited Message
771 Diff Diff IonutCava picture IonutCava Tue 27 Sep, 2016 15:39:49 +0000

[IonutCava]
- Modify GFXDevice::flushRenderQueues so that it creates command buffers instead of directly calling rendering calls:
— Command buffers contain buffer, shader, texture and geometry info
— Command buffer state is now parsed and set at the API level instead of GFXDevice level
— This will allow easier porting to low level APIs later on
- Indirect draw is now a GenericDrawCommand render option instead of an explicit buffer draw parameter

767 Diff Diff IonutCava picture IonutCava Mon 22 Aug, 2016 16:25:37 +0000

[IonutCava]
- Descriptor/State cleanup part 3/3: GenericDrawCommand cleanup

766 Diff Diff IonutCava picture IonutCava Mon 22 Aug, 2016 15:54:49 +0000

[IonutCava]
- Descriptor/State cleanup part 2/3: SceneState/SceneRenderState cleanup

762 Diff Diff IonutCava picture IonutCava Thu 11 Aug, 2016 16:18:35 +0000

[IonutCava]
- Removed a lot of high level GFX state and merged it back on a lower level:
— depth mask is now a framebuffer specific toggle controlled by the RenderPolicy
— rasterization is now a per-buffer draw switch toggled by a rendering flag in GenericDrawCommand
- Replaced old style GL texture binding code with DSA style glBindTextures and glBindSamplers even for single textures
— completely removed the concept of a active texture unit in the GL code
- Fixed some draw policy settings that were clearing the depth buffer in the PostFX passes
- More build type flag replacement of macros
- Render pass system bug fixing
- Add option to skip occlusion culling for certain nodes

761 Diff Diff IonutCava picture IonutCava Wed 10 Aug, 2016 16:24:04 +0000

[IonutCava]
- More work on the new render pass system
- Added new HiZ culling code from nvidia samples: https://github.com/nvpro-samples/gl_occlusion_culling

760 Diff Diff IonutCava picture IonutCava Tue 09 Aug, 2016 16:30:12 +0000

[IonutCava]
- Complete rewrite of RenderPass system:
— Allow every rendering pass (reflection, environment, etc) to use the same rendering system: occlusion culling, light culling, etc
— Define render passes by a param based token similar to modern API systems (DX12/Vulkan)
— W.I.P.: Depth rendering slightly wrong; Environment Mapping ,reflection and refraction rendering currently disabled
- Add compile time variables for DEBUG/PROFILE/RELEASE builds to validate all code for every build

749 Diff Diff IonutCava picture IonutCava Mon 04 Jul, 2016 16:01:34 +0000

[IonutCava]
- Added initial environment mapping code:
— Allow adding, per scene, of multiple environment probes that generate cube map reflections
— Support 2 types of probes: infinite (such as sky only probes) and local. Local probes use an AABB that will later be used for parallax correction
— Probes are held in a scene specific pool, can be updated at different rates and their results can be passed on to materials (if materials don’t need specific reflection systems such as for water or mirrors)
- ToDo:
— Blend between probes (currently, only the closes one is selected)
— Reduce VRAM usage
— Set as fallback for screen space reflections

748 Diff Diff IonutCava picture IonutCava Thu 30 Jun, 2016 18:59:05 +0000

[IonutCava]
- Bug fixing for the new shader recompile system

747 Diff Diff IonutCava picture IonutCava Thu 30 Jun, 2016 15:32:46 +0000

[IonutCava]
- Rework shader recompilation system
— Added a recompile all system for shaders
— Added a recompile selected for materials
— Still buggy

734 IonutCava picture IonutCava Tue 21 Jun, 2016 16:28:11 +0000

[IonutCava]
- Added a render target pool:
— All render targets are now allocated (and tracked) by the GFXDevice.
— Allocation routines return a slim RenderTargetHandle object that will be used later on in draw commands.

- Added a refraction render pass that will handle translucent objects that need refracted textures instead of clear transparency
— Both reflective nodes and refractive nodes are not gathered properly at this point

- All API specific objects (buffers, textures, etc) are now initialized in the GFXDevice class (see GFXDeviceObjects.cpp)
— This allowed for the slimming of the RenderAPIWrapper interface

- Improved ENABLE_GPU_VALIDATION macro utilization:
— It enabled shadow map split plane debugging
— It bypasses loading shaders from text cache