summaryrefslogtreecommitdiff
path: root/Runtime/Camera/ShadowCulling.cpp
blob: f2455471b3fe403bc09888e2d959e0f07ce318f4 (plain)
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
#include "UnityPrefix.h"
#include "ShadowCulling.h"
#include "Runtime/Camera/Light.h"
#include "Runtime/Camera/Camera.h"
#include "Runtime/Camera/CameraUtil.h"
#include "Runtime/Graphics/Transform.h"
#include "Runtime/Geometry/Sphere.h"
#include "Runtime/Geometry/Intersection.h"
#include "Runtime/Math/Rect.h"
#include "Runtime/Misc/QualitySettings.h"
#include "Runtime/Shaders/Material.h"
#include "Runtime/Shaders/Shader.h"
#include "Runtime/Profiler/Profiler.h"
#include "Runtime/Misc/GameObjectUtility.h"
#include "External/shaderlab/Library/shaderlab.h"
#include "External/shaderlab/Library/intshader.h"
#include "Runtime/Camera/BaseRenderer.h"
#include "Runtime/Camera/CullResults.h"
#include "Runtime/Camera/SceneCulling.h"
#include "Runtime/Camera/SceneNode.h"
#include "Runtime/Camera/UnityScene.h"
#include "Runtime/Geometry/BoundingUtils.h"

#include "SceneCulling.h"

PROFILER_INFORMATION(gShadowsCullCastersPoint, "Shadows.CullCastersPoint", kProfilerRender)
PROFILER_INFORMATION(gShadowsCullCastersSpot, "Shadows.CullCastersSpot", kProfilerRender)
PROFILER_INFORMATION(gShadowsCullCastersDir, "Shadows.CullCastersDir", kProfilerRender)

static const float kShadowFadeRange = 0.2f;

static bool AddShadowCasterCullPlane(const Plane frustumCullPlanes[6], const Matrix4x4f& clipToWorld, const Vector3f& centerWorld, float nearPlaneScale, float farPlaneScale, int sideA, int sideB, int sideNeighbor, LightType lightType, const Vector3f& lightVec, Plane& outPlane)
{
	static Vector3f sideOffsets[] = {
		Vector3f(-1.0f,  0.0f,  0.0f),	// kPlaneFrustumLeft
		Vector3f( 1.0f,  0.0f,  0.0f),	// kPlaneFrustumRight
		Vector3f( 0.0f, -1.0f,  0.0f),	// kPlaneFrustumBottom
		Vector3f( 0.0f,  1.0f,  0.0f),	// kPlaneFrustumTop
		Vector3f( 0.0f,  0.0f, -1.0f),	// kPlaneFrustumNear
		Vector3f( 0.0f,  0.0f,  1.0f)	// kPlaneFrustumFar
	};

	const Plane& planeA = frustumCullPlanes[sideA];
	const Plane& planeB = frustumCullPlanes[sideB];
	Vector3f edgeNormal = planeA.GetNormal() + planeB.GetNormal(); // No need to normalize
	Vector3f edgeCenter = sideOffsets[sideA] + sideOffsets[sideB];
	Vector3f edgeDir = sideOffsets[sideNeighbor];
	Vector3f posWorld1, posWorld2;
	Vector3f posLocal1 = edgeCenter - edgeDir;
	Vector3f posLocal2 = edgeCenter + edgeDir;
	clipToWorld.PerspectiveMultiplyPoint3( posLocal1, posWorld1 );
	clipToWorld.PerspectiveMultiplyPoint3( posLocal2, posWorld2 );
	float scale1 = (posLocal1.z < 0.0f) ? nearPlaneScale : farPlaneScale;
	float scale2 = (posLocal2.z < 0.0f) ? nearPlaneScale : farPlaneScale;
	posWorld1 = centerWorld + (posWorld1 - centerWorld) * scale1;
	posWorld2 = centerWorld + (posWorld2 - centerWorld) * scale2;

	if( lightType == kLightDirectional )
	{
		/////@TODO: RUnning around in debug mode this seems to hit quite often in the shantytown scene...
		Vector3f edgeDirWorld = (posWorld2 != posWorld1) ? Normalize( posWorld2 - posWorld1 ) : Vector3f(0.0f, 0.0f, 0.0f);
		Vector3f clipNormal = Cross( edgeDirWorld, lightVec );
		float len = Magnitude( clipNormal );
		// Discard plane if edge is almost parallel with light dir
		if (len < 0.001f)
			return false;
		clipNormal /= len;

		// Flip the normal if we got the wrong direction
		if( Dot( clipNormal, edgeNormal ) < 0.0f )
		{
			clipNormal *= -1.0f;
		}
		outPlane.SetNormalAndPosition( clipNormal, posWorld1 );
	}
	else
	{
		// We know the light is not too close to either plane
		outPlane.Set3Points( posWorld1, posWorld2, lightVec );

		if( Dot( outPlane.GetNormal(), edgeNormal ) < 0.0f )
		{
			outPlane *= -1.0f;
		}
	}
	return true;
}

