forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathW3DScene.cpp
More file actions
1950 lines (1675 loc) · 72.8 KB
/
W3DScene.cpp
File metadata and controls
1950 lines (1675 loc) · 72.8 KB
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
/*
** Command & Conquer Generals(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
// FILE: W3DScene.cpp /////////////////////////////////////////////////////////
//
// Scene manger for display using W3DDispaly. A scene manager can customize
// the rendering process, culling, material passes ...
//
// Author: Colin Day, April 2001
//
///////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES ////////////////////////////////////////////////////////////
#include <stdlib.h>
// USER INCLUDES //////////////////////////////////////////////////////////////
#include "Lib/BaseType.h"
#include "Common/GameUtility.h"
#include "Common/GlobalData.h"
#include "Common/PerfTimer.h"
#include "Common/Player.h"
#include "Common/PlayerList.h"
#include "GameLogic/Object.h"
#include "GameLogic/GameLogic.h"
#include "GameClient/Drawable.h"
#include "GameClient/ParticleSys.h"
#include "GameClient/Color.h"
#include "GameClient/View.h"
#include "W3DDevice/GameClient/HeightMap.h"
#include "W3DDevice/GameClient/W3DScene.h"
#include "W3DDevice/GameClient/W3DDynamicLight.h"
#include "W3DDevice/GameClient/W3DShadow.h"
#include "W3DDevice/GameClient/W3DStatusCircle.h"
#include "W3DDevice/GameClient/W3DCustomScene.h"
#include "W3DDevice/GameClient/W3DShroud.h"
#include "WW3D2/camera.h"
#include "WW3D2/dx8renderer.h"
#include "WW3D2/sortingrenderer.h"
#include "WW3D2/dx8wrapper.h"
#include "WW3D2/light.h"
#include "WW3D2/matpass.h"
#include "WW3D2/shader.h"
#include "WW3D2/dx8caps.h"
#include "WW3D2/colorspace.h"
///////////////////////////////////////////////////////////////////////////////
// DEFINITIONS ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///@todo: Remove these globals since we no longer need W3D to call them for us.
extern void PrepareShadows();
extern void DoTrees(RenderInfoClass & rinfo);
extern void DoShadows(RenderInfoClass & rinfo, Bool stencilPass);
extern void DoParticles(RenderInfoClass & rinfo);
// No texturing, no zbuffer reading/writing, primary gradient, no
// blending, no fogging - mostly for use in solid-colored opaque objects.
#define SC_PLAYER_COLOR ( SHADE_CNST(ShaderClass::PASS_ALWAYS, ShaderClass::DEPTH_WRITE_DISABLE, ShaderClass::COLOR_WRITE_ENABLE, \
ShaderClass::SRCBLEND_ONE, ShaderClass::DSTBLEND_ZERO, ShaderClass::FOG_DISABLE, ShaderClass::GRADIENT_MODULATE, ShaderClass::SECONDARY_GRADIENT_DISABLE, \
ShaderClass::TEXTURING_DISABLE, ShaderClass::ALPHATEST_DISABLE, ShaderClass::CULL_MODE_ENABLE, \
ShaderClass::DETAILCOLOR_DISABLE, ShaderClass::DETAILALPHA_DISABLE) )
static ShaderClass PlayerColorShader(SC_PLAYER_COLOR);
//=============================================================================
// RTS3DScene::RTS3DScene
//=============================================================================
/** */
//=============================================================================
RTS3DScene::RTS3DScene()
{
setName("RTS3DScene");
m_drawTerrainOnly = false;
m_numGlobalLights=0;
Int i=0;
for (; i<LightEnvironmentClass::MAX_LIGHTS; i++)
{
m_globalLight[i]=nullptr;
m_infantryLight[i]=NEW_REF( LightClass, (LightClass::DIRECTIONAL) );
}
m_scratchLight = NEW_REF( LightClass, (LightClass::DIRECTIONAL) );
// REF_PTR_SET(m_globalLight[lightIndex], pLight);
#if ENABLE_CONFIGURABLE_SHROUD
if (TheGlobalData->m_shroudOn)
m_shroudMaterialPass = NEW_REF(W3DShroudMaterialPassClass,());
else
m_shroudMaterialPass = nullptr;
#else
m_shroudMaterialPass = NEW_REF(W3DShroudMaterialPassClass,());
#endif
m_maskMaterialPass = NEW_REF(W3DMaskMaterialPassClass,());
m_customPassMode = SCENE_PASS_DEFAULT;
m_heatVisionMaterialPass = NEW_REF(MaterialPassClass,());
m_heatVisionOnlyPass = NEW_REF(MaterialPassClass,());
VertexMaterialClass *heatVisionMtl = NEW_REF(VertexMaterialClass,());
heatVisionMtl->Set_Lighting(true);
heatVisionMtl->Set_Ambient(0,0,0);
heatVisionMtl->Set_Diffuse(0.02f,0.01f,0.00f);
heatVisionMtl->Set_Emissive(0.5f,0.2f,0.0f);
m_heatVisionMaterialPass->Set_Material(heatVisionMtl);
ShaderClass heatVisionShader=ShaderClass::_PresetAdditiveSolidShader;
heatVisionShader.Set_Depth_Compare(ShaderClass::PASS_EQUAL);
m_heatVisionMaterialPass->Set_Shader(heatVisionShader);
heatVisionMtl->Release_Ref();
heatVisionShader.Set_Depth_Compare(ShaderClass::PASS_LEQUAL);
heatVisionShader.Set_Depth_Mask(ShaderClass::DEPTH_WRITE_DISABLE);
m_heatVisionOnlyPass->Set_Material(heatVisionMtl);
m_heatVisionOnlyPass->Set_Shader(heatVisionShader);
//Allocate memory to hold queue of visible render objects that need to be drawn last
//because they are forced translucent.
m_translucentObjectsCount = 0;
if (TheGlobalData->m_maxVisibleTranslucentObjects > 0)
m_translucentObjectsBuffer = NEW RenderObjClass* [TheGlobalData->m_maxVisibleTranslucentObjects];
else
m_translucentObjectsBuffer = nullptr;
m_numPotentialOccluders=0;
m_numPotentialOccludees=0;
m_numNonOccluderOrOccludee=0;
m_occludedObjectsCount=0;
if (TheGlobalData->m_maxVisibleOccluderObjects > 0)
m_potentialOccluders = NEW RenderObjClass* [TheGlobalData->m_maxVisibleOccluderObjects];
else
m_potentialOccluders = nullptr;
if (TheGlobalData->m_maxVisibleOccludeeObjects > 0)
m_potentialOccludees = NEW RenderObjClass* [TheGlobalData->m_maxVisibleOccludeeObjects];
else
m_potentialOccludees = nullptr;
if (TheGlobalData->m_maxVisibleNonOccluderOrOccludeeObjects > 0)
m_nonOccludersOrOccludees = NEW RenderObjClass* [TheGlobalData->m_maxVisibleNonOccluderOrOccludeeObjects];
else
m_nonOccludersOrOccludees = nullptr;
//Modify the shader to make occlusion transparent
ShaderClass shader = PlayerColorShader;
shader.Set_Src_Blend_Func(ShaderClass::SRCBLEND_SRC_ALPHA);
shader.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);
#ifdef USE_NON_STENCIL_OCCLUSION
for (i=0; i<MAX_PLAYER_COUNT; i++)
{
m_occludedMaterialPass[i]=NEW_REF(MaterialPassClass,());
VertexMaterialClass * vmtl = NEW_REF(VertexMaterialClass,());
vmtl->Set_Lighting(true);
vmtl->Set_Ambient(0,0,0); //we're only using emissive so kill all other lights.
vmtl->Set_Diffuse(0,0,0);
m_occludedMaterialPass[i]->Set_Material(vmtl);
m_occludedMaterialPass[i]->Set_Shader(shader);
vmtl->Release_Ref(); //material pass is holding the pointer so release ref.
}
#else
for (i=0; i<MAX_PLAYER_COUNT; i++)
m_occludedMaterialPass[i]=nullptr;
#endif
}
//=============================================================================
// RTS3DScene::~RTS3DScene
//=============================================================================
/** */
//=============================================================================
RTS3DScene::~RTS3DScene()
{
Int i=0;
for (; i<LightEnvironmentClass::MAX_LIGHTS; i++)
{
REF_PTR_RELEASE(m_globalLight[i]);
REF_PTR_RELEASE(m_infantryLight[i]);
}
REF_PTR_RELEASE(m_scratchLight);
REF_PTR_RELEASE(m_shroudMaterialPass);
REF_PTR_RELEASE(m_maskMaterialPass);
REF_PTR_RELEASE(m_heatVisionMaterialPass);
REF_PTR_RELEASE(m_heatVisionOnlyPass);
delete [] m_translucentObjectsBuffer;
delete [] m_nonOccludersOrOccludees;
delete [] m_potentialOccludees;
delete [] m_potentialOccluders;
for (i=0; i<MAX_PLAYER_COUNT; i++)
{
REF_PTR_RELEASE(m_occludedMaterialPass[i]);
}
}
void RTS3DScene::setGlobalLight(LightClass *pLight, Int lightIndex)
{
if (m_numGlobalLights < (lightIndex+1))
m_numGlobalLights=(lightIndex+1);
REF_PTR_SET(m_globalLight[lightIndex], pLight);
}
/**Find all objects which need to be drawn in a special way because they are occluded by other
objects.
@todo: Need some kind of scene subdivision or find way to use Partition manger to speed up the ray
intersection tests. Maybe truncate the ray to terrain length before using it?
*/
void RTS3DScene::flagOccludedObjects(CameraClass * camera)
{
Vector3 camPosition=camera->Get_Position();
//Find which objects are actually occluded
RenderObjClass **occludee=m_potentialOccludees;
LineSegClass lineseg;
CastResultStruct result;
Bool hit=FALSE;
Vector3 newEndPoint;
result.ComputeContactPoint=false;
RayCollisionTestClass raytest(lineseg,&result,COLL_TYPE_ALL,false,false);
raytest.CollisionType=COLL_TYPE_ALL;
m_occludedObjectsCount=0;
for (Int i=0; i<m_numPotentialOccludees; i++,occludee++)
{
raytest.Ray.Set(camPosition,(*occludee)->Get_Position());
RenderObjClass **occluder=m_potentialOccluders;
//Check this object against all other possible blocking objects
for (Int j=0; j<m_numPotentialOccluders; j++,occluder++)
{
// Do a quick ray-sphere test (Graphics Gems I, p388)
RenderObjClass *robj=*occluder;
const SphereClass *sphere = &robj->Get_Bounding_Sphere();
// make a vector from the ray origin to the sphere center
Vector3 sphere_vector(sphere->Center - raytest.Ray.Get_P0());
// get the dot product between the sphere_vector and the ray vector
Real Alpha = Vector3::Dot_Product(sphere_vector, raytest.Ray.Get_Dir());
Real Beta = sphere->Radius * sphere->Radius - (Vector3::Dot_Product(sphere_vector, sphere_vector) - Alpha * Alpha);
if(Beta < 0.0f)
continue; //no intersection
//Do a more accurate test against object geometry
if (robj->Cast_Ray(raytest))
{
//Found an object closer than last closest object
//Adjust our results and refine search
raytest.CollidedRenderObj = robj;
hit=TRUE;
//reset the result space for next test
result.StartBad = false;
result.Fraction = 1.0f;
break;
}
}
if (hit)
{
//occludee was blocked by something so flag it for custom rendering
DrawableInfo *drawInfo=(DrawableInfo *)(*occludee)->Get_User_Data();
drawInfo->m_flags |= DrawableInfo::ERF_IS_OCCLUDED;
m_potentialOccludees[m_occludedObjectsCount++] = *occludee;
}
}
}
//=============================================================================
// RTS3DScene::castRay
//=============================================================================
/** Does a ray intersection test against objects in our scene.
By default, it only tests objects determined to be visible to the user.
Setting testAll forces it to test all objects in the scene.
CollisionType is used as a mask to ignore certain types of objects.
*/
//=============================================================================
Bool RTS3DScene::castRay(RayCollisionTestClass & raytest, Bool testAll, Int collisionType)
{
// this shouldn't be necessary here, and would be an undesirable performance hit.
// if you ever add or modify code here, it MIGHT become necessary... so do so with caution. (srj)
//#ifdef DIRTY_CONDITION_FLAGS
// StDrawableDirtyStuffLocker lockDirtyStuff;
//#endif
//temporary results for each object tested
CastResultStruct result;
RayCollisionTestClass tempRayTest(raytest.Ray,&result);
Vector3 newEndPoint;
Bool hit=FALSE;
tempRayTest.CollisionType = COLL_TYPE_ALL;
//check if a mesh is translucent before colliding with it. Skips headlights, etc.
tempRayTest.CheckTranslucent = true;
RefRenderObjListIterator it(&RenderList);
// select the first object
it.First();
while (!it.Is_Done())
{
// get the render object
RenderObjClass * robj = it.Peek_Obj();
it.Next();
// only intersect if it was visible or if we must test all
if(robj->Get_Collision_Type() & collisionType && (testAll || robj->Is_Really_Visible()))
{
// Do a quick ray-sphere test (Graphics Gems I, p388)
const SphereClass *sphere = &robj->Get_Bounding_Sphere();
// make a vector from the ray origin to the sphere center
Vector3 sphere_vector(sphere->Center - tempRayTest.Ray.Get_P0());
// get the dot product between the sphere_vector and the ray vector
Real Alpha = Vector3::Dot_Product(sphere_vector, tempRayTest.Ray.Get_Dir());
Real Beta = sphere->Radius * sphere->Radius - (Vector3::Dot_Product(sphere_vector, sphere_vector) - Alpha * Alpha);
if(Beta < 0.0f)
continue; //no intersection
//Do a more accurate test against object geometry
if (robj->Cast_Ray(tempRayTest))
{
//Found an object closer than last closest object
//Adjust our results and refine search
raytest.CollidedRenderObj = robj;
hit=TRUE;
//Refine search by making ray shorter
tempRayTest.Ray.Compute_Point(tempRayTest.Result->Fraction,&newEndPoint);
tempRayTest.Ray.Set(raytest.Ray.Get_P0(),newEndPoint);
//intersection point is at the end of shortened ray, so adjust fraction to 1.0
tempRayTest.Result->Fraction=1.0f;
}
}
}
//Store results of ray intersection test including a clipped ray that ends on object.
raytest.Ray=tempRayTest.Ray;
return hit;
}
//=============================================================================
// RTS3DScene::Visibility_Check
//=============================================================================
/** Custom visibility check method for the RTS3DScene, we can put optimized
* culling methods in here */
//=============================================================================
void RTS3DScene::Visibility_Check(CameraClass * camera)
{
#ifdef DIRTY_CONDITION_FLAGS
StDrawableDirtyStuffLocker lockDirtyStuff;
#endif
RefRenderObjListIterator it(&RenderList);
DrawableInfo *drawInfo = nullptr;
Drawable *draw = nullptr;
RenderObjClass * robj;
m_numPotentialOccluders=0;
m_numPotentialOccludees=0;
m_translucentObjectsCount=0;
m_numNonOccluderOrOccludee=0;
Int currentFrame = TheGameLogic ? TheGameLogic->getFrame() : 0;
if (currentFrame <= TheGlobalData->m_defaultOcclusionDelay)
currentFrame = TheGlobalData->m_defaultOcclusionDelay+1; //make sure occlusion is enabled when game starts (frame 0).
if (ShaderClass::Is_Backface_Culling_Inverted())
{
//we are rendering reflections
///@todo: Have better flag to detect reflection pass
// Loop over all top-level RenderObjects in this scene. If the bounding sphere is not in front
// of all the frustum planes, it is invisible.
for (it.First(); !it.Is_Done(); it.Next()) {
robj = it.Peek_Obj();
draw=nullptr;
drawInfo = (DrawableInfo *)robj->Get_User_Data();
if (drawInfo)
draw=drawInfo->m_drawable;
if( draw )
{
if (robj->Is_Force_Visible()) {
robj->Set_Visible(true);
} else {
robj->Set_Visible(draw->getDrawsInMirror() && !camera->Cull_Sphere(robj->Get_Bounding_Sphere()));
}
}
else
{
//perform normal culling on non-drawables
if (robj->Is_Force_Visible()) {
robj->Set_Visible(true);
} else {
robj->Set_Visible(!camera->Cull_Sphere(robj->Get_Bounding_Sphere()));
}
}
}
}
else
{
// Loop over all top-level RenderObjects in this scene. If the bounding sphere is not in front
// of all the frustum planes, it is invisible.
for (it.First(); !it.Is_Done(); it.Next()) {
robj = it.Peek_Obj();
if (robj->Is_Force_Visible()) {
robj->Set_Visible(true);
} else if (robj->Is_Hidden()) {
robj->Set_Visible(false);
} else {
bool isVisible=!camera->Cull_Sphere(robj->Get_Bounding_Sphere());
if (isVisible)
{
//need to keep track of occluders and occludees for subsequent code.
drawInfo = (DrawableInfo *)robj->Get_User_Data();
if (drawInfo && (draw=drawInfo->m_drawable) != nullptr)
{
if (draw->isDrawableEffectivelyHidden() || draw->getFullyObscuredByShroud())
{ robj->Set_Visible(false);
continue;
}
//assume normal rendering.
drawInfo->m_flags = DrawableInfo::ERF_IS_NORMAL; //clear any rendering flags that may be in effect.
if (draw->getEffectiveOpacity() != 1.0f && m_translucentObjectsCount < TheGlobalData->m_maxVisibleTranslucentObjects)
{
drawInfo->m_flags = DrawableInfo::ERF_IS_TRANSLUCENT;
m_translucentObjectsBuffer[m_translucentObjectsCount++] = robj;
}
else if (TheGlobalData->m_enableBehindBuildingMarkers && TheGameLogic && TheGameLogic->getShowBehindBuildingMarkers())
{
//visible drawable. Check if it's either an occluder or occludee
if (draw->isKindOf(KINDOF_STRUCTURE) && m_numPotentialOccluders < TheGlobalData->m_maxVisibleOccluderObjects)
{
//object which could occlude other objects that need to be visible.
m_potentialOccluders[m_numPotentialOccluders++]=robj;
drawInfo->m_flags |= DrawableInfo::ERF_POTENTIAL_OCCLUDER;
}
else if (draw->getObject() &&
(draw->isKindOf(KINDOF_SCORE) || draw->isKindOf(KINDOF_SCORE_CREATE) || draw->isKindOf(KINDOF_SCORE_DESTROY) || draw->isKindOf(KINDOF_MP_COUNT_FOR_VICTORY)) &&
(draw->getObject()->getSafeOcclusionFrame()) <= currentFrame && m_numPotentialOccludees < TheGlobalData->m_maxVisibleOccludeeObjects)
{
//object which could be occluded but still needs to be visible.
m_potentialOccludees[m_numPotentialOccludees++]=robj;
drawInfo->m_flags |= DrawableInfo::ERF_POTENTIAL_OCCLUDEE;
}
else if (drawInfo->m_flags == DrawableInfo::ERF_IS_NORMAL && m_numNonOccluderOrOccludee < TheGlobalData->m_maxVisibleNonOccluderOrOccludeeObjects)
{
//regular object with no custom effects but still needs to be delayed to get the occlusion feature to work correctly.
m_nonOccludersOrOccludees[m_numNonOccluderOrOccludee++]=robj;
drawInfo->m_flags |= DrawableInfo::ERF_IS_NON_OCCLUDER_OR_OCCLUDEE;
}
}
}
}
robj->Set_Visible(isVisible);
}
///@todo: We're not using LOD yet so I disabled this code. MW
// Also, should check how multiple passes (reflections) get along
// with the LOD manager - we're rendering double the load it thinks we are.
// Prepare visible objects for LOD:
// if (robj->Is_Really_Visible()) {
// robj->Prepare_LOD(*camera);
// }
}
}
Visibility_Checked = true;
}
//============================================================================
// RTS3DScene::renderSingleDrawable
//=============================================================================
/** Renders a single drawable entity. */
//=============================================================================
void RTS3DScene::renderSpecificDrawables(RenderInfoClass &rinfo, Int numDrawable, Drawable **theDrawables)
{
#ifdef DIRTY_CONDITION_FLAGS
StDrawableDirtyStuffLocker lockDirtyStuff;
#endif
const Int localPlayerIndex = rts::getObservedOrLocalPlayerIndex_Safe();
RefRenderObjListIterator it(&UpdateList);
// loop through all render objects in the list:
for (it.First(&RenderList); !it.Is_Done();)
{
RenderObjClass *robj;
// get the render object
robj = it.Peek_Obj();
it.Next(); //advance to next object in case this one gets deleted during renderOneObject().
DrawableInfo *drawInfo = (DrawableInfo *)robj->Get_User_Data();
Drawable *draw=nullptr;
if (drawInfo)
draw = drawInfo->m_drawable;
if (!draw) continue;
Bool match = false;
for (Int i = 0; i<numDrawable; i++) {
if (theDrawables[i] == draw) {
match = true;
break;
}
}
if (match) {
renderOneObject(rinfo, robj, localPlayerIndex);
}
}
}
//============================================================================
// RTS3DScene::renderOneObject
//=============================================================================
/** Renders a single drawable entity. */
//=============================================================================
void RTS3DScene::renderOneObject(RenderInfoClass &rinfo, RenderObjClass *robj, Int localPlayerIndex)
{
Drawable *draw = nullptr;
DrawableInfo *drawInfo = nullptr;
Bool drawableHidden=FALSE;
Object* obj = nullptr;
ObjectShroudStatus ss=OBJECTSHROUD_INVALID;
Bool doExtraMaterialPop=FALSE;
Bool doExtraFlagsPop=FALSE;
LightClass **sceneLights=m_globalLight;
if (robj->Class_ID() == RenderObjClass::CLASSID_IMAGE3D )
{
robj->Render(rinfo); //notify decals system that this track is visible
return; //decals are not lit by this system yet so skip rest of lighting
}
LightEnvironmentClass lightEnv;
SphereClass sph = robj->Get_Bounding_Sphere();
drawInfo = (DrawableInfo *)robj->Get_User_Data();
if (drawInfo)
{
draw = drawInfo->m_drawable;
//If we have a drawInfo but not drawable, we must be dealing with
//a ghost object which is always fogged.
if (!draw)
ss = OBJECTSHROUD_FOGGED;
}
// all this ambient business no longer handles the tinting and flashing stuff,
// but it does still light the drawable explicitly, and can be fudged like this
// infantry test does, here...
// the tint has been delegated to the getTint() stuff, below... MLorenzen
Vector3 ambient = Get_Ambient_Light();
if (draw && (drawableHidden=draw->isDrawableEffectivelyHidden()) != TRUE)
{
#ifdef NOT_IN_USE
const Vector3* drawAmbient = draw->getAmbientLight();
if (drawAmbient)
ambient.Add(ambient, *drawAmbient, &ambient);
#endif
obj = draw->getObject();
if (obj) {
ss = obj->getShroudedStatus(localPlayerIndex);
// For objects like planes, that pop out of the shroud, fire, then head back,
// we keep drawing them for 2 seconds after they return to the fogged area,
// so the player can see them and missiles chasing them. jba.
if (ss == OBJECTSHROUD_CLEAR) {
draw->setShroudClearFrame(TheGameLogic->getFrame());
} else if (ss >= OBJECTSHROUD_FOGGED && draw->getShroudClearFrame() != InvalidShroudClearFrame) {
UnsignedInt limit = 2*LOGICFRAMES_PER_SECOND;
if (obj->isEffectivelyDead()) {
limit += 3*LOGICFRAMES_PER_SECOND;
}
if (TheGameLogic->getFrame() < limit + draw->getShroudClearFrame()) {
// It's been less than 2 seconds since we could see them clear, so keep showing them.
ss = OBJECTSHROUD_PARTIAL_CLEAR;
}
}
if (!robj->Peek_Scene())
return; //this object was removed by the getShroudedStatus() call.
}
else
{
//drawable with no object so no way to know if it's shrouded.
ss = OBJECTSHROUD_CLEAR; //assume not shrouded/fogged.
//Check to see if there is another unrelated object which controls the shroud status
//(Hack for prison camps which contain enemy prisoner drawables)
if (drawInfo->m_shroudStatusObjectID != INVALID_ID)
{
Object *shroudObject=TheGameLogic->findObjectByID(drawInfo->m_shroudStatusObjectID);
if (shroudObject && shroudObject->getShroudedStatus(localPlayerIndex) >= OBJECTSHROUD_FOGGED)
ss = OBJECTSHROUD_SHROUDED; //we will assume that drawables without objects are 'particle' like and therefore don't need drawing if fogged/shrouded.
}
}
if (draw->isKindOf(KINDOF_INFANTRY))
{
ambient = m_infantryAmbient;
sceneLights = m_infantryLight;
}
lightEnv.Reset(sph.Center, ambient);
// HANDLE THE SPECIAL DRAWABLE-LEVEL COLORING SETTINGS FIRST
const Vector3 *tintColor = nullptr;
const Vector3 *selectionColor = nullptr;
tintColor = draw->getTintColor();
selectionColor = draw->getSelectionColor();
if ( tintColor || selectionColor )
{
Vector3 sumTint, temp, restore;
sumTint.Set(0,0,0);
if (tintColor)
Vector3::Add(sumTint, *tintColor, &sumTint);
if (selectionColor)
Vector3::Add(sumTint, *selectionColor, &sumTint);
for (Int globalLightIndex = 0; globalLightIndex < m_numGlobalLights; globalLightIndex++)
{
sceneLights[globalLightIndex]->Get_Diffuse( &temp );
restore = temp;
Vector3::Add(temp, sumTint, &temp);
sceneLights[globalLightIndex]->Set_Diffuse( temp );
lightEnv.Add_Light(*sceneLights[globalLightIndex]);
sceneLights[globalLightIndex]->Set_Diffuse( restore );
}
temp = lightEnv.Get_Equivalent_Ambient();
Vector3::Add(sumTint, temp, &temp );
lightEnv.Set_Output_Ambient( temp );
}
else // no funny coloring going on, so just add the lights normally
{
for (Int globalLightIndex = 0; globalLightIndex < m_numGlobalLights; globalLightIndex++)
{
lightEnv.Add_Light(*sceneLights[globalLightIndex]);
}
}
//Apply custom render pass for any drawables with heatvision enabled
if (draw->getHeatVisionOpacity() != 0 )
{
rinfo.materialPassEmissiveOverride = draw->getHeatVisionOpacity();
if (draw->getStealthLook() == STEALTHLOOK_VISIBLE_DETECTED )
{
// THIS WILL EXPLICITLY SKIP THE FIRST PASS SO THAT HEATVISION ONLY WILL RENDER
rinfo.Push_Override_Flags(RenderInfoClass::RINFO_OVERRIDE_ADDITIONAL_PASSES_ONLY);
rinfo.Push_Material_Pass(m_heatVisionOnlyPass);
doExtraFlagsPop=TRUE;
}
else
{
//THIS CALLS FOR THE HEATVISION TO RENDER
rinfo.Push_Material_Pass(m_heatVisionMaterialPass);
}
doExtraMaterialPop=TRUE;
}
}
else
{
//either no drawable or it is hidden
if (drawableHidden)
return; //don't bother with anything else
//Render object without a drawable. Must be either some fluff/debug object or a ghostObject.
if (ss == OBJECTSHROUD_FOGGED)
{
//Must be ghost object because we don't fog normal things. Fogged objects always have a predefined
//lighting environment applied which emulates the look of fog.
rinfo.light_environment = &m_foggedLightEnv;
robj->Render(rinfo);
rinfo.light_environment = nullptr;
return;
}
else
{
lightEnv.Reset(sph.Center, ambient);
for (Int globalLightIndex = 0; globalLightIndex < m_numGlobalLights; globalLightIndex++)
lightEnv.Add_Light(*m_globalLight[globalLightIndex]);
}
}
if (!drawableHidden)
{
//standard scene lights
RefRenderObjListIterator it2(&LightList);
for (it2.First(); !it2.Is_Done(); it2.Next())
{
LightClass *pLight = (LightClass*)it2.Peek_Obj();
SphereClass lSph = pLight->Get_Bounding_Sphere();
Bool cull = (pLight->Get_Type() == LightClass::POINT && !Spheres_Intersect(sph, lSph));
if (!cull) {
lightEnv.Add_Light(*pLight);
}
}
// dynamic lights
RefRenderObjListIterator dynaLightIt(&m_dynamicLightList);
for (dynaLightIt.First(); !dynaLightIt.Is_Done(); dynaLightIt.Next())
{
W3DDynamicLight* pDyna = (W3DDynamicLight*)dynaLightIt.Peek_Obj();
if (!pDyna->isEnabled()) {
continue;
}
SphereClass lSph = pDyna->Get_Bounding_Sphere();
if (pDyna->Get_Type() == LightClass::POINT && !Spheres_Intersect(sph, lSph)) {
continue;
}
lightEnv.Add_Light(*(LightClass*)dynaLightIt.Peek_Obj());
}
lightEnv.Pre_Render_Update(rinfo.Camera.Get_Transform());
rinfo.light_environment = &lightEnv;
if (drawInfo)
{
#if ENABLE_CONFIGURABLE_SHROUD
if (!TheGlobalData->m_shroudOn)
ss = OBJECTSHROUD_CLEAR;
#endif
if (m_customPassMode == SCENE_PASS_DEFAULT)
{
if (ss <= OBJECTSHROUD_CLEAR)
{
robj->Render(rinfo);
}
else
{
rinfo.Push_Material_Pass(m_shroudMaterialPass);
robj->Render(rinfo);
rinfo.Pop_Material_Pass();
}
}
else if (m_maskMaterialPass)
{
rinfo.Push_Material_Pass(m_maskMaterialPass);
rinfo.Push_Override_Flags(RenderInfoClass::RINFO_OVERRIDE_ADDITIONAL_PASSES_ONLY);
robj->Render(rinfo);
rinfo.Pop_Override_Flags();
rinfo.Pop_Material_Pass();
}
}
else
{
robj->Render(rinfo);
}
}
rinfo.light_environment = nullptr;
if (doExtraMaterialPop) //check if there is an extra material on the stack from the heatvision effect.
rinfo.Pop_Material_Pass();
if (doExtraFlagsPop)
rinfo.Pop_Override_Flags(); //flags used to disable base pass and only render custom heat vision pass.
}
//DECLARE_PERF_TIMER(translucentRender)
/**Draw everything that was submitted from this scene*/
void RTS3DScene::Flush(RenderInfoClass & rinfo)
{
// TheSuperHackers @bugfix Now always prepares shadows to guarantee correct state before doing any
// shadow draw calls. Originally just drawing shadows for trees would not properly prepare shadows.
PrepareShadows();
//don't draw shadows in this mode because they interfere with destination alpha or are invisible (wireframe)
if (m_customPassMode == SCENE_PASS_DEFAULT && Get_Extra_Pass_Polygon_Mode() == EXTRA_PASS_DISABLE)
DoShadows(rinfo, false); //draw all non-stencil shadows (decals) since they fall under other objects.
TheDX8MeshRenderer.Flush(); //draw all non-translucent objects.
//draw all non-translucent objects which were separated because they are hidden and need custom rendering.
#ifdef USE_NON_STENCIL_OCCLUSION
flushOccludedObjects(rinfo);
#else
if (DX8Wrapper::Has_Stencil())
flushOccludedObjectsIntoStencil(rinfo);
#endif
// Draw the trees last so they alpha blend onto everything correctly.
DoTrees(rinfo);
//don't draw shadows in this mode because they interfere with destination alpha
if (m_customPassMode == SCENE_PASS_DEFAULT && Get_Extra_Pass_Polygon_Mode() == EXTRA_PASS_DISABLE)
DoShadows(rinfo, true); //draw all stencil shadows
WW3D::Render_And_Clear_Static_Sort_Lists(rinfo); //draws things like water
if (m_customPassMode == SCENE_PASS_DEFAULT && Get_Extra_Pass_Polygon_Mode() == EXTRA_PASS_DISABLE)
flushTranslucentObjects(rinfo); //draw all translucent meshes which don't need per-polygon sorting.
{
//USE_PERF_TIMER(translucentRender)
//don't draw transparent in this mode because they interfere with destination alpha
if (m_customPassMode == SCENE_PASS_DEFAULT && Get_Extra_Pass_Polygon_Mode() == EXTRA_PASS_DISABLE)
DoParticles(rinfo); //queue up particles for rendering.
SortingRendererClass::Flush(); //draw sorted translucent polygons like particles.
}
TheDX8MeshRenderer.Clear_Pending_Delete_Lists();
}
/**Generate a predefined light environment(s) that will be applied to many objects. Useful for things like totally fogged
objects and most generic map objects that are not lit by dynamic lights.*/
void RTS3DScene::updateFixedLightEnvironments(RenderInfoClass & rinfo)
{
//Figure out how dimly lit fogged objects should be compared to fully lit.
Real foggedLightFrac = (Real)TheGlobalData->m_fogAlpha/(Real)TheGlobalData->m_clearAlpha;
Vector3 oldDiffuse;
Real infantryLightScale;
if( TheGlobalData->m_scriptOverrideInfantryLightScale != -1.0f )
infantryLightScale = TheGlobalData->m_scriptOverrideInfantryLightScale;
else
infantryLightScale = TheGlobalData->m_infantryLightScale[TheGlobalData->m_timeOfDay];
//Generate the default light environment
m_defaultLightEnv.Reset(Vector3(0,0,0), Get_Ambient_Light());
m_foggedLightEnv.Reset(Vector3(0,0,0), Get_Ambient_Light()*foggedLightFrac);
for (Int globalLightIndex = 0; globalLightIndex < m_numGlobalLights; globalLightIndex++)
{
m_defaultLightEnv.Add_Light(*m_globalLight[globalLightIndex]);
//copy default lighting for infantry so we can tweak it.
*m_infantryLight[globalLightIndex]=*m_globalLight[globalLightIndex];
m_globalLight[globalLightIndex]->Get_Diffuse(&oldDiffuse);
m_infantryLight[globalLightIndex]->Set_Diffuse(oldDiffuse*infantryLightScale);
m_globalLight[globalLightIndex]->Get_Ambient(&oldDiffuse);
m_infantryLight[globalLightIndex]->Set_Ambient(oldDiffuse*infantryLightScale);
m_infantryLight[globalLightIndex]->Set_Transform(m_globalLight[globalLightIndex]->Get_Transform());
//copy the normal light for fog so we can modify it
m_scratchLight->Set_Transform(m_globalLight[globalLightIndex]->Get_Transform());
//modify light with attenuated value to adjust for fog.
m_globalLight[globalLightIndex]->Get_Diffuse(&oldDiffuse);
m_scratchLight->Set_Diffuse(oldDiffuse*foggedLightFrac);
m_globalLight[globalLightIndex]->Get_Ambient(&oldDiffuse);
m_scratchLight->Set_Ambient(oldDiffuse*foggedLightFrac);
m_foggedLightEnv.Add_Light(*m_scratchLight);
}
m_defaultLightEnv.Pre_Render_Update(rinfo.Camera.Get_Transform());
m_foggedLightEnv.Pre_Render_Update(rinfo.Camera.Get_Transform());
m_infantryAmbient = Get_Ambient_Light();// * infantryLightScale; //for now don't adjust ambient so that we don't lose directional lighting.
}
/**Generate custom rendering passes for each potential player color. This is currently only used
to render occluded objects using the color of the player*/
void RTS3DScene::updatePlayerColorPasses()
{
#ifdef USE_NON_STENCIL_OCCLUSION
Vector3 hsv,rgb;
if (TheGlobalData->m_enableBehindBuildingMarkers && TheGameLogic->getShowBehindBuildingMarkers())
{
Int numPlayers=ThePlayerList->getPlayerCount();
for (Int i=0; i<numPlayers; i++)
{ Player *player=ThePlayerList->getNthPlayer(i);
Int playerIndex=player->getPlayerIndex();
Real red,green,blue,alpha;
GameGetColorComponentsReal(player->getPlayerColor(),&red,&green,&blue,&alpha);
RGB_To_HSV(hsv,Vector3(red,green,blue));
hsv.Z*=TheGlobalData->m_occludedLuminanceScale;
HSV_To_RGB(rgb,hsv);
VertexMaterialClass *vmat=m_occludedMaterialPass[playerIndex]->Peek_Material();
vmat->Set_Emissive(rgb);
}
}
#endif
}
#define ZBias 0.0001f
//DECLARE_PERF_TIMER(NonTerrainRender)
void RTS3DScene::Render(RenderInfoClass & rinfo)
{
//USE_PERF_TIMER(NonTerrainRender)
DX8Wrapper::Set_Fog(FogEnabled, FogColor, FogStart, FogEnd);
//Override the behind building selection if it's not available on current hardware (needs stencil).
TheWritableGlobalData->m_enableBehindBuildingMarkers = TheWritableGlobalData->m_enableBehindBuildingMarkers && DX8Wrapper::Has_Stencil();
if (Get_Extra_Pass_Polygon_Mode() == EXTRA_PASS_DISABLE)
{
if (m_customPassMode == SCENE_PASS_DEFAULT)
{
//Regular rendering pass with no effects
updatePlayerColorPasses();///@todo: this probably doesn't need to be done each frame.
updateFixedLightEnvironments(rinfo);
Customized_Render(rinfo);
Flush(rinfo);
}
else if (m_customPassMode == SCENE_PASS_ALPHA_MASK)
{
//a projected alpha texture which will later be used to determine where
//wireframe should be visible.
///@todo: Clearing to black may not be needed if the scene already did the clear.
DX8Wrapper::Set_DX8_Render_State(D3DRS_COLORWRITEENABLE,D3DCOLORWRITEENABLE_ALPHA);
DX8Wrapper::Set_DX8_Render_State (D3DRS_ZBIAS, 0);
//Since all objects will be rendered with same material, disable resetting until all are done.
m_maskMaterialPass->setAllowUninstall(FALSE);
Customized_Render(rinfo); //render mask into alpha channel and fill z-buffer with depth values.
Flush(rinfo);
m_maskMaterialPass->setAllowUninstall(TRUE);
m_maskMaterialPass->UnInstall_Materials();
DX8Wrapper::Set_DX8_Render_State(D3DRS_COLORWRITEENABLE,D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_RED);
ShaderClass::Invalidate();
}
}
else
{
Bool old_enable=WW3D::Is_Texturing_Enabled();
if (Get_Extra_Pass_Polygon_Mode() == EXTRA_PASS_CLEAR_LINE)
{
//render scene with solid black color but have destination alpha store
//a projected alpha texture which will later be used to determine where
//wireframe should be visible.
///@todo: Clearing to black may not be needed if the scene already did the clear.
DX8Wrapper::Clear(true, false, Vector3(0.0f,0.0f,0.0f),1.0f); // Clear color but not z
DX8Wrapper::Set_DX8_Render_State(D3DRS_COLORWRITEENABLE,D3DCOLORWRITEENABLE_ALPHA);
DX8Wrapper::Set_DX8_Render_State (D3DRS_ZBIAS, 0);
//We're only filling the z-buffer so ignore normal textures and state changes to speed things up.
m_customPassMode = SCENE_PASS_ALPHA_MASK;
m_maskMaterialPass->setAllowUninstall(FALSE);
Customized_Render(rinfo); //render mask into alpha channel and fill z-buffer with depth values.
Flush(rinfo);
m_maskMaterialPass->setAllowUninstall(TRUE);
m_maskMaterialPass->UnInstall_Materials();
DX8Wrapper::Set_DX8_Render_State(D3DRS_COLORWRITEENABLE,D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_RED);
WW3D::Enable_Coloring(0xff008000);
WW3D::Enable_Texturing(false);
DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
//Move maximum z-buffer value in a little to shift all z-values closer
//and thus forcing line to appear on top of previous pass.
Real nearZ,farZ;
rinfo.Camera.Get_Zbuffer_Range(nearZ, farZ);
rinfo.Camera.Set_Zbuffer_Range(nearZ, farZ-ZBias);
rinfo.Camera.Apply();
// DX8Wrapper::Set_DX8_Render_State (D3DRS_ZBIAS, 4);
Customized_Render(rinfo); //render wireframe where z-test passes
Flush(rinfo);
DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_SOLID);