/
renderDeferredMgr.cpp
1150 lines (944 loc) · 40.2 KB
/
renderDeferredMgr.cpp
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "renderInstance/renderDeferredMgr.h"
#include "gfx/gfxTransformSaver.h"
#include "materials/sceneData.h"
#include "materials/materialManager.h"
#include "materials/materialFeatureTypes.h"
#include "core/util/safeDelete.h"
#include "shaderGen/featureMgr.h"
#include "shaderGen/HLSL/depthHLSL.h"
#include "shaderGen/GLSL/depthGLSL.h"
#include "shaderGen/conditionerFeature.h"
#include "shaderGen/shaderGenVars.h"
#include "scene/sceneRenderState.h"
#include "gfx/gfxStringEnumTranslate.h"
#include "gfx/gfxDebugEvent.h"
#include "gfx/gfxCardProfile.h"
#include "materials/customMaterialDefinition.h"
#include "lighting/advanced/advancedLightManager.h"
#include "lighting/advanced/advancedLightBinManager.h"
#include "terrain/terrCell.h"
#include "renderInstance/renderTerrainMgr.h"
#include "terrain/terrCellMaterial.h"
#include "math/mathUtils.h"
#include "math/util/matrixSet.h"
#include "gfx/gfxTextureManager.h"
#include "gfx/primBuilder.h"
#include "gfx/gfxDrawUtil.h"
#include "materials/shaderData.h"
#include "gfx/sim/cubemapData.h"
const MatInstanceHookType DeferredMatInstanceHook::Type( "Deferred" );
const String RenderDeferredMgr::BufferName("deferred");
const RenderInstType RenderDeferredMgr::RIT_Deferred("Deferred");
const String RenderDeferredMgr::ColorBufferName("color");
const String RenderDeferredMgr::MatInfoBufferName("matinfo");
IMPLEMENT_CONOBJECT(RenderDeferredMgr);
ConsoleDocClass( RenderDeferredMgr,
"@brief The render bin which performs a z+normals deferred used in Advanced Lighting.\n\n"
"This render bin is used in Advanced Lighting to gather all opaque mesh render instances "
"and render them to the g-buffer for use in lighting the scene and doing effects.\n\n"
"PostEffect and other shaders can access the output of this bin by using the #deferred "
"texture target name. See the edge anti-aliasing post effect for an example.\n\n"
"@see game/core/scripts/client/postFx/edgeAA.cs\n"
"@ingroup RenderBin\n" );
RenderDeferredMgr::RenderSignal& RenderDeferredMgr::getRenderSignal()
{
static RenderSignal theSignal;
return theSignal;
}
RenderDeferredMgr::RenderDeferredMgr( bool gatherDepth,
GFXFormat format )
: Parent( RIT_Deferred,
0.01f,
0.01f,
format,
Point2I( Parent::DefaultTargetSize, Parent::DefaultTargetSize),
gatherDepth ? Parent::DefaultTargetChainLength : 0 ),
mDeferredMatInstance( NULL )
{
notifyType( RenderPassManager::RIT_Decal );
notifyType( RenderPassManager::RIT_DecalRoad );
notifyType( RenderPassManager::RIT_Mesh );
notifyType( RenderPassManager::RIT_Terrain );
notifyType( RenderPassManager::RIT_Object );
// We want a full-resolution buffer
mTargetSizeType = RenderTexTargetBinManager::WindowSize;
if(getTargetChainLength() > 0)
GFXShader::addGlobalMacro( "TORQUE_LINEAR_DEPTH" );
mNamedTarget.registerWithName( BufferName );
mColorTarget.registerWithName( ColorBufferName );
mMatInfoTarget.registerWithName( MatInfoBufferName );
mClearGBufferShader = NULL;
_registerFeatures();
}
RenderDeferredMgr::~RenderDeferredMgr()
{
GFXShader::removeGlobalMacro( "TORQUE_LINEAR_DEPTH" );
mColorTarget.release();
mMatInfoTarget.release();
_unregisterFeatures();
SAFE_DELETE( mDeferredMatInstance );
}
void RenderDeferredMgr::_registerFeatures()
{
ConditionerFeature *cond = new LinearEyeDepthConditioner( getTargetFormat() );
FEATUREMGR->registerFeature( MFT_DeferredConditioner, cond );
mNamedTarget.setConditioner( cond );
}
void RenderDeferredMgr::_unregisterFeatures()
{
mNamedTarget.setConditioner( NULL );
FEATUREMGR->unregisterFeature(MFT_DeferredConditioner);
}
bool RenderDeferredMgr::setTargetSize(const Point2I &newTargetSize)
{
bool ret = Parent::setTargetSize( newTargetSize );
mNamedTarget.setViewport( GFX->getViewport() );
mColorTarget.setViewport( GFX->getViewport() );
mMatInfoTarget.setViewport( GFX->getViewport() );
return ret;
}
bool RenderDeferredMgr::_updateTargets()
{
PROFILE_SCOPE(RenderDeferredMgr_updateTargets);
bool ret = Parent::_updateTargets();
// check for an output conditioner, and update it's format
ConditionerFeature *outputConditioner = dynamic_cast<ConditionerFeature *>(FEATUREMGR->getByType(MFT_DeferredConditioner));
if( outputConditioner && outputConditioner->setBufferFormat(mTargetFormat) )
{
// reload materials, the conditioner needs to alter the generated shaders
}
GFXFormat colorFormat = mTargetFormat;
/*
bool independentMrtBitDepth = GFX->getCardProfiler()->queryProfile("independentMrtBitDepth", false);
//If independent bit depth on a MRT is supported than just use 8bit channels for the albedo color.
if(independentMrtBitDepth)
colorFormat = GFXFormatR8G8B8A8;
*/
// andrewmac: Deferred Shading Color Buffer
if (mColorTex.getFormat() != colorFormat || mColorTex.getWidthHeight() != mTargetSize || GFX->recentlyReset())
{
mColorTarget.release();
mColorTex.set(mTargetSize.x, mTargetSize.y, colorFormat,
&GFXDefaultRenderTargetProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__),
1, GFXTextureManager::AA_MATCH_BACKBUFFER);
mColorTarget.setTexture(mColorTex);
for (U32 i = 0; i < mTargetChainLength; i++)
mTargetChain[i]->attachTexture(GFXTextureTarget::Color1, mColorTarget.getTexture());
}
// andrewmac: Deferred Shading Material Info Buffer
if (mMatInfoTex.getFormat() != colorFormat || mMatInfoTex.getWidthHeight() != mTargetSize || GFX->recentlyReset())
{
mMatInfoTarget.release();
mMatInfoTex.set(mTargetSize.x, mTargetSize.y, colorFormat,
&GFXDefaultRenderTargetProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__),
1, GFXTextureManager::AA_MATCH_BACKBUFFER);
mMatInfoTarget.setTexture(mMatInfoTex);
for (U32 i = 0; i < mTargetChainLength; i++)
mTargetChain[i]->attachTexture(GFXTextureTarget::Color2, mMatInfoTarget.getTexture());
}
GFX->finalizeReset();
// Attach the light info buffer as a second render target, if there is
// lightmapped geometry in the scene.
AdvancedLightBinManager *lightBin;
if ( Sim::findObject( "AL_LightBinMgr", lightBin ) &&
lightBin->MRTLightmapsDuringDeferred() &&
lightBin->isProperlyAdded() )
{
// Update the size of the light bin target here. This will call _updateTargets
// on the light bin
ret &= lightBin->setTargetSize( mTargetSize );
if ( ret )
{
// Sanity check
AssertFatal(lightBin->getTargetChainLength() == mTargetChainLength, "Target chain length mismatch");
// Attach light info buffer to Color1 for each target in the chain
for ( U32 i = 0; i < mTargetChainLength; i++ )
{
GFXTexHandle lightInfoTex = lightBin->getTargetTexture(0, i);
mTargetChain[i]->attachTexture(GFXTextureTarget::Color3, lightInfoTex);
}
}
}
_initShaders();
return ret;
}
void RenderDeferredMgr::_createDeferredMaterial()
{
SAFE_DELETE(mDeferredMatInstance);
const GFXVertexFormat *vertexFormat = getGFXVertexFormat<GFXVertexPNTTB>();
MatInstance* deferredMat = static_cast<MatInstance*>(MATMGR->createMatInstance("AL_DefaultDeferredMaterial", vertexFormat));
AssertFatal( deferredMat, "TODO: Handle this better." );
mDeferredMatInstance = new DeferredMatInstance(deferredMat, this);
mDeferredMatInstance->init( MATMGR->getDefaultFeatures(), vertexFormat);
delete deferredMat;
}
void RenderDeferredMgr::setDeferredMaterial( DeferredMatInstance *mat )
{
SAFE_DELETE(mDeferredMatInstance);
mDeferredMatInstance = mat;
}
void RenderDeferredMgr::addElement( RenderInst *inst )
{
PROFILE_SCOPE( RenderDeferredMgr_addElement )
// Skip out if this bin is disabled.
if ( gClientSceneGraph->getCurrentRenderState() &&
gClientSceneGraph->getCurrentRenderState()->disableAdvancedLightingBins() )
return;
// First what type of render instance is it?
const bool isDecalMeshInst = ((inst->type == RenderPassManager::RIT_Decal)||(inst->type == RenderPassManager::RIT_DecalRoad));
const bool isMeshInst = inst->type == RenderPassManager::RIT_Mesh;
const bool isTerrainInst = inst->type == RenderPassManager::RIT_Terrain;
// Get the material if its a mesh.
BaseMatInstance* matInst = NULL;
if ( isMeshInst || isDecalMeshInst )
matInst = static_cast<MeshRenderInst*>(inst)->matInst;
if (matInst)
{
// Skip decals if they don't have normal maps.
if (isDecalMeshInst && !matInst->hasNormalMap())
return;
// If its a custom material and it refracts... skip it.
if (matInst->isCustomMaterial() &&
static_cast<CustomMaterial*>(matInst->getMaterial())->mRefract)
return;
// Make sure we got a deferred material.
matInst = getDeferredMaterial(matInst);
if (!matInst || !matInst->isValid())
return;
}
// We're gonna add it to the bin... get the right element list.
Vector< MainSortElem > *elementList;
if ( isMeshInst || isDecalMeshInst )
elementList = &mElementList;
else if ( isTerrainInst )
elementList = &mTerrainElementList;
else
elementList = &mObjectElementList;
elementList->increment();
MainSortElem &elem = elementList->last();
elem.inst = inst;
// Store the original key... we might need it.
U32 originalKey = elem.key;
// Sort front-to-back first to get the most fillrate savings.
const F32 invSortDistSq = F32_MAX - inst->sortDistSq;
elem.key = *((U32*)&invSortDistSq);
// Next sort by pre-pass material if its a mesh... use the original sort key.
if (isMeshInst && matInst)
elem.key2 = matInst->getStateHint();
else
elem.key2 = originalKey;
}
void RenderDeferredMgr::sort()
{
PROFILE_SCOPE( RenderDeferredMgr_sort );
Parent::sort();
dQsort( mTerrainElementList.address(), mTerrainElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
dQsort( mObjectElementList.address(), mObjectElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
}
void RenderDeferredMgr::clear()
{
Parent::clear();
mTerrainElementList.clear();
mObjectElementList.clear();
}
void RenderDeferredMgr::render( SceneRenderState *state )
{
PROFILE_SCOPE(RenderDeferredMgr_render);
// Take a look at the SceneRenderState and see if we should skip drawing the pre-pass
if ( state->disableAdvancedLightingBins() )
return;
// NOTE: We don't early out here when the element list is
// zero because we need the deferred to be cleared.
// Automagically save & restore our viewport and transforms.
GFXTransformSaver saver;
GFXDEBUGEVENT_SCOPE( RenderDeferredMgr_Render, ColorI::RED );
// Tell the superclass we're about to render
const bool isRenderingToTarget = _onPreRender(state);
// Clear all z-buffer, and g-buffer.
clearBuffers();
// Restore transforms
MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
matrixSet.restoreSceneViewProjection();
const MatrixF worldViewXfm = GFX->getWorldMatrix();
// Setup the default deferred material for object instances.
if ( !mDeferredMatInstance )
_createDeferredMaterial();
if ( mDeferredMatInstance )
{
matrixSet.setWorld(MatrixF::Identity);
mDeferredMatInstance->setTransforms(matrixSet, state);
}
// Signal start of pre-pass
getRenderSignal().trigger( state, this, true );
// First do a loop and render all the terrain... these are
// usually the big blockers in a scene and will save us fillrate
// on the smaller meshes and objects.
// The terrain doesn't need any scene graph data
// in the the deferred... so just clear it.
SceneData sgData;
sgData.init( state, SceneData::DeferredBin );
Vector< MainSortElem >::const_iterator itr = mTerrainElementList.begin();
for ( ; itr != mTerrainElementList.end(); itr++ )
{
TerrainRenderInst *ri = static_cast<TerrainRenderInst*>( itr->inst );
TerrainCellMaterial *mat = ri->cellMat->getDeferredMat();
GFX->setPrimitiveBuffer( ri->primBuff );
GFX->setVertexBuffer( ri->vertBuff );
mat->setTransformAndEye( *ri->objectToWorldXfm,
worldViewXfm,
GFX->getProjectionMatrix(),
state->getFarPlane() );
while ( mat->setupPass( state, sgData ) )
GFX->drawPrimitive( ri->prim );
}
// init loop data
GFXTextureObject *lastLM = NULL;
GFXCubemap *lastCubemap = NULL;
GFXTextureObject *lastReflectTex = NULL;
GFXTextureObject *lastAccuTex = NULL;
// Next render all the meshes.
itr = mElementList.begin();
for ( ; itr != mElementList.end(); )
{
MeshRenderInst *ri = static_cast<MeshRenderInst*>( itr->inst );
// Get the deferred material.
BaseMatInstance *mat = getDeferredMaterial( ri->matInst );
// Set up SG data proper like and flag it
// as a pre-pass render
setupSGData( ri, sgData );
Vector< MainSortElem >::const_iterator meshItr, endOfBatchItr = itr;
while ( mat->setupPass( state, sgData ) )
{
meshItr = itr;
for ( ; meshItr != mElementList.end(); meshItr++ )
{
MeshRenderInst *passRI = static_cast<MeshRenderInst*>( meshItr->inst );
// Check to see if we need to break this batch.
//
// NOTE: We're comparing the non-deferred materials
// here so we don't incur the cost of looking up the
// deferred hook on each inst.
//
if ( newPassNeeded( ri, passRI ) )
break;
// Set up SG data for this instance.
setupSGData( passRI, sgData );
mat->setSceneInfo(state, sgData);
matrixSet.setWorld(*passRI->objectToWorld);
matrixSet.setView(*passRI->worldToCamera);
matrixSet.setProjection(*passRI->projection);
mat->setTransforms(matrixSet, state);
// Setup HW skinning transforms if applicable
if (mat->usesHardwareSkinning())
{
mat->setNodeTransforms(passRI->mNodeTransforms, passRI->mNodeTransformCount);
}
// If we're instanced then don't render yet.
if ( mat->isInstanced() )
{
// Let the material increment the instance buffer, but
// break the batch if it runs out of room for more.
if ( !mat->stepInstance() )
{
meshItr++;
break;
}
continue;
}
bool dirty = false;
// set the lightmaps if different
if( passRI->lightmap && passRI->lightmap != lastLM )
{
sgData.lightmap = passRI->lightmap;
lastLM = passRI->lightmap;
dirty = true;
}
// set the cubemap if different.
if ( passRI->cubemap != lastCubemap )
{
sgData.cubemap = passRI->cubemap;
lastCubemap = passRI->cubemap;
dirty = true;
}
if ( passRI->reflectTex != lastReflectTex )
{
sgData.reflectTex = passRI->reflectTex;
lastReflectTex = passRI->reflectTex;
dirty = true;
}
// Update accumulation texture if it changed.
// Note: accumulation texture can be NULL, and must be updated.
if (passRI->accuTex != lastAccuTex)
{
sgData.accuTex = passRI->accuTex;
lastAccuTex = passRI->accuTex;
dirty = true;
}
if ( dirty )
mat->setTextureStages( state, sgData );
// Setup the vertex and index buffers.
mat->setBuffers( passRI->vertBuff, passRI->primBuff );
// Render this sucker.
if ( passRI->prim )
GFX->drawPrimitive( *passRI->prim );
else
GFX->drawPrimitive( passRI->primBuffIndex );
}
// Draw the instanced batch.
if ( mat->isInstanced() )
{
// Sets the buffers including the instancing stream.
mat->setBuffers( ri->vertBuff, ri->primBuff );
if ( ri->prim )
GFX->drawPrimitive( *ri->prim );
else
GFX->drawPrimitive( ri->primBuffIndex );
}
endOfBatchItr = meshItr;
} // while( mat->setupPass(state, sgData) )
// Force the increment if none happened, otherwise go to end of batch.
itr = ( itr == endOfBatchItr ) ? itr + 1 : endOfBatchItr;
}
// The final loop is for object render instances.
itr = mObjectElementList.begin();
for ( ; itr != mObjectElementList.end(); itr++ )
{
ObjectRenderInst *ri = static_cast<ObjectRenderInst*>( itr->inst );
if ( ri->renderDelegate )
ri->renderDelegate( ri, state, mDeferredMatInstance );
}
// Signal end of pre-pass
getRenderSignal().trigger( state, this, false );
if(isRenderingToTarget)
_onPostRender();
}
const GFXStateBlockDesc & RenderDeferredMgr::getOpaqueStenciWriteDesc( bool lightmappedGeometry /*= true*/ )
{
static bool sbInit = false;
static GFXStateBlockDesc sOpaqueStaticLitStencilWriteDesc;
static GFXStateBlockDesc sOpaqueDynamicLitStencilWriteDesc;
if(!sbInit)
{
sbInit = true;
// Build the static opaque stencil write/test state block descriptions
sOpaqueStaticLitStencilWriteDesc.stencilDefined = true;
sOpaqueStaticLitStencilWriteDesc.stencilEnable = true;
sOpaqueStaticLitStencilWriteDesc.stencilWriteMask = 0x03;
sOpaqueStaticLitStencilWriteDesc.stencilMask = 0x03;
sOpaqueStaticLitStencilWriteDesc.stencilRef = RenderDeferredMgr::OpaqueStaticLitMask;
sOpaqueStaticLitStencilWriteDesc.stencilPassOp = GFXStencilOpReplace;
sOpaqueStaticLitStencilWriteDesc.stencilFailOp = GFXStencilOpKeep;
sOpaqueStaticLitStencilWriteDesc.stencilZFailOp = GFXStencilOpKeep;
sOpaqueStaticLitStencilWriteDesc.stencilFunc = GFXCmpAlways;
// Same only dynamic
sOpaqueDynamicLitStencilWriteDesc = sOpaqueStaticLitStencilWriteDesc;
sOpaqueDynamicLitStencilWriteDesc.stencilRef = RenderDeferredMgr::OpaqueDynamicLitMask;
}
return (lightmappedGeometry ? sOpaqueStaticLitStencilWriteDesc : sOpaqueDynamicLitStencilWriteDesc);
}
const GFXStateBlockDesc & RenderDeferredMgr::getOpaqueStencilTestDesc()
{
static bool sbInit = false;
static GFXStateBlockDesc sOpaqueStencilTestDesc;
if(!sbInit)
{
// Build opaque test
sbInit = true;
sOpaqueStencilTestDesc.stencilDefined = true;
sOpaqueStencilTestDesc.stencilEnable = true;
sOpaqueStencilTestDesc.stencilWriteMask = 0xFE;
sOpaqueStencilTestDesc.stencilMask = 0x03;
sOpaqueStencilTestDesc.stencilRef = 0;
sOpaqueStencilTestDesc.stencilPassOp = GFXStencilOpKeep;
sOpaqueStencilTestDesc.stencilFailOp = GFXStencilOpKeep;
sOpaqueStencilTestDesc.stencilZFailOp = GFXStencilOpKeep;
sOpaqueStencilTestDesc.stencilFunc = GFXCmpLess;
}
return sOpaqueStencilTestDesc;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
ProcessedDeferredMaterial::ProcessedDeferredMaterial( Material& mat, const RenderDeferredMgr *deferredMgr )
: Parent(mat), mDeferredMgr(deferredMgr)
{
}
void ProcessedDeferredMaterial::_determineFeatures( U32 stageNum,
MaterialFeatureData &fd,
const FeatureSet &features )
{
Parent::_determineFeatures( stageNum, fd, features );
// Find this for use down below...
bool bEnableMRTLightmap = false;
AdvancedLightBinManager *lightBin;
if ( Sim::findObject( "AL_LightBinMgr", lightBin ) )
bEnableMRTLightmap = lightBin->MRTLightmapsDuringDeferred();
// If this material has a lightmap or tonemap (texture or baked vertex color),
// it must be static. Otherwise it is dynamic.
mIsLightmappedGeometry = ( fd.features.hasFeature( MFT_ToneMap ) ||
fd.features.hasFeature( MFT_LightMap ) ||
fd.features.hasFeature( MFT_VertLit ) ||
( bEnableMRTLightmap && (fd.features.hasFeature( MFT_IsTranslucent ) ||
fd.features.hasFeature( MFT_ForwardShading ) ||
fd.features.hasFeature( MFT_IsTranslucentZWrite) ) ) );
// Integrate proper opaque stencil write state
mUserDefined.addDesc( mDeferredMgr->getOpaqueStenciWriteDesc( mIsLightmappedGeometry ) );
FeatureSet newFeatures;
// These are always on for deferred.
newFeatures.addFeature( MFT_EyeSpaceDepthOut );
newFeatures.addFeature( MFT_DeferredConditioner );
#ifndef TORQUE_DEDICATED
//tag all materials running through deferred as deferred
newFeatures.addFeature(MFT_isDeferred);
// Deferred Shading : Diffuse
if (mStages[stageNum].getTex( MFT_DiffuseMap ))
{
newFeatures.addFeature(MFT_DiffuseMap);
}
newFeatures.addFeature( MFT_DiffuseColor );
// Deferred Shading : Specular
if( mStages[stageNum].getTex( MFT_SpecularMap ) )
{
newFeatures.addFeature( MFT_DeferredSpecMap );
}
else if ( mMaterial->mPixelSpecular[stageNum] )
{
newFeatures.addFeature( MFT_DeferredSpecVars );
}
else
newFeatures.addFeature(MFT_DeferredEmptySpec);
// Deferred Shading : Material Info Flags
newFeatures.addFeature( MFT_DeferredMatInfoFlags );
for ( U32 i=0; i < fd.features.getCount(); i++ )
{
const FeatureType &type = fd.features.getAt( i );
// Turn on the diffuse texture only if we
// have alpha test.
if ( type == MFT_AlphaTest )
{
newFeatures.addFeature( MFT_AlphaTest );
newFeatures.addFeature( MFT_DiffuseMap );
}
else if ( type == MFT_IsTranslucentZWrite )
{
newFeatures.addFeature( MFT_IsTranslucentZWrite );
newFeatures.addFeature( MFT_DiffuseMap );
}
// Always allow these.
else if ( type == MFT_IsDXTnm ||
type == MFT_TexAnim ||
type == MFT_NormalMap ||
type == MFT_DetailNormalMap ||
type == MFT_AlphaTest ||
type == MFT_Parallax ||
type == MFT_InterlacedDeferred ||
type == MFT_Visibility ||
type == MFT_UseInstancing ||
type == MFT_DiffuseVertColor ||
type == MFT_DetailMap ||
type == MFT_DiffuseMapAtlas)
newFeatures.addFeature( type );
// Add any transform features.
else if ( type.getGroup() == MFG_PreTransform ||
type.getGroup() == MFG_Transform ||
type.getGroup() == MFG_PostTransform )
newFeatures.addFeature( type );
}
if (mMaterial->mAccuEnabled[stageNum])
{
newFeatures.addFeature(MFT_AccuMap);
mHasAccumulation = true;
}
// we need both diffuse and normal maps + sm3 to have an accu map
if (newFeatures[MFT_AccuMap] &&
(!newFeatures[MFT_DiffuseMap] ||
!newFeatures[MFT_NormalMap] ||
GFX->getPixelShaderVersion() < 3.0f)) {
AssertWarn(false, "SAHARA: Using an Accu Map requires SM 3.0 and a normal map.");
newFeatures.removeFeature(MFT_AccuMap);
mHasAccumulation = false;
}
// if we still have the AccuMap feature, we add all accu constant features
if (newFeatures[MFT_AccuMap]) {
// add the dependencies of the accu map
newFeatures.addFeature(MFT_AccuScale);
newFeatures.addFeature(MFT_AccuDirection);
newFeatures.addFeature(MFT_AccuStrength);
newFeatures.addFeature(MFT_AccuCoverage);
newFeatures.addFeature(MFT_AccuSpecular);
// now remove some features that are not compatible with this
newFeatures.removeFeature(MFT_UseInstancing);
}
// If there is lightmapped geometry support, add the MRT light buffer features
if(bEnableMRTLightmap)
{
// If this material has a lightmap, pass it through, and flag it to
// send it's output to RenderTarget3
if( fd.features.hasFeature( MFT_ToneMap ) )
{
newFeatures.addFeature( MFT_ToneMap );
newFeatures.addFeature( MFT_LightbufferMRT );
}
else if( fd.features.hasFeature( MFT_LightMap ) )
{
newFeatures.addFeature( MFT_LightMap );
newFeatures.addFeature( MFT_LightbufferMRT );
}
else if( fd.features.hasFeature( MFT_VertLit ) )
{
// Flag un-tone-map if necesasary
if( fd.features.hasFeature( MFT_DiffuseMap ) )
newFeatures.addFeature( MFT_VertLitTone );
newFeatures.addFeature( MFT_VertLit );
newFeatures.addFeature( MFT_LightbufferMRT );
}
else
{
// If this object isn't lightmapped, add a zero-output feature to it
newFeatures.addFeature( MFT_RenderTarget3_Zero );
}
}
// cubemaps only available on stage 0 for now - bramage
if ( stageNum < 1 &&
( ( mMaterial->mCubemapData && mMaterial->mCubemapData->mCubemap ) ||
mMaterial->mDynamicCubemap ) )
newFeatures.addFeature( MFT_CubeMap );
#endif
// Set the new features.
fd.features = newFeatures;
}
U32 ProcessedDeferredMaterial::getNumStages()
{
// Loops through all stages to determine how many
// stages we actually use.
//
// The first stage is always active else we shouldn't be
// creating the material to begin with.
U32 numStages = 1;
U32 i;
for( i=1; i<Material::MAX_STAGES; i++ )
{
// Assume stage is inactive
bool stageActive = false;
// Cubemaps only on first stage
if( i == 0 )
{
// If we have a cubemap the stage is active
if( mMaterial->mCubemapData || mMaterial->mDynamicCubemap )
{
numStages++;
continue;
}
}
// If we have a texture for the a feature the
// stage is active.
if ( mStages[i].hasValidTex() )
stageActive = true;
// If this stage has specular lighting, it's active
if ( mMaterial->mPixelSpecular[i] )
stageActive = true;
// If this stage has diffuse color, it's active
if ( mMaterial->mDiffuse[i].alpha > 0 &&
mMaterial->mDiffuse[i] != ColorF::WHITE )
stageActive = true;
// If we have a Material that is vertex lit
// then it may not have a texture
if( mMaterial->mVertLit[i] )
stageActive = true;
// Increment the number of active stages
numStages += stageActive;
}
return numStages;
}
void ProcessedDeferredMaterial::addStateBlockDesc(const GFXStateBlockDesc& desc)
{
GFXStateBlockDesc deferredStateBlock = desc;
// Adjust color writes if this is a pure z-fill pass
const bool pixelOutEnabled = mDeferredMgr->getTargetChainLength() > 0;
if ( !pixelOutEnabled )
{
deferredStateBlock.colorWriteDefined = true;
deferredStateBlock.colorWriteRed = pixelOutEnabled;
deferredStateBlock.colorWriteGreen = pixelOutEnabled;
deferredStateBlock.colorWriteBlue = pixelOutEnabled;
deferredStateBlock.colorWriteAlpha = pixelOutEnabled;
}
// Never allow the alpha test state when rendering
// the deferred as we use the alpha channel for the
// depth information... MFT_AlphaTest will handle it.
deferredStateBlock.alphaDefined = true;
deferredStateBlock.alphaTestEnable = false;
// If we're translucent then we're doing deferred blending
// which never writes to the depth channels.
const bool isTranslucent = getMaterial()->isTranslucent();
if ( isTranslucent )
{
deferredStateBlock.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
deferredStateBlock.setColorWrites(false, false, false, true);
}
// Enable z reads, but only enable zwrites if we're not translucent.
deferredStateBlock.setZReadWrite( true, isTranslucent ? false : true );
// Pass to parent
Parent::addStateBlockDesc(deferredStateBlock);
}
DeferredMatInstance::DeferredMatInstance(MatInstance* root, const RenderDeferredMgr *deferredMgr)
: Parent(*root->getMaterial()), mDeferredMgr(deferredMgr)
{
mFeatureList = root->getRequestedFeatures();
mVertexFormat = root->getVertexFormat();
mUserObject = root->getUserObject();
}
DeferredMatInstance::~DeferredMatInstance()
{
}
ProcessedMaterial* DeferredMatInstance::getShaderMaterial()
{
return new ProcessedDeferredMaterial(*mMaterial, mDeferredMgr);
}
bool DeferredMatInstance::init( const FeatureSet &features,
const GFXVertexFormat *vertexFormat )
{
bool vaild = Parent::init(features, vertexFormat);
if (mMaterial && mMaterial->mDiffuseMapFilename[0].isNotEmpty() && mMaterial->mDiffuseMapFilename[0].substr(0, 1).equal("#"))
{
String texTargetBufferName = mMaterial->mDiffuseMapFilename[0].substr(1, mMaterial->mDiffuseMapFilename[0].length() - 1);
NamedTexTarget *texTarget = NamedTexTarget::find(texTargetBufferName);
RenderPassData* rpd = getPass(0);
if (rpd)
{
rpd->mTexSlot[0].texTarget = texTarget;
rpd->mTexType[0] = Material::TexTarget;
rpd->mSamplerNames[0] = "diffuseMap";
}
}
return vaild;
}
DeferredMatInstanceHook::DeferredMatInstanceHook( MatInstance *baseMatInst,
const RenderDeferredMgr *deferredMgr )
: mHookedDeferredMatInst(NULL), mDeferredManager(deferredMgr)
{
// If the material is a custom material then
// hope that using DefaultDeferredMaterial gives
// them a good deferred.
if ( baseMatInst->isCustomMaterial() )
{
MatInstance* dummyInst = static_cast<MatInstance*>( MATMGR->createMatInstance( "AL_DefaultDeferredMaterial", baseMatInst->getVertexFormat() ) );
mHookedDeferredMatInst = new DeferredMatInstance( dummyInst, deferredMgr );
mHookedDeferredMatInst->init( dummyInst->getRequestedFeatures(), baseMatInst->getVertexFormat());
delete dummyInst;
return;
}
// Create the deferred material instance.
mHookedDeferredMatInst = new DeferredMatInstance(baseMatInst, deferredMgr);
mHookedDeferredMatInst->getFeaturesDelegate() = baseMatInst->getFeaturesDelegate();
// Get the features, but remove the instancing feature if the
// original material didn't end up using it.
FeatureSet features = baseMatInst->getRequestedFeatures();
if ( !baseMatInst->isInstanced() )
features.removeFeature( MFT_UseInstancing );
// Initialize the material.
mHookedDeferredMatInst->init(features, baseMatInst->getVertexFormat());
}
DeferredMatInstanceHook::~DeferredMatInstanceHook()
{
SAFE_DELETE(mHookedDeferredMatInst);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void LinearEyeDepthConditioner::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd )
{
// find depth
ShaderFeature *depthFeat = FEATUREMGR->getByType( MFT_EyeSpaceDepthOut );
AssertFatal( depthFeat != NULL, "No eye space depth feature found!" );
Var *depth = (Var*) LangElement::find(depthFeat->getOutputVarName());
AssertFatal( depth, "Something went bad with ShaderGen. The depth should be already generated by the EyeSpaceDepthOut feature." );
MultiLine *meta = new MultiLine;
meta->addStatement( assignOutput( depth ) );
output = meta;
}
Var *LinearEyeDepthConditioner::_conditionOutput( Var *unconditionedOutput, MultiLine *meta )
{
Var *retVar = NULL;
String fracMethodName = (GFX->getAdapterType() == OpenGL) ? "fract" : "frac";
switch(getBufferFormat())
{
case GFXFormatR8G8B8A8:
retVar = new Var;
retVar->setType("float4");
retVar->setName("_ppDepth");
meta->addStatement( new GenOp( " // depth conditioner: packing to rgba\r\n" ) );
meta->addStatement( new GenOp(
avar( " @ = %s(@ * (255.0/256) * float4(1, 255, 255 * 255, 255 * 255 * 255));\r\n", fracMethodName.c_str() ),
new DecOp(retVar), unconditionedOutput ) );
break;
default:
retVar = unconditionedOutput;
meta->addStatement( new GenOp( " // depth conditioner: no conditioning\r\n" ) );
break;
}
AssertFatal( retVar != NULL, avar( "Cannot condition output to buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
return retVar;
}
Var *LinearEyeDepthConditioner::_unconditionInput( Var *conditionedInput, MultiLine *meta )
{
String float4Typename = (GFX->getAdapterType() == OpenGL) ? "vec4" : "float4";
Var *retVar = conditionedInput;
if(getBufferFormat() != GFXFormat_COUNT)
{
retVar = new Var;
retVar->setType(float4Typename.c_str());
retVar->setName("_ppDepth");
meta->addStatement( new GenOp( avar( " @ = %s(0, 0, 1, 1);\r\n", float4Typename.c_str() ), new DecOp(retVar) ) );
switch(getBufferFormat())
{
case GFXFormatR32F:
case GFXFormatR16F:
meta->addStatement( new GenOp( " // depth conditioner: float texture\r\n" ) );
meta->addStatement( new GenOp( " @.w = @.r;\r\n", retVar, conditionedInput ) );
break;
case GFXFormatR8G8B8A8:
meta->addStatement( new GenOp( " // depth conditioner: unpacking from rgba\r\n" ) );
meta->addStatement( new GenOp(
avar( " @.w = dot(@ * (256.0/255), %s(1, 1 / 255, 1 / (255 * 255), 1 / (255 * 255 * 255)));\r\n", float4Typename.c_str() )
, retVar, conditionedInput ) );