void CalculateShadowCasterCull(const Plane frustumCullPlanes[6], const Matrix4x4f& clipToWorld,
							   const Vector3f& centerWorld, float nearPlaneScale, float farPlaneScale,
							   LightType lightType, const Vector3f& lightVec, ShadowCasterCull& result,
							   const bool alreadyTested[kPlaneFrustumNum])
{
	// Create clip volume from the distant planes and silhouette edges of camera's frustum (as seen by the light)
	// Maximum planes generated should be 10, but we check at runtime to be sure
	result.planeCount = 0;
	bool facingLight[kPlaneFrustumNum];
	bool enablePlane[kPlaneFrustumNum];
	float epsilon = 0.01f;
	for( int i = 0; i < kPlaneFrustumNum; ++i )
	{
		Plane plane = frustumCullPlanes[i];
		if( lightType == kLightDirectional )
		{
			// Compare light direction and normal
			float d = Dot( plane.GetNormal(), lightVec );
			facingLight[i] = d < 0.0f;
			enablePlane[i] = true;
		}
		else
		{
			float dist = plane.GetDistanceToPoint( lightVec );
			facingLight[i] = false;
			enablePlane[i] = true;
			if( dist > -epsilon )
			{
				// Light is inside or just outside the frustum
				facingLight[i] = true;
				if ( dist < epsilon )
				{
					// Point is too close to the plane to care about edges
					enablePlane[i] = false;
				}
				if ( dist < 0.0f )
				{
					// Push plane slightly so the frustum encloses the light
					plane.distance -= dist;
				}
			}
		}
		if( facingLight[i] && !alreadyTested[i] )
		{
			result.planes[result.planeCount++] = plane;
			if( result.planeCount == ShadowCasterCull::kMaxPlanes )
				return;
		}
	}

	// Sides in running order (each plane touches previous)
	static int camera4Sides[] = {
		kPlaneFrustumLeft,
		kPlaneFrustumBottom,
		kPlaneFrustumRight,
		kPlaneFrustumTop
	};
	static int cameraNearFar[] = {
		kPlaneFrustumNear,
		kPlaneFrustumFar
	};

	// Iterate over diagonal edges
	for( int edge = 0; edge < 4; ++edge )
	{
		int sideA = camera4Sides[edge];
		// If we already tested side A, we also tested B
		if( alreadyTested[sideA] )
			continue;
		int sideB = camera4Sides[(edge + 1) % 4];
		int sideNeighbor = kPlaneFrustumFar;
		if( facingLight[sideA] != facingLight[sideB] &&
			enablePlane[sideA] && enablePlane[sideB] )
		{
			Plane& plane = result.planes[result.planeCount];
			bool success = AddShadowCasterCullPlane(frustumCullPlanes, clipToWorld,
				centerWorld, nearPlaneScale, farPlaneScale,
				sideA, sideB, sideNeighbor, lightType, lightVec, plane);
			result.planeCount += success ? 1 : 0;
			if( result.planeCount == ShadowCasterCull::kMaxPlanes )
				return;
		}
	}

	// Iterate over near and far edges
	for( int nearFar = 0; nearFar < 2; ++nearFar )
	{
		int sideA = cameraNearFar[nearFar];
		// If we already tested side A, we also tested B
		if( alreadyTested[sideA] )
			continue;
		for( int edge = 0; edge < 4; ++edge )
		{
			int sideB = camera4Sides[edge];
			int sideNeighbor = camera4Sides[(edge + 1) % 4];
			if( facingLight[sideA] != facingLight[sideB] &&
				enablePlane[sideA] && enablePlane[sideB] )
			{
				Plane& plane = result.planes[result.planeCount];
				bool success = AddShadowCasterCullPlane(frustumCullPlanes, clipToWorld,
					centerWorld, nearPlaneScale, farPlaneScale,
					sideA, sideB, sideNeighbor, lightType, lightVec, plane);
				result.planeCount += success ? 1 : 0;
				if( result.planeCount == ShadowCasterCull::kMaxPlanes )
					return;
			}
		}
	}
}

static const bool s_AlreadyTestedNone[kPlaneFrustumNum] = { false, false, false, false, false, false };

