-
Notifications
You must be signed in to change notification settings - Fork 170
/
SEGI.cs
1262 lines (994 loc) · 40.3 KB
/
SEGI.cs
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
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections;
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[ExecuteInEditMode]
#if UNITY_5_4_OR_NEWER
[ImageEffectAllowedInSceneView]
#endif
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Sonic Ether/SEGI")]
public class SEGI : MonoBehaviour
{
#region Parameters
[Serializable]
public enum VoxelResolution
{
low = 128,
high = 256
}
public bool updateGI = true;
public LayerMask giCullingMask = 2147483647;
public float shadowSpaceSize = 50.0f;
public Light sun;
public Color skyColor;
public float voxelSpaceSize = 25.0f;
public bool useBilateralFiltering = false;
[Range(0, 2)]
public int innerOcclusionLayers = 1;
[Range(0.01f, 1.0f)]
public float temporalBlendWeight = 0.1f;
public VoxelResolution voxelResolution = VoxelResolution.high;
public bool visualizeSunDepthTexture = false;
public bool visualizeGI = false;
public bool visualizeVoxels = false;
public bool halfResolution = true;
public bool stochasticSampling = true;
public bool infiniteBounces = false;
public Transform followTransform;
[Range(1, 128)]
public int cones = 6;
[Range(1, 32)]
public int coneTraceSteps = 14;
[Range(0.1f, 2.0f)]
public float coneLength = 1.0f;
[Range(0.5f, 6.0f)]
public float coneWidth = 5.5f;
[Range(0.0f, 4.0f)]
public float occlusionStrength = 1.0f;
[Range(0.0f, 4.0f)]
public float nearOcclusionStrength = 0.5f;
[Range(0.001f, 4.0f)]
public float occlusionPower = 1.5f;
[Range(0.0f, 4.0f)]
public float coneTraceBias = 1.0f;
[Range(0.0f, 4.0f)]
public float nearLightGain = 1.0f;
[Range(0.0f, 4.0f)]
public float giGain = 1.0f;
[Range(0.0f, 4.0f)]
public float secondaryBounceGain = 1.0f;
[Range(0.0f, 16.0f)]
public float softSunlight = 0.0f;
[Range(0.0f, 8.0f)]
public float skyIntensity = 1.0f;
public bool doReflections = true;
[Range(12, 128)]
public int reflectionSteps = 64;
[Range(0.001f, 4.0f)]
public float reflectionOcclusionPower = 1.0f;
[Range(0.0f, 1.0f)]
public float skyReflectionIntensity = 1.0f;
public bool voxelAA = false;
public bool gaussianMipFilter = false;
[Range(0.1f, 4.0f)]
public float farOcclusionStrength = 1.0f;
[Range(0.1f, 4.0f)]
public float farthestOcclusionStrength = 1.0f;
[Range(3, 16)]
public int secondaryCones = 6;
[Range(0.1f, 4.0f)]
public float secondaryOcclusionStrength = 1.0f;
public bool sphericalSkylight = false;
#endregion
#region InternalVariables
object initChecker;
Material material;
Camera attachedCamera;
Transform shadowCamTransform;
Camera shadowCam;
GameObject shadowCamGameObject;
Texture2D[] blueNoise;
int sunShadowResolution = 256;
int prevSunShadowResolution;
Shader sunDepthShader;
float shadowSpaceDepthRatio = 10.0f;
int frameCounter = 0;
RenderTexture sunDepthTexture;
RenderTexture previousGIResult;
RenderTexture previousCameraDepth;
///<summary>This is a volume texture that is immediately written to in the voxelization shader. The RInt format enables atomic writes to avoid issues where multiple fragments are trying to write to the same voxel in the volume.</summary>
RenderTexture integerVolume;
///<summary>An array of volume textures where each element is a mip/LOD level. Each volume is half the resolution of the previous volume. Separate textures for each mip level are required for manual mip-mapping of the main GI volume texture.</summary>
RenderTexture[] volumeTextures;
///<summary>The secondary volume texture that holds irradiance calculated during the in-volume GI tracing that occurs when Infinite Bounces is enabled. </summary>
RenderTexture secondaryIrradianceVolume;
///<summary>The alternate mip level 0 main volume texture needed to avoid simultaneous read/write errors while performing temporal stabilization on the main voxel volume.</summary>
RenderTexture volumeTextureB;
///<summary>The current active volume texture that holds GI information to be read during GI tracing.</summary>
RenderTexture activeVolume;
///<summary>The volume texture that holds GI information to be read during GI tracing that was used in the previous frame.</summary>
RenderTexture previousActiveVolume;
///<summary>A 2D texture with the size of [voxel resolution, voxel resolution] that must be used as the active render texture when rendering the scene for voxelization. This texture scales depending on whether Voxel AA is enabled to ensure correct voxelization.</summary>
RenderTexture dummyVoxelTextureAAScaled;
///<summary>A 2D texture with the size of [voxel resolution, voxel resolution] that must be used as the active render texture when rendering the scene for voxelization. This texture is always the same size whether Voxel AA is enabled or not.</summary>
RenderTexture dummyVoxelTextureFixed;
bool notReadyToRender = false;
Shader voxelizationShader;
Shader voxelTracingShader;
ComputeShader clearCompute;
ComputeShader transferIntsCompute;
ComputeShader mipFilterCompute;
const int numMipLevels = 6;
Camera voxelCamera;
GameObject voxelCameraGO;
GameObject leftViewPoint;
GameObject topViewPoint;
float voxelScaleFactor
{
get
{
return (float)voxelResolution / 256.0f;
}
}
Vector3 voxelSpaceOrigin;
Vector3 previousVoxelSpaceOrigin;
Vector3 voxelSpaceOriginDelta;
Quaternion rotationFront = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);
Quaternion rotationLeft = new Quaternion(0.0f, 0.7f, 0.0f, 0.7f);
Quaternion rotationTop = new Quaternion(0.7f, 0.0f, 0.0f, 0.7f);
int voxelFlipFlop = 0;
enum RenderState
{
Voxelize,
Bounce
}
RenderState renderState = RenderState.Voxelize;
#endregion
#region SupportingObjectsAndProperties
struct Pass
{
public static int DiffuseTrace = 0;
public static int BilateralBlur = 1;
public static int BlendWithScene = 2;
public static int TemporalBlend = 3;
public static int SpecularTrace = 4;
public static int GetCameraDepthTexture = 5;
public static int GetWorldNormals = 6;
public static int VisualizeGI = 7;
public static int WriteBlack = 8;
public static int VisualizeVoxels = 10;
public static int BilateralUpsample = 11;
}
public struct SystemSupported
{
public bool hdrTextures;
public bool rIntTextures;
public bool dx11;
public bool volumeTextures;
public bool postShader;
public bool sunDepthShader;
public bool voxelizationShader;
public bool tracingShader;
public bool fullFunctionality
{
get
{
return hdrTextures && rIntTextures && dx11 && volumeTextures && postShader && sunDepthShader && voxelizationShader && tracingShader;
}
}
}
/// <summary>
/// Contains info on system compatibility of required hardware functionality
/// </summary>
public SystemSupported systemSupported;
/// <summary>
/// Estimates the VRAM usage of all the render textures used to render GI.
/// </summary>
public float vramUsage
{
get
{
long v = 0;
if (sunDepthTexture != null)
v += sunDepthTexture.width * sunDepthTexture.height * 16;
if (previousGIResult != null)
v += previousGIResult.width * previousGIResult.height * 16 * 4;
if (previousCameraDepth != null)
v += previousCameraDepth.width * previousCameraDepth.height * 32;
if (integerVolume != null)
v += integerVolume.width * integerVolume.height * integerVolume.volumeDepth * 32;
if (volumeTextures != null)
{
for (int i = 0; i < volumeTextures.Length; i++)
{
if (volumeTextures[i] != null)
v += volumeTextures[i].width * volumeTextures[i].height * volumeTextures[i].volumeDepth * 16 * 4;
}
}
if (secondaryIrradianceVolume != null)
v += secondaryIrradianceVolume.width * secondaryIrradianceVolume.height * secondaryIrradianceVolume.volumeDepth * 16 * 4;
if (volumeTextureB != null)
v += volumeTextureB.width * volumeTextureB.height * volumeTextureB.volumeDepth * 16 * 4;
if (dummyVoxelTextureAAScaled != null)
v += dummyVoxelTextureAAScaled.width * dummyVoxelTextureAAScaled.height * 8;
if (dummyVoxelTextureFixed != null)
v += dummyVoxelTextureFixed.width * dummyVoxelTextureFixed.height * 8;
float vram = (v / 8388608.0f);
return vram;
}
}
int mipFilterKernel
{
get
{
return gaussianMipFilter ? 1 : 0;
}
}
int dummyVoxelResolution
{
get
{
return (int)voxelResolution * (voxelAA ? 2 : 1);
}
}
int giRenderRes
{
get
{
return halfResolution ? 2 : 1;
}
}
#endregion
///<summary>Applies an SEGIPreset to this instance of SEGI.</summary>
public void ApplyPreset(SEGIPreset preset)
{
voxelResolution = preset.voxelResolution;
voxelAA = preset.voxelAA;
innerOcclusionLayers = preset.innerOcclusionLayers;
infiniteBounces = preset.infiniteBounces;
temporalBlendWeight = preset.temporalBlendWeight;
useBilateralFiltering = preset.useBilateralFiltering;
halfResolution = preset.halfResolution;
stochasticSampling = preset.stochasticSampling;
doReflections = preset.doReflections;
cones = preset.cones;
coneTraceSteps = preset.coneTraceSteps;
coneLength = preset.coneLength;
coneWidth = preset.coneWidth;
coneTraceBias = preset.coneTraceBias;
occlusionStrength = preset.occlusionStrength;
nearOcclusionStrength = preset.nearOcclusionStrength;
occlusionPower = preset.occlusionPower;
nearLightGain = preset.nearLightGain;
giGain = preset.giGain;
secondaryBounceGain = preset.secondaryBounceGain;
reflectionSteps = preset.reflectionSteps;
reflectionOcclusionPower = preset.reflectionOcclusionPower;
skyReflectionIntensity = preset.skyReflectionIntensity;
gaussianMipFilter = preset.gaussianMipFilter;
farOcclusionStrength = preset.farOcclusionStrength;
farthestOcclusionStrength = preset.farthestOcclusionStrength;
secondaryCones = preset.secondaryCones;
secondaryOcclusionStrength = preset.secondaryOcclusionStrength;
}
void Start()
{
InitCheck();
}
void InitCheck()
{
if (initChecker == null)
{
Init();
}
}
void CreateVolumeTextures()
{
if (volumeTextures != null)
{
for (int i = 0; i < numMipLevels; i++)
{
if (volumeTextures[i] != null) {
volumeTextures[i].DiscardContents();
volumeTextures[i].Release();
DestroyImmediate(volumeTextures[i]);
}
}
}
volumeTextures = new RenderTexture[numMipLevels];
for (int i = 0; i < numMipLevels; i++)
{
int resolution = (int)voxelResolution / Mathf.RoundToInt(Mathf.Pow((float)2, (float)i));
volumeTextures[i] = new RenderTexture(resolution, resolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
#if UNITY_5_4_OR_NEWER
volumeTextures[i].dimension = TextureDimension.Tex3D;
#else
volumeTextures[i].isVolume = true;
#endif
volumeTextures[i].volumeDepth = resolution;
volumeTextures[i].enableRandomWrite = true;
volumeTextures[i].filterMode = FilterMode.Bilinear;
#if UNITY_5_4_OR_NEWER
volumeTextures[i].autoGenerateMips = false;
#else
volumeTextures[i].generateMips = false;
#endif
volumeTextures[i].useMipMap = false;
volumeTextures[i].Create();
volumeTextures[i].hideFlags = HideFlags.HideAndDontSave;
}
if (volumeTextureB)
{
volumeTextureB.DiscardContents();
volumeTextureB.Release();
DestroyImmediate(volumeTextureB);
}
volumeTextureB = new RenderTexture((int)voxelResolution, (int)voxelResolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
#if UNITY_5_4_OR_NEWER
volumeTextureB.dimension = TextureDimension.Tex3D;
#else
volumeTextureB.isVolume = true;
#endif
volumeTextureB.volumeDepth = (int)voxelResolution;
volumeTextureB.enableRandomWrite = true;
volumeTextureB.filterMode = FilterMode.Bilinear;
#if UNITY_5_4_OR_NEWER
volumeTextureB.autoGenerateMips = false;
#else
volumeTextureB.generateMips = false;
#endif
volumeTextureB.useMipMap = false;
volumeTextureB.Create();
volumeTextureB.hideFlags = HideFlags.HideAndDontSave;
if (secondaryIrradianceVolume)
{
secondaryIrradianceVolume.DiscardContents();
secondaryIrradianceVolume.Release();
DestroyImmediate(secondaryIrradianceVolume);
}
secondaryIrradianceVolume = new RenderTexture((int)voxelResolution, (int)voxelResolution, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
#if UNITY_5_4_OR_NEWER
secondaryIrradianceVolume.dimension = TextureDimension.Tex3D;
#else
secondaryIrradianceVolume.isVolume = true;
#endif
secondaryIrradianceVolume.volumeDepth = (int)voxelResolution;
secondaryIrradianceVolume.enableRandomWrite = true;
secondaryIrradianceVolume.filterMode = FilterMode.Point;
#if UNITY_5_4_OR_NEWER
secondaryIrradianceVolume.autoGenerateMips = false;
#else
secondaryIrradianceVolume.generateMips = false;
#endif
secondaryIrradianceVolume.useMipMap = false;
secondaryIrradianceVolume.antiAliasing = 1;
secondaryIrradianceVolume.Create();
secondaryIrradianceVolume.hideFlags = HideFlags.HideAndDontSave;
if (integerVolume)
{
integerVolume.DiscardContents();
integerVolume.Release();
DestroyImmediate(integerVolume);
}
integerVolume = new RenderTexture((int)voxelResolution, (int)voxelResolution, 0, RenderTextureFormat.RInt, RenderTextureReadWrite.Linear);
#if UNITY_5_4_OR_NEWER
integerVolume.dimension = TextureDimension.Tex3D;
#else
integerVolume.isVolume = true;
#endif
integerVolume.volumeDepth = (int)voxelResolution;
integerVolume.enableRandomWrite = true;
integerVolume.filterMode = FilterMode.Point;
integerVolume.Create();
integerVolume.hideFlags = HideFlags.HideAndDontSave;
ResizeDummyTexture();
}
void ResizeDummyTexture()
{
if (dummyVoxelTextureAAScaled)
{
dummyVoxelTextureAAScaled.DiscardContents();
dummyVoxelTextureAAScaled.Release();
DestroyImmediate(dummyVoxelTextureAAScaled);
}
dummyVoxelTextureAAScaled = new RenderTexture(dummyVoxelResolution, dummyVoxelResolution, 0, RenderTextureFormat.R8);
dummyVoxelTextureAAScaled.Create();
dummyVoxelTextureAAScaled.hideFlags = HideFlags.HideAndDontSave;
if (dummyVoxelTextureFixed)
{
dummyVoxelTextureFixed.DiscardContents();
dummyVoxelTextureFixed.Release();
DestroyImmediate(dummyVoxelTextureFixed);
}
dummyVoxelTextureFixed = new RenderTexture((int)voxelResolution, (int)voxelResolution, 0, RenderTextureFormat.R8);
dummyVoxelTextureFixed.Create();
dummyVoxelTextureFixed.hideFlags = HideFlags.HideAndDontSave;
}
void Init()
{
//Setup shaders and materials
sunDepthShader = Shader.Find("Hidden/SEGIRenderSunDepth");
clearCompute = Resources.Load("SEGIClear") as ComputeShader;
transferIntsCompute = Resources.Load("SEGITransferInts") as ComputeShader;
mipFilterCompute = Resources.Load("SEGIMipFilter") as ComputeShader;
voxelizationShader = Shader.Find("Hidden/SEGIVoxelizeScene");
voxelTracingShader = Shader.Find("Hidden/SEGITraceScene");
if (!material) {
material = new Material(Shader.Find("Hidden/SEGI"));
material.hideFlags = HideFlags.HideAndDontSave;
}
//Get the camera attached to this game object
attachedCamera = this.GetComponent<Camera>();
attachedCamera.depthTextureMode |= DepthTextureMode.Depth;
#if UNITY_5_4_OR_NEWER
attachedCamera.depthTextureMode |= DepthTextureMode.MotionVectors;
#endif
//Find the proxy shadow rendering camera if it exists
GameObject scgo = GameObject.Find("SEGI_SHADOWCAM");
//If not, create it
if (!scgo)
{
shadowCamGameObject = new GameObject("SEGI_SHADOWCAM");
shadowCam = shadowCamGameObject.AddComponent<Camera>();
shadowCamGameObject.hideFlags = HideFlags.HideAndDontSave;
shadowCam.enabled = false;
shadowCam.depth = attachedCamera.depth - 1;
shadowCam.orthographic = true;
shadowCam.orthographicSize = shadowSpaceSize;
shadowCam.clearFlags = CameraClearFlags.SolidColor;
shadowCam.backgroundColor = new Color(0.0f, 0.0f, 0.0f, 1.0f);
shadowCam.farClipPlane = shadowSpaceSize * 2.0f * shadowSpaceDepthRatio;
shadowCam.cullingMask = giCullingMask;
shadowCam.useOcclusionCulling = false;
shadowCamTransform = shadowCamGameObject.transform;
}
else //Otherwise, it already exists, just get it
{
shadowCamGameObject = scgo;
shadowCam = scgo.GetComponent<Camera>();
shadowCamTransform = shadowCamGameObject.transform;
}
//Create the proxy camera objects responsible for rendering the scene to voxelize the scene. If they already exist, destroy them
GameObject vcgo = GameObject.Find("SEGI_VOXEL_CAMERA");
if (!vcgo) {
voxelCameraGO = new GameObject("SEGI_VOXEL_CAMERA");
voxelCameraGO.hideFlags = HideFlags.HideAndDontSave;
voxelCamera = voxelCameraGO.AddComponent<Camera>();
voxelCamera.enabled = false;
voxelCamera.orthographic = true;
voxelCamera.orthographicSize = voxelSpaceSize * 0.5f;
voxelCamera.nearClipPlane = 0.0f;
voxelCamera.farClipPlane = voxelSpaceSize;
voxelCamera.depth = -2;
voxelCamera.renderingPath = RenderingPath.Forward;
voxelCamera.clearFlags = CameraClearFlags.Color;
voxelCamera.backgroundColor = Color.black;
voxelCamera.useOcclusionCulling = false;
}
else
{
voxelCameraGO = vcgo;
voxelCamera = vcgo.GetComponent<Camera>();
}
GameObject lvp = GameObject.Find("SEGI_LEFT_VOXEL_VIEW");
if (!lvp) {
leftViewPoint = new GameObject("SEGI_LEFT_VOXEL_VIEW");
leftViewPoint.hideFlags = HideFlags.HideAndDontSave;
}
else
{
leftViewPoint = lvp;
}
GameObject tvp = GameObject.Find("SEGI_TOP_VOXEL_VIEW");
if (!tvp) {
topViewPoint = new GameObject("SEGI_TOP_VOXEL_VIEW");
topViewPoint.hideFlags = HideFlags.HideAndDontSave;
}
else
{
topViewPoint = tvp;
}
//Get blue noise textures
blueNoise = null;
blueNoise = new Texture2D[64];
for (int i = 0; i < 64; i++)
{
string fileName = "LDR_RGBA_" + i.ToString();
Texture2D blueNoiseTexture = Resources.Load("Noise Textures/" + fileName) as Texture2D;
if (blueNoiseTexture == null)
{
Debug.LogWarning("Unable to find noise texture \"Assets/SEGI/Resources/Noise Textures/" + fileName + "\" for SEGI!");
}
blueNoise[i] = blueNoiseTexture;
}
//Setup sun depth texture
if (sunDepthTexture)
{
sunDepthTexture.DiscardContents();
sunDepthTexture.Release();
DestroyImmediate(sunDepthTexture);
}
sunDepthTexture = new RenderTexture(sunShadowResolution, sunShadowResolution, 16, RenderTextureFormat.RHalf, RenderTextureReadWrite.Linear);
sunDepthTexture.wrapMode = TextureWrapMode.Clamp;
sunDepthTexture.filterMode = FilterMode.Point;
sunDepthTexture.Create();
sunDepthTexture.hideFlags = HideFlags.HideAndDontSave;
//Create the volume textures
CreateVolumeTextures();
initChecker = new object();
}
void CheckSupport()
{
systemSupported.hdrTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf);
systemSupported.rIntTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RInt);
systemSupported.dx11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders;
systemSupported.volumeTextures = SystemInfo.supports3DTextures;
systemSupported.postShader = material.shader.isSupported;
systemSupported.sunDepthShader = sunDepthShader.isSupported;
systemSupported.voxelizationShader = voxelizationShader.isSupported;
systemSupported.tracingShader = voxelTracingShader.isSupported;
if (!systemSupported.fullFunctionality)
{
Debug.LogWarning("SEGI is not supported on the current platform. Check for shader compile errors in SEGI/Resources");
enabled = false;
}
}
void OnDrawGizmosSelected()
{
if (!enabled)
return;
Color prevColor = Gizmos.color;
Gizmos.color = new Color(1.0f, 0.25f, 0.0f, 0.5f);
Gizmos.DrawCube(voxelSpaceOrigin, new Vector3(voxelSpaceSize, voxelSpaceSize, voxelSpaceSize));
Gizmos.color = new Color(1.0f, 0.0f, 0.0f, 0.1f);
Gizmos.color = prevColor;
}
void CleanupTexture(ref RenderTexture texture)
{
if (texture)
{
texture.DiscardContents();
texture.Release();
DestroyImmediate(texture);
}
}
void CleanupTextures()
{
CleanupTexture(ref sunDepthTexture);
CleanupTexture(ref previousGIResult);
CleanupTexture(ref previousCameraDepth);
CleanupTexture(ref integerVolume);
for (int i = 0; i < volumeTextures.Length; i++)
{
CleanupTexture(ref volumeTextures[i]);
}
CleanupTexture(ref secondaryIrradianceVolume);
CleanupTexture(ref volumeTextureB);
CleanupTexture(ref dummyVoxelTextureAAScaled);
CleanupTexture(ref dummyVoxelTextureFixed);
}
void Cleanup()
{
DestroyImmediate(material);
DestroyImmediate(voxelCameraGO);
DestroyImmediate(leftViewPoint);
DestroyImmediate(topViewPoint);
DestroyImmediate(shadowCamGameObject);
initChecker = null;
CleanupTextures();
}
void OnEnable()
{
InitCheck();
ResizeRenderTextures();
CheckSupport();
}
void OnDisable()
{
Cleanup();
}
void ResizeRenderTextures()
{
if (previousGIResult)
{
previousGIResult.DiscardContents();
previousGIResult.Release();
DestroyImmediate(previousGIResult);
}
int width = attachedCamera.pixelWidth == 0 ? 2 : attachedCamera.pixelWidth;
int height = attachedCamera.pixelHeight == 0 ? 2 : attachedCamera.pixelHeight;
previousGIResult = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBHalf);
previousGIResult.wrapMode = TextureWrapMode.Clamp;
previousGIResult.filterMode = FilterMode.Bilinear;
previousGIResult.useMipMap = true;
#if UNITY_5_4_OR_NEWER
previousGIResult.autoGenerateMips = false;
#else
previousResult.generateMips = false;
#endif
previousGIResult.Create();
previousGIResult.hideFlags = HideFlags.HideAndDontSave;
if (previousCameraDepth)
{
previousCameraDepth.DiscardContents();
previousCameraDepth.Release();
DestroyImmediate(previousCameraDepth);
}
previousCameraDepth = new RenderTexture(width, height, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear);
previousCameraDepth.wrapMode = TextureWrapMode.Clamp;
previousCameraDepth.filterMode = FilterMode.Bilinear;
previousCameraDepth.Create();
previousCameraDepth.hideFlags = HideFlags.HideAndDontSave;
}
void ResizeSunShadowBuffer()
{
if (sunDepthTexture)
{
sunDepthTexture.DiscardContents();
sunDepthTexture.Release();
DestroyImmediate(sunDepthTexture);
}
sunDepthTexture = new RenderTexture(sunShadowResolution, sunShadowResolution, 16, RenderTextureFormat.RHalf, RenderTextureReadWrite.Linear);
sunDepthTexture.wrapMode = TextureWrapMode.Clamp;
sunDepthTexture.filterMode = FilterMode.Point;
sunDepthTexture.Create();
sunDepthTexture.hideFlags = HideFlags.HideAndDontSave;
}
void Update()
{
if (notReadyToRender)
return;
if (previousGIResult == null)
{
ResizeRenderTextures();
}
if (previousGIResult.width != attachedCamera.pixelWidth || previousGIResult.height != attachedCamera.pixelHeight)
{
ResizeRenderTextures();
}
if ((int)sunShadowResolution != prevSunShadowResolution)
{
ResizeSunShadowBuffer();
}
prevSunShadowResolution = (int)sunShadowResolution;
if (volumeTextures[0].width != (int)voxelResolution)
{
CreateVolumeTextures();
}
if (dummyVoxelTextureAAScaled.width != dummyVoxelResolution)
{
ResizeDummyTexture();
}
}
Matrix4x4 TransformViewMatrix(Matrix4x4 mat)
{
//Since the third column of the view matrix needs to be reversed if using reversed z-buffer, do so here
#if UNITY_5_5_OR_NEWER
if (SystemInfo.usesReversedZBuffer)
{
mat[2, 0] = -mat[2, 0];
mat[2, 1] = -mat[2, 1];
mat[2, 2] = -mat[2, 2];
mat[2, 3] = -mat[2, 3];
}
#endif
return mat;
}
void OnPreRender()
{
//Force reinitialization to make sure that everything is working properly if one of the cameras was unexpectedly destroyed
if (!voxelCamera || !shadowCam)
initChecker = null;
InitCheck();
if (notReadyToRender)
return;
if (!updateGI)
{
return;
}
//Cache the previous active render texture to avoid issues with other Unity rendering going on
RenderTexture previousActive = RenderTexture.active;
Shader.SetGlobalInt("SEGIVoxelAA", voxelAA ? 1 : 0);
//Main voxelization work
if (renderState == RenderState.Voxelize)
{
activeVolume = voxelFlipFlop == 0 ? volumeTextures[0] : volumeTextureB; //Flip-flopping volume textures to avoid simultaneous read and write errors in shaders
previousActiveVolume = voxelFlipFlop == 0 ? volumeTextureB : volumeTextures[0];
//float voxelTexel = (1.0f * voxelSpaceSize) / (int)voxelResolution * 0.5f; //Calculate the size of a voxel texel in world-space units
//Setup the voxel volume origin position
float interval = voxelSpaceSize / 8.0f; //The interval at which the voxel volume will be "locked" in world-space
Vector3 origin;
if (followTransform)
{
origin = followTransform.position;
}
else
{
//GI is still flickering a bit when the scene view and the game view are opened at the same time
origin = transform.position + transform.forward * voxelSpaceSize / 4.0f;
}
//Lock the voxel volume origin based on the interval
voxelSpaceOrigin = new Vector3(Mathf.Round(origin.x / interval) * interval, Mathf.Round(origin.y / interval) * interval, Mathf.Round(origin.z / interval) * interval);
//Calculate how much the voxel origin has moved since last voxelization pass. Used for scrolling voxel data in shaders to avoid ghosting when the voxel volume moves in the world
voxelSpaceOriginDelta = voxelSpaceOrigin - previousVoxelSpaceOrigin;
Shader.SetGlobalVector("SEGIVoxelSpaceOriginDelta", voxelSpaceOriginDelta / voxelSpaceSize);
previousVoxelSpaceOrigin = voxelSpaceOrigin;
//Set the voxel camera (proxy camera used to render the scene for voxelization) parameters
voxelCamera.enabled = false;
voxelCamera.orthographic = true;
voxelCamera.orthographicSize = voxelSpaceSize * 0.5f;
voxelCamera.nearClipPlane = 0.0f;
voxelCamera.farClipPlane = voxelSpaceSize;
voxelCamera.depth = -2;
voxelCamera.renderingPath = RenderingPath.Forward;
voxelCamera.clearFlags = CameraClearFlags.Color;
voxelCamera.backgroundColor = Color.black;
voxelCamera.cullingMask = giCullingMask;
//Move the voxel camera game object and other related objects to the above calculated voxel space origin
voxelCameraGO.transform.position = voxelSpaceOrigin - Vector3.forward * voxelSpaceSize * 0.5f;
voxelCameraGO.transform.rotation = rotationFront;
leftViewPoint.transform.position = voxelSpaceOrigin + Vector3.left * voxelSpaceSize * 0.5f;
leftViewPoint.transform.rotation = rotationLeft;
topViewPoint.transform.position = voxelSpaceOrigin + Vector3.up * voxelSpaceSize * 0.5f;
topViewPoint.transform.rotation = rotationTop;
//Set matrices needed for voxelization
Shader.SetGlobalMatrix("WorldToCamera", attachedCamera.worldToCameraMatrix);
Shader.SetGlobalMatrix("SEGIVoxelViewFront", TransformViewMatrix(voxelCamera.transform.worldToLocalMatrix));
Shader.SetGlobalMatrix("SEGIVoxelViewLeft", TransformViewMatrix(leftViewPoint.transform.worldToLocalMatrix));
Shader.SetGlobalMatrix("SEGIVoxelViewTop", TransformViewMatrix(topViewPoint.transform.worldToLocalMatrix));
Shader.SetGlobalMatrix("SEGIWorldToVoxel", voxelCamera.worldToCameraMatrix);
Shader.SetGlobalMatrix("SEGIVoxelProjection", voxelCamera.projectionMatrix);
Shader.SetGlobalMatrix("SEGIVoxelProjectionInverse", voxelCamera.projectionMatrix.inverse);
Shader.SetGlobalInt("SEGIVoxelResolution", (int)voxelResolution);
Matrix4x4 voxelToGIProjection = (shadowCam.projectionMatrix) * (shadowCam.worldToCameraMatrix) * (voxelCamera.cameraToWorldMatrix);
Shader.SetGlobalMatrix("SEGIVoxelToGIProjection", voxelToGIProjection);
Shader.SetGlobalVector("SEGISunlightVector", sun ? Vector3.Normalize(sun.transform.forward) : Vector3.up);
//Set paramteters
Shader.SetGlobalColor("GISunColor", sun == null ? Color.black : new Color(Mathf.Pow(sun.color.r, 2.2f), Mathf.Pow(sun.color.g, 2.2f), Mathf.Pow(sun.color.b, 2.2f), Mathf.Pow(sun.intensity, 2.2f)));
Shader.SetGlobalColor("SEGISkyColor", new Color(Mathf.Pow(skyColor.r * skyIntensity * 0.5f, 2.2f), Mathf.Pow(skyColor.g * skyIntensity * 0.5f, 2.2f), Mathf.Pow(skyColor.b * skyIntensity * 0.5f, 2.2f), Mathf.Pow(skyColor.a, 2.2f)));
Shader.SetGlobalFloat("GIGain", giGain);
Shader.SetGlobalFloat("SEGISecondaryBounceGain", infiniteBounces ? secondaryBounceGain : 0.0f);
Shader.SetGlobalFloat("SEGISoftSunlight", softSunlight);
Shader.SetGlobalInt("SEGISphericalSkylight", sphericalSkylight ? 1 : 0);
Shader.SetGlobalInt("SEGIInnerOcclusionLayers", innerOcclusionLayers);
//Render the depth texture from the sun's perspective in order to inject sunlight with shadows during voxelization
if (sun != null)
{
shadowCam.cullingMask = giCullingMask;
Vector3 shadowCamPosition = voxelSpaceOrigin + Vector3.Normalize(-sun.transform.forward) * shadowSpaceSize * 0.5f * shadowSpaceDepthRatio;
shadowCamTransform.position = shadowCamPosition;
shadowCamTransform.LookAt(voxelSpaceOrigin, Vector3.up);
shadowCam.renderingPath = RenderingPath.Forward;
shadowCam.depthTextureMode |= DepthTextureMode.None;
shadowCam.orthographicSize = shadowSpaceSize;
shadowCam.farClipPlane = shadowSpaceSize * 2.0f * shadowSpaceDepthRatio;
Graphics.SetRenderTarget(sunDepthTexture);
shadowCam.SetTargetBuffers(sunDepthTexture.colorBuffer, sunDepthTexture.depthBuffer);
shadowCam.RenderWithShader(sunDepthShader, "");
Shader.SetGlobalTexture("SEGISunDepth", sunDepthTexture);
}
//Clear the volume texture that is immediately written to in the voxelization scene shader
clearCompute.SetTexture(0, "RG0", integerVolume);
clearCompute.SetInt("Res", (int)voxelResolution);
clearCompute.Dispatch(0, (int)voxelResolution / 16, (int)voxelResolution / 16, 1);
//Render the scene with the voxel proxy camera object with the voxelization shader to voxelize the scene to the volume integer texture
Graphics.SetRandomWriteTarget(1, integerVolume);
voxelCamera.targetTexture = dummyVoxelTextureAAScaled;
voxelCamera.RenderWithShader(voxelizationShader, "");
Graphics.ClearRandomWriteTargets();
//Transfer the data from the volume integer texture to the main volume texture used for GI tracing.
transferIntsCompute.SetTexture(0, "Result", activeVolume);
transferIntsCompute.SetTexture(0, "PrevResult", previousActiveVolume);
transferIntsCompute.SetTexture(0, "RG0", integerVolume);