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
#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/Camera/Headers/Camera.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)
{
    _customShaders.fill(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 (RenderPackage& pkg : _renderData) {
        pkg.isOcclusionCullable(nodeType != SceneNodeType::TYPE_SKY);
    }

    // Prepare it for rendering lines
    RenderStateBlock primitiveStateBlock;

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

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

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

    if (nodeSkinned) {
        primitiveStateBlock.setZRead(false);
        _skeletonPrimitive = GFX_DEVICE.newIMP();
        _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.newIMP();
        // 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]->clear();
    _boundingBoxPrimitive[1]->clear();
    _boundingSpherePrimitive->clear();

    if (_skeletonPrimitive != nullptr) {
        _skeletonPrimitive->clear();
    }

    if (Config::Build::IS_DEBUG_BUILD) {
        _axisGizmo->clear();
    }
}

void RenderingComponent::postLoad() {
    for (U32 i = 0; i < to_const_uint(RenderStage::COUNT); ++i) {
        RenderPackage& pkg = _renderData[to_uint(static_cast<RenderStage>(i))];
        _parentSGN.getNode()->initialiseDrawCommands(_parentSGN, static_cast<RenderStage>(i), pkg._drawCommands);
    }
}

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(RenderStage renderStage) {
    if (_parentSGN.getNode()->getDrawState(renderStage)) {
        const Material_ptr& mat = getMaterialInstance();
        if (mat) {
            if (!mat->canDraw(renderStage)) {
                return false;
            }
        }
        return true;
    }

    return false;
}

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

    _parentSGN.forEachChild([](const SceneGraphNode& child) {
        RenderingComponent* const renderable = child.get<RenderingComponent>();
        if (renderable) {
            renderable->rebuildMaterial();
        }
    });
}

void RenderingComponent::registerTextureDependency(const TextureData& additionalTexture) {
    _textureDependencies.addTexture(additionalTexture);
}

void RenderingComponent::removeTextureDependency(const TextureData& additionalTexture) {
    _textureDependencies.removeTexture(additionalTexture);
}

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

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

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

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

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

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

        _parentSGN.forEachChild([state](const SceneGraphNode& child) {
            RenderingComponent* const renderable = child.get<RenderingComponent>();
            if (renderable) {
                renderable->renderGeometry(state);
            }
        });
    }
}

void RenderingComponent::renderWireframe(const bool state) {
    if (_renderWireframe != state) {
        _renderWireframe = state;
    
        _parentSGN.forEachChild([state](const SceneGraphNode& child) {
            RenderingComponent* const renderable = child.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);
        }

        _parentSGN.forEachChild([state](const SceneGraphNode& child) {
            RenderingComponent* const renderable = child.get<RenderingComponent>();
            if (renderable) {
                renderable->renderBoundingBox(state);
            }
        });
    }
}

void RenderingComponent::renderBoundingSphere(const bool state) {
    if (_renderBoundingSphere != state) {
        _renderBoundingSphere = state;
        if (!state) {
            _boundingSpherePrimitive->paused(true);
        }

        _parentSGN.forEachChild([state](const SceneGraphNode& child) {
            RenderingComponent* const renderable = child.get<RenderingComponent>();
            if (renderable) {
                renderable->renderBoundingSphere(state);
            }
        });
    }
}

void RenderingComponent::renderSkeleton(const bool state) {
    if (_renderSkeleton != state) {
        _renderSkeleton = state;
        if (!state && _skeletonPrimitive) {
            _skeletonPrimitive->paused(true);
        }

        _parentSGN.forEachChild([state](const SceneGraphNode& child) {
            RenderingComponent* const renderable = child.get<RenderingComponent>();
            if (renderable) {
                renderable->renderSkeleton(state);
            }
        });
    }
}

void RenderingComponent::castsShadows(const bool state) {
    if (_castsShadows != state) {
        _castsShadows = state;

        _parentSGN.forEachChild([state](const SceneGraphNode& child) {
            RenderingComponent* const renderable = child.get<RenderingComponent>();
            if (renderable) {
                renderable->castsShadows(state);
            }
        });
    }
}

void RenderingComponent::receivesShadows(const bool state) {
    if (_receiveShadows != state) {
        _receiveShadows = state;
    
        _parentSGN.forEachChild([state](const SceneGraphNode& child) {
            RenderingComponent* const renderable = child.get<RenderingComponent>();
            if (renderable) {
                renderable->receivesShadows(state);
            }
        });
    }
}

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, F32& reflectionIndex, F32& refractionIndex) 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) {
        reflectionIndex = to_float(mat->defaultReflectionTextureIndex());
        refractionIndex = to_float(mat->defaultRefractionTextureIndex());
    } else {
        reflectionIndex = refractionIndex = 0.0f;
    }
}