void CalculateShadowCasterCull(const Plane frustumCullPlanes[6], const Matrix4x4f& clipToWorld, const Vector3f& centerWorld, float nearPlaneScale, float farPlaneScale, LightType lightType, const Transform& trans, ShadowCasterCull& result)
{
	// Get position for positional lights and direction for directional lights
	Vector3f lightVec;
	if( lightType == kLightDirectional )
	{
		lightVec = trans.TransformDirection( Vector3f::zAxis );
	}
	else
	{
		Assert( lightType == kLightPoint || lightType == kLightSpot );
		lightVec = trans.GetPosition();
	}
	CalculateShadowCasterCull(frustumCullPlanes, clipToWorld, centerWorld, nearPlaneScale, farPlaneScale, lightType, lightVec, result, s_AlreadyTestedNone);
}

static bool CanUseProjectionForShadows (const Matrix4x4f& clipToWorld, float farNearRatio, const Camera& camera, const Vector3f& cameraPos)
{
	// Check if eye position is the focal point of the camera projection
	// and we can scale near plane from the eye pos to get the far plane.
	// This works for asymmetric projections, not for oblique etc.
	Vector3f cameraFrustum[8];
	GetFrustumPoints(clipToWorld, cameraFrustum);
	for (int i = 0; i < 4; i++)
	{
		const Vector3f& nearPos = cameraFrustum[i];
		const Vector3f& farPos = cameraFrustum[i + 4];
		Vector3f derivedFar = cameraPos + (nearPos - cameraPos) * farNearRatio;
		float diff = SqrMagnitude(derivedFar - farPos);
		float length = SqrMagnitude(farPos - nearPos);
		if (!(diff <= length * 0.01f))
		{
			return false;
		}
	}
	return true;
}

void SetupShadowCullData (Camera& camera, const Vector3f& cameraPos, const ShaderReplaceData& shaderReplaceData, const SceneCullingParameters* sceneCullParams, ShadowCullData& cullData)
{
	const Rectf screenRect = camera.GetScreenViewportRect();
	float shadowDistance = CalculateShadowDistance (camera);

	Vector3f viewDir = -NormalizeSafe(camera.GetCameraToWorldMatrix().GetAxisZ());

	cullData.camera = &camera;
	cullData.eyePos = cameraPos;
	cullData.viewDir = viewDir;
	cullData.shadowDistance = shadowDistance;
	cullData.projectionNear = camera.GetProjectionNear();
	cullData.projectionFar = camera.GetProjectionFar();
	cullData.farPlaneScale = shadowDistance / cullData.projectionFar;
	cullData.viewWidth = screenRect.width;
	cullData.viewHeight = screenRect.height;
	cullData.actualWorldToClip = camera.GetWorldToClipMatrix();
	cullData.visbilityForShadowCulling = NULL;
	Matrix4x4f::Invert_Full(cullData.actualWorldToClip, cullData.cameraClipToWorld);

	float farNearRatio = cullData.projectionFar / cullData.projectionNear;
	if (!CanUseProjectionForShadows(cullData.cameraClipToWorld, farNearRatio, camera, cameraPos))
	{
		// Use implicit projection instead (which we used always before 3.5)
		Matrix4x4f proj;
		camera.GetImplicitProjectionMatrix(camera.GetNear(), camera.GetFar(), proj);
		MultiplyMatrices4x4 (&proj, &camera.GetWorldToCameraMatrix(), &cullData.cameraWorldToClip);
		Matrix4x4f::Invert_Full(cullData.cameraWorldToClip, cullData.cameraClipToWorld);
	}
	else
		cullData.cameraWorldToClip = cullData.actualWorldToClip;

	camera.CalculateFrustumPlanes(cullData.shadowCullPlanes, cullData.cameraWorldToClip, shadowDistance, cullData.baseFarDistance, true);
	for( int i = 0; i < kPlaneFrustumNum; i++ )
		cullData.cameraCullPlanes[i] = cullData.shadowCullPlanes[i];
	cullData.cameraCullPlanes[kPlaneFrustumFar].distance = cullData.baseFarDistance + camera.GetFar();
	cullData.shadowCullCenter = Vector3f::zero;
	float cullRadius = 1e15f;
	cullData.useSphereCulling = CalculateSphericalShadowRange(camera, cullData.shadowCullCenter, cullRadius);
	cullData.shadowCullRadius = cullRadius;
	cullData.shadowCullSquareRadius = cullRadius * cullRadius;
	const float* layerCullDistances = camera.GetLayerCullDistances();
	std::copy(layerCullDistances, layerCullDistances + kNumLayers, cullData.layerCullDistances);
	cullData.layerCullSpherical = camera.GetLayerCullSpherical();
	cullData.shaderReplace = shaderReplaceData;
	cullData.sceneCullParameters = sceneCullParams;
}

float CalculateShadowDistance (const Camera& camera)
{
	return std::min (QualitySettings::GetShadowDistanceForRendering(), camera.GetFar());
}

float CalculateShadowSphereOffset (const Camera& camera)
{
	float fov = camera.GetFov();
	static float maxDegrees = 180.0f;
	const float maxOffset = (1.0f - kShadowFadeRange) * 0.5f;
	float weight = clamp(1.0f - fov / maxDegrees, 0.0f, 1.0f);
	return maxOffset * weight;
}

bool CalculateSphericalShadowRange (const Camera& camera, Vector3f& outCenter, float& outRadius)
{
	const QualitySettings::QualitySetting& quality = GetQualitySettings().GetCurrent();
	if (quality.shadowProjection == kShadowProjCloseFit)
		return false;

	outCenter = camera.GetPosition();
	outRadius = CalculateShadowDistance(camera);

	float sphereOffset = CalculateShadowSphereOffset(camera);
	Vector3f vectorOffset(0, 0, -sphereOffset * outRadius);
	outCenter += camera.GetCameraToWorldMatrix().MultiplyVector3(vectorOffset);
	outRadius *= (1.0f - sphereOffset);
	return true;

	Assert(quality.shadowProjection == kShadowProjStableFit);
	return true;
}

void CalculateLightShadowFade (const Camera& camera, float shadowStrength, Vector4f& outParams, Vector4f& outCenterAndType)
{
	float shadowDistance = CalculateShadowDistance(camera);
	float shadowRange = shadowDistance;
	Vector3f center = camera.GetPosition();
	bool spherical = CalculateSphericalShadowRange(camera, center, shadowRange);

	// R = 1-strength
	// G = 1.0 / shadowDistance
	// B = 1.0 / (shadowDistance - shadowStartFade)
	// A = -shadowStartFade / (shadowDistance - shadowStartFade)
	outParams.x = 1.0f - shadowStrength; // R = 1-strength

	if (shadowRange > 0)
	{
		outParams.y = camera.GetFar() / shadowDistance;
		// fade factor = (x-start)/len = x * invlen - start*invlen
		const float shadowStartFade = shadowRange - shadowDistance * kShadowFadeRange;
		const float shadowFadeInvLen = 1.0f / (shadowRange - shadowStartFade);
		outParams.z = shadowFadeInvLen;
		outParams.w = -shadowStartFade * shadowFadeInvLen;
	}
	else
	{
		outParams.y = std::numeric_limits<float>::infinity();
		outParams.z = 0;
		outParams.w = 1;
	}

	outCenterAndType = Vector4f(center.x, center.y, center.z, spherical);
}

struct ShadowCullContext
{
	const ShadowCullData* camera;
	bool excludeLightmapped;
	UInt32 cullLayers;
};


static void AddShadowCaster (const SceneNode& node, const AABB& aabb, const ShadowCullData& context, bool expandCasterBounds, MinMaxAABB& casterBounds, ShadowCasters& casters, ShadowCasterParts& casterParts)
{
	const BaseRenderer* renderer = node.renderer;
	
	Assert( renderer && renderer->GetCastShadows() );

	// Find out which sub-materials do cast shadows
	// and prefetch shader pointers.
	size_t partsStartIndex = casterParts.size();
	int matCount = renderer->GetMaterialCount();
	
	Shader* replaceShader = context.shaderReplace.replacementShader;
	const bool replacementTagSet = context.shaderReplace.replacementTagSet;
	const int replacementTagID = context.shaderReplace.replacementTagID;
	
	for( int i = 0; i < matCount; ++i )
	{
		Material* mat = renderer->GetMaterial(i);
		if( !mat )
			continue;

		Shader* originalShader = mat->GetShader();
		Shader* actualShader = replaceShader ? replaceShader : originalShader;
		
		// Find the subshader...
		int usedSubshaderIndex = -1;
		if (replaceShader)
		{
			if (replacementTagSet)
			{
				int subshaderTypeID = originalShader->GetShaderLabShader()->GetTag (replacementTagID, true);
				if (subshaderTypeID < 0)
					continue; // skip rendering
				usedSubshaderIndex = replaceShader->GetSubShaderWithTagValue (replacementTagID, subshaderTypeID);
				if (usedSubshaderIndex == -1)
					continue; // skip rendering
			}
			else
				usedSubshaderIndex = 0;
		}
		else
			usedSubshaderIndex = originalShader->GetActiveSubShaderIndex();
		
		Assert (usedSubshaderIndex != -1);
		
		if (actualShader->GetShadowCasterPassToUse(usedSubshaderIndex))
		{
			ShadowCasterPartData part;
			part.subMeshIndex = renderer->GetSubsetIndex(i);
			part.shader = actualShader;
			part.subShaderIndex = usedSubshaderIndex;
			part.material = mat;
			casterParts.push_back (part);
		}
	}

	// This object does cast shadows, store info
	size_t partsEndIndex = casterParts.size();
	if( partsEndIndex != partsStartIndex )
	{
		ShadowCasterData data;
		data.node = &node;
		data.worldAABB = &aabb;
		data.visibleCascades = 1;
		data.partsStartIndex = partsStartIndex;
		data.partsEndIndex = partsEndIndex;

		casters.push_back( data );

		if( expandCasterBounds )
			casterBounds.Encapsulate( aabb );
	}
}