/// Called after the current node was rendered
void RenderingComponent::postRender(const SceneRenderState& sceneRenderState, RenderStage renderStage, RenderSubPassCmds& subPassesInOut) {
    
    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);
        }
    }

    RenderSubPassCmd& subPassInOut = subPassesInOut.back();
    subPassInOut._commands.push_back(_boundingBoxPrimitive[0]->toDrawCommand());
    subPassInOut._commands.push_back(_boundingBoxPrimitive[1]->toDrawCommand());
    subPassInOut._commands.push_back(_boundingSpherePrimitive->toDrawCommand());
    if (_skeletonPrimitive) {
        subPassInOut._commands.push_back(_skeletonPrimitive->toDrawCommand());
    }
    if (Config::Build::IS_DEBUG_BUILD) {
        subPassInOut._commands.push_back(_axisGizmo->toDrawCommand());
     }
}

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

    ShaderBufferList::iterator it;
    for (RenderPackage& pkg : _renderData) {
        ShaderBufferList::iterator itEnd = std::end(pkg._shaderBuffers);
        it = std::find_if(std::begin(pkg._shaderBuffers), itEnd,
            [slot](const 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 (RenderPackage& pkg : _renderData) {
        pkg._shaderBuffers.erase(
            std::remove_if(std::begin(pkg._shaderBuffers), std::end(pkg._shaderBuffers),
                [&slot](const ShaderBufferBinding& binding)
                    -> bool { return binding._slot == slot; }),
            std::end(pkg._shaderBuffers));
    }
}

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

size_t RenderingComponent::getDrawStateHash(RenderStage renderStage) {
    bool shadowStage = renderStage == RenderStage::SHADOW;
    bool depthPass = renderStage == RenderStage::Z_PRE_PASS || shadowStage;
    bool reflectionStage = renderStage == RenderStage::REFLECTION;
    bool refractionStage = renderStage == RenderStage::REFRACTION;

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

    if (!_materialInstance) {
        return 0;
    }

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

void RenderingComponent::updateLoDLevel(const Camera& camera, 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;

    _lodLevel = to_ubyte(_parentSGN.getNode()->getLODcount() - 1);

    // ToDo: Hack for lower LoD rendering in reflection and refraction passes
    if (renderStage != RenderStage::REFLECTION && renderStage != RenderStage::REFRACTION) {
        const vec3<F32>& eyePos = camera.getEye();
        const BoundingSphere& bSphere = _parentSGN.get<BoundsComponent>()->getBoundingSphere();
        F32 cameraDistanceSQ = bSphere.getCenter().distanceSquared(eyePos);

        U8 lodLevelTemp = cameraDistanceSQ > SCENE_NODE_LOD0_SQ
                                           ? cameraDistanceSQ > SCENE_NODE_LOD1_SQ ? 2 : 1
                                           : 0;

        _lodLevel = std::min(_lodLevel, std::max(lodLevelTemp, to_ubyte(0)));
    }
}

RenderPackage&
RenderingComponent::getDrawPackage(const SceneRenderState& sceneRenderState, RenderStage renderStage) {
    RenderPackage& pkg = _renderData[to_uint(renderStage)];
    pkg.isRenderable(false);
    if (canDraw(renderStage) && _parentSGN.prepareDraw(sceneRenderState, renderStage))
    {
        for (GenericDrawCommand& cmd : pkg._drawCommands) {
            cmd.renderMask(renderMask());
            cmd.stateHash(getDrawStateHash(renderStage));
            cmd.shaderProgram(getDrawShader(renderStage));
        }

        _parentSGN.getNode()->updateDrawCommands(_parentSGN, renderStage, sceneRenderState, pkg._drawCommands);

        updateLoDLevel(*Camera::activeCamera(), renderStage);

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

    return pkg;
}

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 vec2<F32>& zPlanes,
                                          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);

    RenderTargetID reflectRTID(RenderTargetUsage::REFLECTION, reflectionIndex);

    if (_reflectionCallback) {
        _reflectionCallback(_parentSGN, renderState, reflectRTID, reflectionIndex);
    } else {
        GFX_DEVICE.generateCubeMap(GFX_DEVICE.renderTarget(reflectRTID),
                                   0,
                                   camPos,
                                   vec2<F32>(zPlanes.x, zPlanes.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 vec2<F32>& zPlanes,
                                          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,
                        RenderTargetID(RenderTargetUsage::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](const EnvironmentProbe_ptr& a, const EnvironmentProbe_ptr& 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
800 Diff Diff IonutCava picture IonutCava Fri 25 Nov, 2016 17:04:02 +0000

[IonutCava]
- More profile-guided optimizations
- Added GLSL normal map blending methods from: http://blog.selfshadow.com/sandbox/normals.html
- Added more profile timers

794 Diff Diff IonutCava picture IonutCava Tue 22 Nov, 2016 16:44:26 +0000

[IonutCava]
- Change SDL_GL_Context management from a pool-based system to a thread_local variable type System
- Reworked SceneGraphNode child access for safer and faster iteration.
— Added a forEachChild with multiple overloads to apply a lambda expression over every child of the target SGN
- Slight optimization to Text rendering by batching all labels due for rendering and submitting them at all at once

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

783 Diff Diff IonutCava picture IonutCava Fri 14 Oct, 2016 15:50:34 +0000

[IonutCava]
- More cleanup of the Frustum class
- Change random number generation system to use the C++11 <random> features. (default engine set to Mersenne Twister and using a uniform distribution as default)

778 Diff Diff IonutCava picture IonutCava Mon 10 Oct, 2016 15:18:32 +0000

[IonutCava]
- Rendering abstraction cleanup

777 Diff Diff IonutCava picture IonutCava Fri 07 Oct, 2016 16:14:48 +0000

[IonutCava]
- Continue to implement CommandBuffer / RenderPass / RenderSubPass system.
— Rendering artefacts are still present.

776 Diff Diff 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)

773 Diff Diff IonutCava picture IonutCava Tue 04 Oct, 2016 15:53:18 +0000

[IonutCava]
- Split GenericDrawCommand gathering system into Init/Update to facilitate future threading support
- Fix drawCount() == 0 case in submitRenderCommand
- Make _cameraPool (more) threadsafe

771 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