static bool CullCastersCommon(const ShadowCullContext& context, const SceneNode& node, const AABB& aabb)
{
	const BaseRenderer* renderer = node.renderer;
	if (!renderer->GetCastShadows())
		return false;

	if (context.excludeLightmapped && renderer->IsLightmappedForShadows())
		return false;

	const int nodeLayer = node.layer;
	const int nodeLayerMask = 1 << nodeLayer;
	if (!(nodeLayerMask & context.cullLayers))
		return false;

	// For casters that use per-layer culling distance: check if they are behind cull distance.
	// If they are, don't cast shadows.
	const ShadowCullData& cullData = *context.camera;
	float layerCullDist = cullData.layerCullDistances[nodeLayer];
	if (layerCullDist)
	{
		if (cullData.layerCullSpherical)
		{

			float sqDist = SqrMagnitude(aabb.GetCenter() - cullData.eyePos);
			if (sqDist > Sqr(layerCullDist))
				return false;
		}
		else
		{
			Plane farPlane = cullData.shadowCullPlanes[kPlaneFrustumFar];
			farPlane.distance = layerCullDist + cullData.baseFarDistance;
			if( !IntersectAABBPlaneBounds( aabb, &farPlane, 1 ) )
				return false;			
		}
	}

	return true;
}

//
// Point light shadow caster culling

struct PointCullContext : public ShadowCullContext
{
	Sphere lightSphere;
};

static bool CullCastersPoint( PointCullContext* context, const SceneNode& node, const AABB& aabb )
{
	if (!CullCastersCommon(*context, node, aabb))
		return false;
	
	if (!IntersectAABBSphere( aabb, context->lightSphere ))
		return false;

	return true;
}

//
// Spot light shadow caster culling

struct SpotCullContext : public ShadowCullContext
{
	Matrix4x4f worldToLightMatrix, projectionMatrix;
	Plane spotLightFrustum[6];
};

static bool CullCastersSpot( SpotCullContext* context, const SceneNode& node, const AABB& aabb )
{
	if (!CullCastersCommon(*context, node, aabb))
		return false;

	// World space light frustum vs. global AABB
	if (!IntersectAABBFrustumFull (aabb, context->spotLightFrustum))
		return false;

	const TransformInfo& xformInfo = node.renderer->GetTransformInfo ();

	Plane planes[6];
	// NOTE: it's important to multiply world->light and node->world matrices
	// before multiplying in the projection matrix. Otherwise when object/light
	// coordinates will approach 10 thousands range, we'll get culling errors
	// because of imprecision.
	//Matrix4x4f proj = context->projectionMatrix * (context->worldToLightMatrix * node->worldMatrix);
	Matrix4x4f temp, proj;
	MultiplyMatrices4x4 (&context->worldToLightMatrix, &xformInfo.worldMatrix, &temp);
	MultiplyMatrices4x4 (&context->projectionMatrix, &temp, &proj);
	ExtractProjectionPlanes( proj, planes );

	if (!IntersectAABBFrustumFull( xformInfo.localAABB, planes ) )
		return false;

	return true;
}


//
// Directional light shadow caster culling

struct DirectionalCullContext : public ShadowCullContext
{
};

static bool CullCastersDirectional( DirectionalCullContext* context, const SceneNode& node, const AABB& aabb )
{
	return CullCastersCommon(*context, node, aabb);
}


static void CullDirectionalShadows (IndexList& visible, const SceneNode* nodes, const AABB* boundingBoxes, DirectionalCullContext &context )
{
	// Generate Visible nodes from all static & dynamic objects
	int visibleCount = 0;
	for (int i=0;i<visible.size;i++)
	{
		const SceneNode& node = nodes[visible.indices[i]];
		const AABB& bounds = boundingBoxes[visible.indices[i]];

		if (CullCastersDirectional( &context, node, bounds))
			visible.indices[visibleCount++] = visible.indices[i];
	}
	visible.size = visibleCount;
}

static void CullSpotShadows (IndexList& visible, const SceneNode* nodes, const AABB* boundingBoxes, SpotCullContext &context )
{
	// Generate Visible nodes from all static & dynamic objects
	int visibleCount = 0;
	for (int i=0;i<visible.size;i++)
	{
		const SceneNode& node = nodes[visible.indices[i]];
		const AABB& bounds = boundingBoxes[visible.indices[i]];

		if (CullCastersSpot( &context, node, bounds))
			visible.indices[visibleCount++] = visible.indices[i];
	}
	visible.size = visibleCount;
}

static void CullPointShadows (IndexList& visible, const SceneNode* nodes, const AABB* boundingBoxes, PointCullContext &context )
{
	// Generate Visible nodes from all static & dynamic objects
	int visibleCount = 0;
	for (int i=0;i<visible.size;i++)
	{
		const SceneNode& node = nodes[visible.indices[i]];
		const AABB& bounds = boundingBoxes[visible.indices[i]];

		if (CullCastersPoint( &context, node, bounds ))
			visible.indices[visibleCount++] = visible.indices[i];
	}
	visible.size = visibleCount;
}

static void CullShadowCastersDetail( const Light& light, const ShadowCullData& cullData, bool excludeLightmapped, CullingOutput& visibleRenderers )
{
	const RendererCullData* rendererCullData = cullData.sceneCullParameters->renderers;
	
	int cullLayers = light.GetCullingMask() & cullData.camera->GetCullingMask();
	LightType lightType = light.GetType();
	switch (lightType)
	{
		case kLightPoint:
		{
			PointCullContext context;
			const Transform& lt = light.GetComponent (Transform);
			Vector3f lightPos = lt.GetPosition();
			context.lightSphere = Sphere( lightPos, light.GetRange() );
			context.camera = &cullData;
			context.cullLayers = cullLayers;
			context.excludeLightmapped = excludeLightmapped;
			
			for (int i=0;i<kVisibleListCount;i++)
				CullPointShadows (visibleRenderers.visible[i], rendererCullData[i].nodes, rendererCullData[i].bounds, context);
		}
			break;
			
		case kLightSpot:
		{
			SpotCullContext context;
			Matrix4x4f zscale, proj;
			zscale.SetScale (Vector3f (1.0F, 1.0F, -1.0F));
			proj.SetPerspectiveCotan( light.GetCotanHalfSpotAngle(), 0.0001F, light.GetRange() );
			MultiplyMatrices4x4 (&proj, &zscale, &context.projectionMatrix);
			const Transform& lt = light.GetComponent (Transform);
			context.worldToLightMatrix = lt.GetWorldToLocalMatrixNoScale();
			
			Matrix4x4f temp;
			MultiplyMatrices4x4 (&context.projectionMatrix, &context.worldToLightMatrix, &temp);
			ExtractProjectionPlanes (temp, context.spotLightFrustum);
			
			context.camera = &cullData;
			context.cullLayers = cullLayers;
			context.excludeLightmapped = excludeLightmapped;
			
			for (int i=0;i<kVisibleListCount;i++)
				CullSpotShadows (visibleRenderers.visible[i], rendererCullData[i].nodes, rendererCullData[i].bounds, context);
		}
			break;
		case kLightDirectional:
		{
			DirectionalCullContext context;
			context.camera = &cullData;
			context.cullLayers = cullLayers;
			context.excludeLightmapped = excludeLightmapped;
			
			for (int i=0;i<kVisibleListCount;i++)
				CullDirectionalShadows (visibleRenderers.visible[i], rendererCullData[i].nodes, rendererCullData[i].bounds, context);
		}
			break;
	}
}

void CullShadowCasters (const Light& light, const ShadowCullData& cullData, bool excludeLightmapped, CullingOutput& cullingOutput )
{
	LightType lightType = light.GetType();
	
	if (lightType == kLightPoint)
	{
		PROFILER_BEGIN(gShadowsCullCastersPoint,&light)
	}
	else if (lightType == kLightSpot)
	{
		PROFILER_BEGIN(gShadowsCullCastersSpot,&light)
	}
	else
	{
		PROFILER_BEGIN(gShadowsCullCastersDir,&light)
	}
	
	const Transform& lt = light.GetComponent (Transform);
	ShadowCasterCull casterCull;
	
	CalculateShadowCasterCull( cullData.shadowCullPlanes, cullData.cameraClipToWorld, cullData.eyePos,
							  1.0, cullData.farPlaneScale, lightType, lt, casterCull );
	
	SceneCullingParameters cullParams = *cullData.sceneCullParameters;
	cullData.camera->CalculateCustomCullingParameters(cullParams, casterCull.planes, casterCull.planeCount);
	
	if (lightType == kLightDirectional)
	{
		Vector3f lightDir = lt.TransformDirection (Vector3f(0,0,-1));
		cullParams.lightDir = lightDir;
	}
	
	if (cullParams.useShadowCasterCulling && (lightType == kLightDirectional))
	{
		CullShadowCastersWithUmbra(cullParams, cullingOutput);
	}
	else
	{
		CullSceneWithoutUmbra (cullParams, cullingOutput);
	}
	
	
	CullShadowCastersDetail (light, cullData, excludeLightmapped, cullingOutput);
	
	PROFILER_END
}


void GenerateShadowCasterParts (const Light& light, const ShadowCullData& cullData, const CullingOutput& visibleRenderers, MinMaxAABB& casterBounds, ShadowCasters& casters, ShadowCasterParts& casterParts)
{
	const bool isDirectionalLight = light.GetType() == kLightDirectional;
	
	const RendererCullData* rendererCullData = cullData.sceneCullParameters->renderers;
	for (int t=0;t<kVisibleListCount;t++)
	{
		const IndexList& visibleList = visibleRenderers.visible[t];
		const RendererCullData& renderLists = rendererCullData[t];
		for (int i=0;i<visibleList.size;i++)
		{
			int renderIndex = visibleList[i];
			bool casterTouchesView = false;
			if (isDirectionalLight)
			{
				// Only compute caster AABB for casters that touch the view frustum.
				// Other casters might be valid casters, but behind near plane of resulting
				// shadow camera. This is ok, we manually push those onto near plane in caster vertex shader.
				//
				// If we'd bound all casters we get the issue of insufficient depth precision when some caster
				// has a valid caster, but is waaay far away (50000 units or so).
				casterTouchesView = IntersectAABBFrustumFull( renderLists.bounds[renderIndex], cullData.cameraCullPlanes );
			}
			
			// Last argument expandCasterBounds should be false for point lights as they don't use casterBounds to adjust shadow map view
			AddShadowCaster( renderLists.nodes[renderIndex], renderLists.bounds[renderIndex], cullData, casterTouchesView, casterBounds, casters, casterParts );
		}
	}
}



/*
 
 static bool CullCastersDirectional( DirectionalCullContext* context, const SceneNode& node, const AABB& aabb, float lodFade )
 {
 if (!CullCastersCommon(*context, node, aabb))
 return false;
 
 // Only compute caster AABB for casters that touch the view frustum.
 // Other casters might be valid casters, but behind near plane of resulting
 // shadow camera. This is ok, we manually push those onto near plane in caster vertex shader.
 //
 // If we'd bound all casters we get the issue of insufficient depth precision when some caster
 // has a valid caster, but is waaay far away (50000 units or so).
 bool casterTouchesView = IntersectAABBFrustumFull( aabb, context->camera->cameraCullPlanes );
 AddShadowCaster( node, aabb, *context, casterTouchesView );
 return true;
 }
 
 
 */



struct Circle2f
{
	Vector2f center;
	float radius;
};

void CullDirectionalCascades(ShadowCasters& casters, const ShadowCascadeInfo cascades[kMaxShadowCascades], int cascadeCount,
									const Quaternionf& lightRot, const Vector3f& lightDir, const ShadowCullData& cullData)
{
	Assert(cascadeCount <= kMaxShadowCascades);
	const QualitySettings::QualitySetting& quality = GetQualitySettings().GetCurrent();
	if (quality.shadowProjection == kShadowProjCloseFit && cascadeCount == 1)
	{
		// We already culled casters for one non-spherical cascade
		return;
	}
	const Camera& camera = *cullData.camera;

	// Split frustums extruded towards light
	ShadowCasterCull cullPlanes[kMaxShadowCascades];

	// Only objects inside a cylinder can cast shadows onto a sphere
	// We cull in light space so the cylinders become circles
	Circle2f cullCylinders[kMaxShadowCascades];

	Matrix4x4f lightMat;
	QuaternionToMatrix(lightRot, lightMat);

	for (int casc = 0; casc < cascadeCount; casc++)
	{
		const ShadowCascadeInfo& cascade = cascades[casc];
		if (!cascade.enabled)
			continue;
		if (quality.shadowProjection == kShadowProjStableFit)
		{
			// We use spherical splits so cull against a cylinder
			const Vector3f& centerWorld = cascade.outerSphere.GetCenter();
			cullCylinders[casc].center.x = Dot(centerWorld, lightMat.GetAxisX());
			cullCylinders[casc].center.y = Dot(centerWorld, lightMat.GetAxisY());
			cullCylinders[casc].radius = cascade.outerSphere.GetRadius();
		}
		if (cascadeCount == 1)
		{
			// We have already culled against non-cascaded frustum
			cullPlanes[casc].planeCount = 0;
			continue;
		}

		bool alreadyTested[kPlaneFrustumNum];
		for (int p = 0; p < kPlaneFrustumNear; p++)
			alreadyTested[p] = true;
		alreadyTested[kPlaneFrustumNear] = (casc == 0);
		alreadyTested[kPlaneFrustumFar] = ((casc + 1) == cascadeCount);

		Plane splitPlanes[kPlaneFrustumNum];
		memcpy(splitPlanes, cullData.shadowCullPlanes, sizeof(splitPlanes));
		splitPlanes[kPlaneFrustumNear].distance += cascade.minViewDistance - camera.GetNear();
		splitPlanes[kPlaneFrustumFar].distance += cascade.maxViewDistance - cullData.shadowDistance;
		float nearPlaneScale = cascade.minViewDistance / cullData.projectionNear;
		float farPlaneScale = cascade.maxViewDistance / cullData.projectionFar;
		CalculateShadowCasterCull(splitPlanes, cullData.cameraClipToWorld, cullData.eyePos,
			nearPlaneScale, farPlaneScale, kLightDirectional, lightDir, cullPlanes[casc], alreadyTested);
	}

	UInt32 allVisible = 0;
	for (int casc = 0; casc < cascadeCount; casc++)
		allVisible = (allVisible << 1) | 1;

	// Go over casters and determine in which cascades they are visible
	int casterCount = casters.size();
	for (int i = 0; i < casterCount; i++)
	{
		ShadowCasterData& caster = casters[i];
		const AABB& bounds = *caster.worldAABB;
		caster.visibleCascades = allVisible;
		UInt32 currentCascadeMask = 1;

		if (quality.shadowProjection == kShadowProjStableFit)
		{
			float casterRadius = Magnitude(bounds.GetExtent());
			Vector2f lightSpaceCenter;
			lightSpaceCenter.x = Dot(bounds.GetCenter(), lightMat.GetAxisX());
			lightSpaceCenter.y = Dot(bounds.GetCenter(), lightMat.GetAxisY());
			currentCascadeMask = 1;
			for (int casc = 0; casc < cascadeCount; casc++, currentCascadeMask <<= 1)
			{
				if (!cascades[casc].enabled)
					continue;
				// Do the caster bounds and cascade intersect in light space?
				Vector2f vec = lightSpaceCenter - cullCylinders[casc].center;
				float sqrDist = Sqr(vec.x) + Sqr(vec.y);
				float cullRadius = cullCylinders[casc].radius;
				if (sqrDist > Sqr(casterRadius + cullRadius))
				{
					// Circles do not intersect, mark as invisible
					caster.visibleCascades &= ~currentCascadeMask;
				}
			}
		}

		if (cascadeCount > 1)
		{
			currentCascadeMask = 1;
			for (int casc = 0; casc < cascadeCount; casc++, currentCascadeMask <<= 1)
			{
				if (!cascades[casc].enabled)
					continue;
				// Did we already cull this?
				if (caster.visibleCascades & currentCascadeMask)
				{
					if (!IntersectAABBPlaneBounds(bounds, cullPlanes[casc].planes, cullPlanes[casc].planeCount))
					{
						// Outside cull planes, mark this as invisible
						caster.visibleCascades &= ~currentCascadeMask;
					}
				}
			}
		}
	}
}

bool IsObjectWithinShadowRange (const ShadowCullData& shadowCullData, const AABB& bounds)
{
	if (shadowCullData.useSphereCulling)
	{
		float sqrDist = SqrMagnitude(bounds.GetCenter() - shadowCullData.shadowCullCenter);
		if (sqrDist < shadowCullData.shadowCullSquareRadius)
			return true;
		Sphere sphere(shadowCullData.shadowCullCenter, shadowCullData.shadowCullRadius);
		return IntersectAABBSphere(bounds, sphere);
	}
	else
	{
		return IntersectAABBPlaneBounds(bounds, &shadowCullData.shadowCullPlanes[kPlaneFrustumFar], 1);
	}
}