-
Notifications
You must be signed in to change notification settings - Fork 869
Expand file tree
/
Copy pathPostProcessPassRenderGraph.cs
More file actions
3204 lines (2744 loc) · 162 KB
/
PostProcessPassRenderGraph.cs
File metadata and controls
3204 lines (2744 loc) · 162 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
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
using System;
using System.Runtime.CompilerServices;
namespace UnityEngine.Rendering.Universal
{
internal class PostProcessPassRenderGraph
{
// Precomputed shader ids to same some CPU cycles (mostly affects mobile)
// TODO: move into post-process passes.
internal static class ShaderConstants
{
public static readonly int _CameraDepthTextureID = Shader.PropertyToID("_CameraDepthTexture");
public static readonly int _StencilRef = Shader.PropertyToID("_StencilRef");
public static readonly int _StencilMask = Shader.PropertyToID("_StencilMask");
public static readonly int _ColorTexture = Shader.PropertyToID("_ColorTexture");
public static readonly int _Params = Shader.PropertyToID("_Params");
public static readonly int _Params2 = Shader.PropertyToID("_Params2");
public static readonly int _ViewProjM = Shader.PropertyToID("_ViewProjM");
public static readonly int _PrevViewProjM = Shader.PropertyToID("_PrevViewProjM");
public static readonly int _ViewProjMStereo = Shader.PropertyToID("_ViewProjMStereo");
public static readonly int _PrevViewProjMStereo = Shader.PropertyToID("_PrevViewProjMStereo");
public static readonly int _FullscreenProjMat = Shader.PropertyToID("_FullscreenProjMat");
// DoF
public static readonly int _FullCoCTexture = Shader.PropertyToID("_FullCoCTexture");
public static readonly int _HalfCoCTexture = Shader.PropertyToID("_HalfCoCTexture");
public static readonly int _DofTexture = Shader.PropertyToID("_DofTexture");
public static readonly int _CoCParams = Shader.PropertyToID("_CoCParams");
public static readonly int _BokehKernel = Shader.PropertyToID("_BokehKernel");
public static readonly int _BokehConstants = Shader.PropertyToID("_BokehConstants");
public static readonly int _DownSampleScaleFactor = Shader.PropertyToID("_DownSampleScaleFactor");
// SMAA
public static readonly int _Metrics = Shader.PropertyToID("_Metrics");
public static readonly int _AreaTexture = Shader.PropertyToID("_AreaTexture");
public static readonly int _SearchTexture = Shader.PropertyToID("_SearchTexture");
public static readonly int _BlendTexture = Shader.PropertyToID("_BlendTexture");
//public static readonly int _EdgeTexture = Shader.PropertyToID("_EdgeTexture");
// Bloom
public static readonly int _SourceTexLowMip = Shader.PropertyToID("_SourceTexLowMip");
public static readonly int _Bloom_Params = Shader.PropertyToID("_Bloom_Params");
public static readonly int _Bloom_Texture = Shader.PropertyToID("_Bloom_Texture");
public static readonly int _LensDirt_Texture = Shader.PropertyToID("_LensDirt_Texture");
public static readonly int _LensDirt_Params = Shader.PropertyToID("_LensDirt_Params");
public static readonly int _LensDirt_Intensity = Shader.PropertyToID("_LensDirt_Intensity");
// Uber
public static readonly int _Distortion_Params1 = Shader.PropertyToID("_Distortion_Params1");
public static readonly int _Distortion_Params2 = Shader.PropertyToID("_Distortion_Params2");
public static readonly int _Chroma_Params = Shader.PropertyToID("_Chroma_Params");
public static readonly int _Vignette_Params1 = Shader.PropertyToID("_Vignette_Params1");
public static readonly int _Vignette_Params2 = Shader.PropertyToID("_Vignette_Params2");
public static readonly int _Vignette_ParamsXR = Shader.PropertyToID("_Vignette_ParamsXR");
// Color Lookup-table
public static readonly int _InternalLut = Shader.PropertyToID("_InternalLut");
public static readonly int _Lut_Params = Shader.PropertyToID("_Lut_Params");
public static readonly int _UserLut = Shader.PropertyToID("_UserLut");
public static readonly int _UserLut_Params = Shader.PropertyToID("_UserLut_Params");
}
// TODO: move into post-process passes.
internal static class Constants
{
// Bloom
public const int k_MaxPyramidSize = 16;
// DoF
public const int k_GaussianDoFPassComputeCoc = 0;
public const int k_GaussianDoFPassDownscalePrefilter = 1;
public const int k_GaussianDoFPassBlurH = 2;
public const int k_GaussianDoFPassBlurV = 3;
public const int k_GaussianDoFPassComposite = 4;
public const int k_BokehDoFPassComputeCoc = 0;
public const int k_BokehDoFPassDownscalePrefilter = 1;
public const int k_BokehDoFPassBlur = 2;
public const int k_BokehDoFPassPostFilter = 3;
public const int k_BokehDoFPassComposite = 4;
}
PostProcessMaterialLibrary m_Materials;
// Builtin effects settings (VolumeComponents)
DepthOfField m_DepthOfField;
MotionBlur m_MotionBlur;
PaniniProjection m_PaniniProjection;
Bloom m_Bloom;
ScreenSpaceLensFlare m_LensFlareScreenSpace;
LensDistortion m_LensDistortion;
ChromaticAberration m_ChromaticAberration;
Vignette m_Vignette;
ColorLookup m_ColorLookup;
ColorAdjustments m_ColorAdjustments;
Tonemapping m_Tonemapping;
FilmGrain m_FilmGrain;
// Targets
string[] m_BloomMipDownName;
string[] m_BloomMipUpName;
TextureHandle[] _BloomMipUp;
TextureHandle[] _BloomMipDown;
RTHandle m_UserLut;
RTHandle m_InternalLut;
// SMAA misc.
readonly GraphicsFormat m_SMAAEdgeFormat;
// Bloom misc.
readonly GraphicsFormat m_BloomColorFormat;
// Cached bloom params from previous frame to avoid unnecessary material updates
BloomMaterialParams m_BloomParamsPrev;
// DoF misc.
readonly GraphicsFormat m_GaussianCoCFormat;
readonly GraphicsFormat m_GaussianDoFColorFormat;
// Bokeh DoF misc.
Vector4[] m_BokehKernel;
int m_BokehHash;
// Needed if the device changes its render target width/height (ex, Mobile platform allows change of orientation)
float m_BokehMaxRadius;
float m_BokehRCPAspect;
// Lens Flare misc.
readonly GraphicsFormat m_LensFlareScreenSpaceColorFormat;
// Uber misc.
int m_DitheringTextureIndex; // 8-bit dithering
// If there's a final post process pass after this pass.
// If yes, Film Grain and Dithering are setup in the final pass, otherwise they are setup in this pass.
bool m_HasFinalPass;
// Some Android devices do not support sRGB backbuffer
// We need to do the conversion manually on those
// Also if HDR output is active
bool m_EnableColorEncodingIfNeeded;
// Use Fast conversions between SRGB and Linear
bool m_UseFastSRGBLinearConversion;
// Support Screen Space Lens Flare post process effect
bool m_SupportScreenSpaceLensFlare;
// Support Data Driven Lens Flare post process effect
bool m_SupportDataDrivenLensFlare;
/// <summary>
/// Creates a new <c>PostProcessPass</c> instance.
/// </summary>
/// <param name="data">The <c>PostProcessData</c> resources to use.</param>
/// <param name="requestPostProColorFormat">Requested <c>GraphicsFormat</c> for postprocess rendering.</param>
/// <seealso cref="RenderPassEvent"/>
/// <seealso cref="PostProcessData"/>
/// <seealso cref="PostProcessParams"/>
/// <seealso cref="GraphicsFormat"/>
public PostProcessPassRenderGraph(PostProcessData data, GraphicsFormat requestPostProColorFormat)
{
Assertions.Assert.IsNotNull(data, "PostProcessData and resources cannot be null.");
m_Materials = new PostProcessMaterialLibrary(data);
// Arrays for Bloom pyramid TextureHandle names.
m_BloomMipDownName = new string[Constants.k_MaxPyramidSize];
m_BloomMipUpName = new string[Constants.k_MaxPyramidSize];
for (int i = 0; i < Constants.k_MaxPyramidSize; i++)
{
m_BloomMipUpName[i] = "_BloomMipUp" + i;
m_BloomMipDownName[i] = "_BloomMipDown" + i;
}
// Arrays for Bloom pyramid TextureHandles.
_BloomMipUp = new TextureHandle[Constants.k_MaxPyramidSize];
_BloomMipDown = new TextureHandle[Constants.k_MaxPyramidSize];
// NOTE: Request color format is the back-buffer color format. It can be HDR or SDR (when HDR disabled).
// Request color might have alpha or might not have alpha.
// The actual post-process target can be different. A RenderTexture with a custom format. Not necessarily a back-buffer.
// A RenderTexture with a custom format can have an alpha channel, regardless of the back-buffer setting,
// so the post-processing should just use the current target format/alpha to toggle alpha output.
//
// However, we want to filter out the alpha shader variants when not used (common case).
// The rule is that URP post-processing format follows the back-buffer format setting.
bool requestHDR = IsHDRFormat(requestPostProColorFormat);
//bool requestAlpha = IsAlphaFormat(postProcessParams.requestColorFormat);
GraphicsFormat defaultFormat = GraphicsFormat.None;
// Texture format pre-lookup
// UUM-41070: We require `Linear | Render` but with the deprecated FormatUsage this was checking `Blend`
// For now, we keep checking for `Blend` until the performance hit of doing the correct checks is evaluated
if (requestHDR)
{
const GraphicsFormatUsage usage = GraphicsFormatUsage.Blend;
if (SystemInfo.IsFormatSupported(requestPostProColorFormat, usage)) // Typically, RGBA16Float.
{
defaultFormat = requestPostProColorFormat;
}
else if (SystemInfo.IsFormatSupported(GraphicsFormat.B10G11R11_UFloatPack32, usage)) // HDR fallback
{
// NOTE: Technically request format can be with alpha, however if it's not supported and we fall back here
// , we assume no alpha. Post-process default format follows the back buffer format.
// If support failed, it must have failed for back buffer too.
defaultFormat = GraphicsFormat.B10G11R11_UFloatPack32;
}
else
{
defaultFormat = QualitySettings.activeColorSpace == ColorSpace.Linear
? GraphicsFormat.R8G8B8A8_SRGB
: GraphicsFormat.R8G8B8A8_UNorm;
}
}
else // SDR
{
defaultFormat = QualitySettings.activeColorSpace == ColorSpace.Linear
? GraphicsFormat.R8G8B8A8_SRGB
: GraphicsFormat.R8G8B8A8_UNorm;
}
// Bloom
m_BloomColorFormat = defaultFormat;
// SMAA
// Only two components are needed for edge render texture, but on some vendors four components may be faster.
if (SystemInfo.IsFormatSupported(GraphicsFormat.R8G8_UNorm, GraphicsFormatUsage.Render) && SystemInfo.graphicsDeviceVendor.ToLowerInvariant().Contains("arm"))
m_SMAAEdgeFormat = GraphicsFormat.R8G8_UNorm;
else
m_SMAAEdgeFormat = GraphicsFormat.R8G8B8A8_UNorm;
// Depth of Field
//
// CoC
// UUM-41070: We require `Linear | Render` but with the deprecated FormatUsage this was checking `Blend`
// For now, we keep checking for `Blend` until the performance hit of doing the correct checks is evaluated
if (SystemInfo.IsFormatSupported(GraphicsFormat.R16_UNorm, GraphicsFormatUsage.Blend))
m_GaussianCoCFormat = GraphicsFormat.R16_UNorm;
else if (SystemInfo.IsFormatSupported(GraphicsFormat.R16_SFloat, GraphicsFormatUsage.Blend))
m_GaussianCoCFormat = GraphicsFormat.R16_SFloat;
else // Expect CoC banding
m_GaussianCoCFormat = GraphicsFormat.R8_UNorm;
m_GaussianDoFColorFormat = defaultFormat;
// LensFlare
m_LensFlareScreenSpaceColorFormat = defaultFormat;
}
public void Cleanup()
{
m_Materials.Cleanup();
Dispose();
}
/// <summary>
/// Disposes used resources.
/// </summary>
public void Dispose()
{
m_UserLut?.Release();
}
// NOTE: Duplicate in compatibility mode
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool IsHDRFormat(GraphicsFormat format)
{
return format == GraphicsFormat.B10G11R11_UFloatPack32 ||
GraphicsFormatUtility.IsHalfFormat(format) ||
GraphicsFormatUtility.IsFloatFormat(format);
}
// NOTE: Duplicate in compatibility mode
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool IsAlphaFormat(GraphicsFormat format)
{
return GraphicsFormatUtility.HasAlphaChannel(format);
}
// NOTE: Duplicate in compatibility mode
[MethodImpl(MethodImplOptions.AggressiveInlining)]
bool RequireSRGBConversionBlitToBackBuffer(bool requireSrgbConversion)
{
return requireSrgbConversion && m_EnableColorEncodingIfNeeded;
}
// NOTE: Duplicate in compatibility mode
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool RequireHDROutput(UniversalCameraData cameraData)
{
// If capturing, don't convert to HDR.
// If not last in the stack, don't convert to HDR.
return cameraData.isHDROutputActive && cameraData.captureActions == null;
}
private class UpdateCameraResolutionPassData
{
internal Vector2Int newCameraTargetSize;
}
// Updates render target descriptors and shader constants to reflect a new render size
// This should be called immediately after the resolution changes mid-frame (typically after an upscaling operation).
void UpdateCameraResolution(RenderGraph renderGraph, UniversalCameraData cameraData, Vector2Int newCameraTargetSize)
{
// Update the camera data descriptor to reflect post-upscaled sizes
cameraData.cameraTargetDescriptor.width = newCameraTargetSize.x;
cameraData.cameraTargetDescriptor.height = newCameraTargetSize.y;
// Update the shader constants to reflect the new camera resolution
using (var builder = renderGraph.AddUnsafePass<UpdateCameraResolutionPassData>("Update Camera Resolution", out var passData))
{
passData.newCameraTargetSize = newCameraTargetSize;
// This pass only modifies shader constants
builder.AllowGlobalStateModification(true);
builder.SetRenderFunc(static (UpdateCameraResolutionPassData data, UnsafeGraphContext ctx) =>
{
ctx.cmd.SetGlobalVector(
ShaderPropertyId.screenSize,
new Vector4(
data.newCameraTargetSize.x,
data.newCameraTargetSize.y,
1.0f / data.newCameraTargetSize.x,
1.0f / data.newCameraTargetSize.y
)
);
});
}
}
internal static TextureHandle CreateCompatibleTexture(RenderGraph renderGraph, in TextureHandle source, string name, bool clear, FilterMode filterMode)
{
var desc = source.GetDescriptor(renderGraph);
MakeCompatible(ref desc);
desc.name = name;
desc.clearBuffer = clear;
desc.filterMode = filterMode;
return renderGraph.CreateTexture(desc);
}
internal static TextureHandle CreateCompatibleTexture(RenderGraph renderGraph, in TextureDesc desc, string name, bool clear, FilterMode filterMode)
{
var descCompatible = GetCompatibleDescriptor(desc);
descCompatible.name = name;
descCompatible.clearBuffer = clear;
descCompatible.filterMode = filterMode;
return renderGraph.CreateTexture(descCompatible);
}
internal static TextureDesc GetCompatibleDescriptor(TextureDesc desc, int width, int height, GraphicsFormat format)
{
desc.width = width;
desc.height = height;
desc.format = format;
MakeCompatible(ref desc);
return desc;
}
internal static TextureDesc GetCompatibleDescriptor(TextureDesc desc)
{
MakeCompatible(ref desc);
return desc;
}
internal static void MakeCompatible(ref TextureDesc desc)
{
desc.msaaSamples = MSAASamples.None;
desc.useMipMap = false;
desc.autoGenerateMips = false;
desc.anisoLevel = 0;
desc.discardBuffer = false;
}
internal static RenderTextureDescriptor GetCompatibleDescriptor(RenderTextureDescriptor desc, int width, int height, GraphicsFormat format, GraphicsFormat depthStencilFormat = GraphicsFormat.None)
{
desc.depthStencilFormat = depthStencilFormat;
desc.msaaSamples = 1;
desc.width = width;
desc.height = height;
desc.graphicsFormat = format;
return desc;
}
#region StopNaNs
private class StopNaNsPassData
{
internal TextureHandle sourceTexture;
internal Material stopNaN;
}
public void RenderStopNaN(RenderGraph renderGraph, in TextureHandle activeCameraColor, out TextureHandle stopNaNTarget)
{
stopNaNTarget = CreateCompatibleTexture(renderGraph, activeCameraColor, "_StopNaNsTarget", true, FilterMode.Bilinear);
using (var builder = renderGraph.AddRasterRenderPass<StopNaNsPassData>("Stop NaNs", out var passData,
ProfilingSampler.Get(URPProfileId.RG_StopNaNs)))
{
builder.SetRenderAttachment(stopNaNTarget, 0, AccessFlags.ReadWrite);
passData.sourceTexture = activeCameraColor;
builder.UseTexture(activeCameraColor, AccessFlags.Read);
passData.stopNaN = m_Materials.stopNaN;
builder.SetRenderFunc(static (StopNaNsPassData data, RasterGraphContext context) =>
{
var cmd = context.cmd;
RTHandle sourceTextureHdl = data.sourceTexture;
Vector2 viewportScale = sourceTextureHdl.useScaling? new Vector2(sourceTextureHdl.rtHandleProperties.rtHandleScale.x, sourceTextureHdl.rtHandleProperties.rtHandleScale.y) : Vector2.one;
Blitter.BlitTexture(cmd, sourceTextureHdl, viewportScale, data.stopNaN, 0);
});
}
}
#endregion
#region SMAA
private class SMAASetupPassData
{
internal Vector4 metrics;
internal Texture2D areaTexture;
internal Texture2D searchTexture;
internal float stencilRef;
internal float stencilMask;
internal AntialiasingQuality antialiasingQuality;
internal Material material;
}
private class SMAAPassData
{
internal TextureHandle sourceTexture;
internal TextureHandle blendTexture;
internal Material material;
}
public void RenderSMAA(RenderGraph renderGraph, UniversalResourceData resourceData, AntialiasingQuality antialiasingQuality, in TextureHandle source, out TextureHandle SMAATarget)
{
var destDesc = renderGraph.GetTextureDesc(source);
SMAATarget = CreateCompatibleTexture(renderGraph, destDesc, "_SMAATarget", true, FilterMode.Bilinear);
destDesc.clearColor = Color.black;
destDesc.clearColor.a = 0.0f;
var edgeTextureDesc = destDesc;
edgeTextureDesc.format = m_SMAAEdgeFormat;
var edgeTexture = CreateCompatibleTexture(renderGraph, edgeTextureDesc, "_EdgeStencilTexture", true, FilterMode.Bilinear);
var edgeTextureStencilDesc = destDesc;
edgeTextureStencilDesc.format = GraphicsFormatUtility.GetDepthStencilFormat(24);
var edgeTextureStencil = CreateCompatibleTexture(renderGraph, edgeTextureStencilDesc, "_EdgeTexture", true, FilterMode.Bilinear);
var blendTextureDesc = destDesc;
blendTextureDesc.format = GraphicsFormat.R8G8B8A8_UNorm;
var blendTexture = CreateCompatibleTexture(renderGraph, blendTextureDesc, "_BlendTexture", true, FilterMode.Point);
// Anti-aliasing
var material = m_Materials.subpixelMorphologicalAntialiasing;
using (var builder = renderGraph.AddRasterRenderPass<SMAASetupPassData>("SMAA Material Setup", out var passData, ProfilingSampler.Get(URPProfileId.RG_SMAAMaterialSetup)))
{
const int kStencilBit = 64;
// TODO RENDERGRAPH: handle dynamic scaling
passData.metrics = new Vector4(1f / destDesc.width, 1f / destDesc.height, destDesc.width, destDesc.height);
passData.areaTexture = m_Materials.resources.textures.smaaAreaTex;
passData.searchTexture = m_Materials.resources.textures.smaaSearchTex;
passData.stencilRef = (float)kStencilBit;
passData.stencilMask = (float)kStencilBit;
passData.antialiasingQuality = antialiasingQuality;
passData.material = material;
builder.AllowPassCulling(false);
builder.SetRenderFunc(static (SMAASetupPassData data, RasterGraphContext context) =>
{
// Globals
data.material.SetVector(ShaderConstants._Metrics, data.metrics);
data.material.SetTexture(ShaderConstants._AreaTexture, data.areaTexture);
data.material.SetTexture(ShaderConstants._SearchTexture, data.searchTexture);
data.material.SetFloat(ShaderConstants._StencilRef, data.stencilRef);
data.material.SetFloat(ShaderConstants._StencilMask, data.stencilMask);
// Quality presets
data.material.shaderKeywords = null;
switch (data.antialiasingQuality)
{
case AntialiasingQuality.Low:
data.material.EnableKeyword(ShaderKeywordStrings.SmaaLow);
break;
case AntialiasingQuality.Medium:
data.material.EnableKeyword(ShaderKeywordStrings.SmaaMedium);
break;
case AntialiasingQuality.High:
data.material.EnableKeyword(ShaderKeywordStrings.SmaaHigh);
break;
}
});
}
using (var builder = renderGraph.AddRasterRenderPass<SMAAPassData>("SMAA Edge Detection", out var passData, ProfilingSampler.Get(URPProfileId.RG_SMAAEdgeDetection)))
{
builder.SetRenderAttachment(edgeTexture, 0, AccessFlags.Write);
builder.SetRenderAttachmentDepth(edgeTextureStencil, AccessFlags.Write);
passData.sourceTexture = source;
builder.UseTexture(source, AccessFlags.Read);
builder.UseTexture(resourceData.cameraDepth ,AccessFlags.Read);
passData.material = material;
builder.SetRenderFunc(static (SMAAPassData data, RasterGraphContext context) =>
{
var SMAAMaterial = data.material;
var cmd = context.cmd;
RTHandle sourceTextureHdl = data.sourceTexture;
// Pass 1: Edge detection
Vector2 viewportScale = sourceTextureHdl.useScaling ? new Vector2(sourceTextureHdl.rtHandleProperties.rtHandleScale.x, sourceTextureHdl.rtHandleProperties.rtHandleScale.y) : Vector2.one;
Blitter.BlitTexture(cmd, sourceTextureHdl, viewportScale, SMAAMaterial, 0);
});
}
using (var builder = renderGraph.AddRasterRenderPass<SMAAPassData>("SMAA Blend weights", out var passData, ProfilingSampler.Get(URPProfileId.RG_SMAABlendWeight)))
{
builder.SetRenderAttachment(blendTexture, 0, AccessFlags.Write);
builder.SetRenderAttachmentDepth(edgeTextureStencil, AccessFlags.Read);
passData.sourceTexture = edgeTexture;
builder.UseTexture(edgeTexture, AccessFlags.Read);
passData.material = material;
builder.SetRenderFunc(static (SMAAPassData data, RasterGraphContext context) =>
{
var SMAAMaterial = data.material;
var cmd = context.cmd;
RTHandle sourceTextureHdl = data.sourceTexture;
// Pass 2: Blend weights
Vector2 viewportScale = sourceTextureHdl.useScaling ? new Vector2(sourceTextureHdl.rtHandleProperties.rtHandleScale.x, sourceTextureHdl.rtHandleProperties.rtHandleScale.y) : Vector2.one;
Blitter.BlitTexture(cmd, sourceTextureHdl, viewportScale, SMAAMaterial, 1);
});
}
using (var builder = renderGraph.AddRasterRenderPass<SMAAPassData>("SMAA Neighborhood blending", out var passData, ProfilingSampler.Get(URPProfileId.RG_SMAANeighborhoodBlend)))
{
builder.AllowGlobalStateModification(true);
builder.SetRenderAttachment(SMAATarget, 0, AccessFlags.Write);
passData.sourceTexture = source;
builder.UseTexture(source, AccessFlags.Read);
passData.blendTexture = blendTexture;
builder.UseTexture(blendTexture, AccessFlags.Read);
passData.material = material;
builder.SetRenderFunc(static (SMAAPassData data, RasterGraphContext context) =>
{
var SMAAMaterial = data.material;
var cmd = context.cmd;
RTHandle sourceTextureHdl = data.sourceTexture;
// Pass 3: Neighborhood blending
SMAAMaterial.SetTexture(ShaderConstants._BlendTexture, data.blendTexture);
Vector2 viewportScale = sourceTextureHdl.useScaling ? new Vector2(sourceTextureHdl.rtHandleProperties.rtHandleScale.x, sourceTextureHdl.rtHandleProperties.rtHandleScale.y) : Vector2.one;
Blitter.BlitTexture(cmd, sourceTextureHdl, viewportScale, SMAAMaterial, 2);
});
}
}
#endregion
#region Bloom
private class UberSetupBloomPassData
{
internal Vector4 bloomParams;
internal Vector4 dirtScaleOffset;
internal float dirtIntensity;
internal Texture dirtTexture;
internal bool highQualityFilteringValue;
internal TextureHandle bloomTexture;
internal Material uberMaterial;
}
public void UberPostSetupBloomPass(RenderGraph rendergraph, Material uberMaterial, in TextureDesc srcDesc)
{
using (new ProfilingScope(ProfilingSampler.Get(URPProfileId.RG_UberPostSetupBloomPass)))
{
// Setup bloom on uber
var tint = m_Bloom.tint.value.linear;
var luma = ColorUtils.Luminance(tint);
tint = luma > 0f ? tint * (1f / luma) : Color.white;
var bloomParams = new Vector4(m_Bloom.intensity.value, tint.r, tint.g, tint.b);
// Setup lens dirtiness on uber
// Keep the aspect ratio correct & center the dirt texture, we don't want it to be
// stretched or squashed
var dirtTexture = m_Bloom.dirtTexture.value == null ? Texture2D.blackTexture : m_Bloom.dirtTexture.value;
float dirtRatio = dirtTexture.width / (float)dirtTexture.height;
float screenRatio = srcDesc.width / (float)srcDesc.height;
var dirtScaleOffset = new Vector4(1f, 1f, 0f, 0f);
float dirtIntensity = m_Bloom.dirtIntensity.value;
if (dirtRatio > screenRatio)
{
dirtScaleOffset.x = screenRatio / dirtRatio;
dirtScaleOffset.z = (1f - dirtScaleOffset.x) * 0.5f;
}
else if (screenRatio > dirtRatio)
{
dirtScaleOffset.y = dirtRatio / screenRatio;
dirtScaleOffset.w = (1f - dirtScaleOffset.y) * 0.5f;
}
var highQualityFilteringValue = m_Bloom.highQualityFiltering.value;
uberMaterial.SetVector(ShaderConstants._Bloom_Params, bloomParams);
uberMaterial.SetVector(ShaderConstants._LensDirt_Params, dirtScaleOffset);
uberMaterial.SetFloat(ShaderConstants._LensDirt_Intensity, dirtIntensity);
uberMaterial.SetTexture(ShaderConstants._LensDirt_Texture, dirtTexture);
// Keyword setup - a bit convoluted as we're trying to save some variants in Uber...
if (highQualityFilteringValue)
uberMaterial.EnableKeyword(dirtIntensity > 0f ? ShaderKeywordStrings.BloomHQDirt : ShaderKeywordStrings.BloomHQ);
else
uberMaterial.EnableKeyword(dirtIntensity > 0f ? ShaderKeywordStrings.BloomLQDirt : ShaderKeywordStrings.BloomLQ);
}
}
private class BloomPassData
{
internal int mipCount;
internal Material material;
internal Material[] upsampleMaterials;
internal TextureHandle sourceTexture;
internal TextureHandle[] bloomMipUp;
internal TextureHandle[] bloomMipDown;
}
internal struct BloomMaterialParams
{
internal Vector4 parameters;
internal Vector4 parameters2;
internal BloomFilterMode bloomFilter;
internal bool highQualityFiltering;
internal bool enableAlphaOutput;
internal bool Equals(ref BloomMaterialParams other)
{
return parameters == other.parameters &&
parameters2 == other.parameters2 &&
highQualityFiltering == other.highQualityFiltering &&
enableAlphaOutput == other.enableAlphaOutput &&
bloomFilter == other.bloomFilter;
}
}
public Vector2Int CalcBloomResolution(Bloom bloom, in TextureDesc bloomSourceDesc)
{
// Start at half-res
int downres = 1;
switch (m_Bloom.downscale.value)
{
case BloomDownscaleMode.Half:
downres = 1;
break;
case BloomDownscaleMode.Quarter:
downres = 2;
break;
default:
throw new ArgumentOutOfRangeException();
}
//We should set the limit the downres result to ensure we dont turn 1x1 textures, which should technically be valid
//into 0x0 textures which will be invalid
int tw = Mathf.Max(1, bloomSourceDesc.width >> downres);
int th = Mathf.Max(1, bloomSourceDesc.height >> downres);
return new Vector2Int(tw, th);
}
public int CalcBloomMipCount(Bloom bloom, Vector2Int bloomResolution)
{
// Determine the iteration count
int maxSize = Mathf.Max(bloomResolution.x, bloomResolution.y);
int iterations = Mathf.FloorToInt(Mathf.Log(maxSize, 2f) - 1);
int mipCount = Mathf.Clamp(iterations, 1, m_Bloom.maxIterations.value);
return mipCount;
}
public void RenderBloomTexture(RenderGraph renderGraph, in TextureHandle source, out TextureHandle destination, bool enableAlphaOutput)
{
var srcDesc = source.GetDescriptor(renderGraph);
Vector2Int bloomRes = CalcBloomResolution(m_Bloom, in srcDesc);
int mipCount = CalcBloomMipCount(m_Bloom, bloomRes);
int tw = bloomRes.x;
int th = bloomRes.y;
// Setup
using(new ProfilingScope(ProfilingSampler.Get(URPProfileId.RG_BloomSetup)))
{
// Pre-filtering parameters
float clamp = m_Bloom.clamp.value;
float threshold = Mathf.GammaToLinearSpace(m_Bloom.threshold.value);
float thresholdKnee = threshold * 0.5f; // Hardcoded soft knee
// Material setup
float scatter = Mathf.Lerp(0.05f, 0.95f, m_Bloom.scatter.value); // Blend factor between low/hi mip on upsample.
float kawaseScatter = Mathf.Clamp01(m_Bloom.scatter.value); // Blend factor between linear and blurred sample. 1.0 for strict Kawase blur.
float dualScatter = Mathf.Lerp(0.3f, 1.3f, m_Bloom.scatter.value); // Dual upsample filter scale. Scatter default == 0.7 --> 1.0 filter scale.
BloomMaterialParams bloomParams = new BloomMaterialParams();
bloomParams.parameters = new Vector4(scatter, clamp, threshold, thresholdKnee);
bloomParams.parameters2 = new Vector4(0.5f, kawaseScatter, dualScatter, 0.5f * dualScatter);
bloomParams.bloomFilter = m_Bloom.filter.value;
bloomParams.highQualityFiltering = m_Bloom.highQualityFiltering.value;
bloomParams.enableAlphaOutput = enableAlphaOutput;
// Setting keywords can be somewhat expensive on low-end platforms.
// Previous params are cached to avoid setting the same keywords every frame.
var material = m_Materials.bloom;
bool bloomParamsDirty = !m_BloomParamsPrev.Equals(ref bloomParams);
bool isParamsPropertySet = material.HasProperty(ShaderConstants._Params);
if (bloomParamsDirty || !isParamsPropertySet)
{
material.SetVector(ShaderConstants._Params, bloomParams.parameters);
material.SetVector(ShaderConstants._Params2, bloomParams.parameters2);
CoreUtils.SetKeyword(material, ShaderKeywordStrings.BloomHQ, bloomParams.highQualityFiltering);
CoreUtils.SetKeyword(material, ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT, bloomParams.enableAlphaOutput);
// These materials are duplicate just to allow different bloom blits to use different textures.
for (uint i = 0; i < Constants.k_MaxPyramidSize; ++i)
{
var materialPyramid = m_Materials.bloomUpsample[i];
materialPyramid.SetVector(ShaderConstants._Params, bloomParams.parameters);
CoreUtils.SetKeyword(materialPyramid, ShaderKeywordStrings.BloomHQ, bloomParams.highQualityFiltering);
CoreUtils.SetKeyword(materialPyramid, ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT, bloomParams.enableAlphaOutput);
// TODO: investigate suggested quality improvement trick in more detail:
// Kawase5: 0, 1, 2, 2, 3
// Kawase9: 0, 1, 2, 3, 4, 4, 5, 6, 7
// ? -> KawaseN: duplicate pass at N/2 (See, Bandwidth-Efficient Rendering, siggraph2015)
float kawaseDist = 0.5f + ((i > mipCount / 2) ? (i - 1) : i);
Vector4 params2 = bloomParams.parameters2;
params2.x = kawaseDist;
materialPyramid.SetVector(ShaderConstants._Params2, params2);
}
m_BloomParamsPrev = bloomParams;
}
// Create bloom mip pyramid textures
{
var desc = GetCompatibleDescriptor(srcDesc, tw, th, m_BloomColorFormat);
_BloomMipDown[0] = CreateCompatibleTexture(renderGraph, desc, m_BloomMipDownName[0], false, FilterMode.Bilinear);
_BloomMipUp[0] = CreateCompatibleTexture(renderGraph, desc, m_BloomMipUpName[0], false, FilterMode.Bilinear);
if (bloomParams.bloomFilter != BloomFilterMode.Kawase)
{
for (int i = 1; i < mipCount; i++)
{
tw = Mathf.Max(1, tw >> 1);
th = Mathf.Max(1, th >> 1);
ref TextureHandle mipDown = ref _BloomMipDown[i];
ref TextureHandle mipUp = ref _BloomMipUp[i];
desc.width = tw;
desc.height = th;
mipDown = CreateCompatibleTexture(renderGraph, desc, m_BloomMipDownName[i], false, FilterMode.Bilinear);
mipUp = CreateCompatibleTexture(renderGraph, desc, m_BloomMipUpName[i], false, FilterMode.Bilinear);
}
}
}
}
switch (m_Bloom.filter.value)
{
case BloomFilterMode.Dual:
destination = BloomDual(renderGraph, source, mipCount);
break;
case BloomFilterMode.Kawase:
destination = BloomKawase(renderGraph, source, mipCount);
break;
case BloomFilterMode.Gaussian: goto default;
default:
destination = BloomGaussian(renderGraph, source, mipCount);
break;
}
}
TextureHandle BloomGaussian(RenderGraph renderGraph, TextureHandle source, int mipCount)
{
using (var builder = renderGraph.AddUnsafePass<BloomPassData>("Blit Bloom Mipmaps", out var passData, ProfilingSampler.Get(URPProfileId.Bloom)))
{
passData.mipCount = mipCount;
passData.material = m_Materials.bloom;
passData.upsampleMaterials = m_Materials.bloomUpsample;
passData.sourceTexture = source;
passData.bloomMipDown = _BloomMipDown;
passData.bloomMipUp = _BloomMipUp;
// TODO RENDERGRAPH: properly setup dependencies between passes
builder.AllowPassCulling(false);
builder.UseTexture(source, AccessFlags.Read);
for (int i = 0; i < mipCount; i++)
{
builder.UseTexture(_BloomMipDown[i], AccessFlags.ReadWrite);
builder.UseTexture(_BloomMipUp[i], AccessFlags.ReadWrite);
}
builder.SetRenderFunc(static (BloomPassData data, UnsafeGraphContext context) =>
{
// TODO: can't call BlitTexture with unsafe command buffer
var cmd = CommandBufferHelpers.GetNativeCommandBuffer(context.cmd);
var material = data.material;
int mipCount = data.mipCount;
var loadAction = RenderBufferLoadAction.DontCare; // Blit - always write all pixels
var storeAction = RenderBufferStoreAction.Store; // Blit - always read by then next Blit
// Prefilter
using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.RG_BloomPrefilter)))
{
Blitter.BlitCameraTexture(cmd, data.sourceTexture, data.bloomMipDown[0], loadAction,
storeAction, material, 0);
}
// Downsample - gaussian pyramid
// Classic two pass gaussian blur - use mipUp as a temporary target
// First pass does 2x downsampling + 9-tap gaussian
// Second pass does 9-tap gaussian using a 5-tap filter + bilinear filtering
using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.RG_BloomDownsample)))
{
TextureHandle lastDown = data.bloomMipDown[0];
for (int i = 1; i < mipCount; i++)
{
TextureHandle mipDown = data.bloomMipDown[i];
TextureHandle mipUp = data.bloomMipUp[i];
Blitter.BlitCameraTexture(cmd, lastDown, mipUp, loadAction, storeAction, material, 1);
Blitter.BlitCameraTexture(cmd, mipUp, mipDown, loadAction, storeAction, material, 2);
lastDown = mipDown;
}
}
using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.RG_BloomUpsample)))
{
// Upsample (bilinear by default, HQ filtering does bicubic instead
for (int i = mipCount - 2; i >= 0; i--)
{
TextureHandle lowMip =
(i == mipCount - 2) ? data.bloomMipDown[i + 1] : data.bloomMipUp[i + 1];
TextureHandle highMip = data.bloomMipDown[i];
TextureHandle dst = data.bloomMipUp[i];
// We need a separate material for each upsample pass because setting the low texture mip source
// gets overriden by the time the render func is executed.
// Material is a reference, so all the blits would share the same material state in the cmdbuf.
// NOTE: another option would be to use cmd.SetGlobalTexture().
var upMaterial = data.upsampleMaterials[i];
upMaterial.SetTexture(ShaderConstants._SourceTexLowMip, lowMip);
Blitter.BlitCameraTexture(cmd, highMip, dst, loadAction, storeAction, upMaterial, 3);
}
}
});
// 1st mip is the prefilter.
return mipCount == 1 ? passData.bloomMipDown[0] : passData.bloomMipUp[0];
}
}
TextureHandle BloomKawase(RenderGraph renderGraph, TextureHandle source, int mipCount)
{
using (var builder = renderGraph.AddUnsafePass<BloomPassData>("Blit Bloom Mipmaps (Kawase)", out var passData, ProfilingSampler.Get(URPProfileId.Bloom)))
{
passData.mipCount = mipCount;
passData.material = m_Materials.bloom;
passData.upsampleMaterials = m_Materials.bloomUpsample;
passData.sourceTexture = source;
passData.bloomMipDown = _BloomMipDown;
passData.bloomMipUp = _BloomMipUp;
// TODO RENDERGRAPH: properly setup dependencies between passes
builder.AllowPassCulling(false);
builder.UseTexture(source, AccessFlags.Read);
builder.UseTexture(_BloomMipDown[0], AccessFlags.ReadWrite);
builder.UseTexture(_BloomMipUp[0], AccessFlags.ReadWrite);
builder.SetRenderFunc(static (BloomPassData data, UnsafeGraphContext context) =>
{
// TODO: can't call BlitTexture with unsafe command buffer
var cmd = CommandBufferHelpers.GetNativeCommandBuffer(context.cmd);
var material = data.material;
int mipCount = data.mipCount;
var loadAction = RenderBufferLoadAction.DontCare; // Blit - always write all pixels
var storeAction = RenderBufferStoreAction.Store; // Blit - always read by then next Blit
// Prefilter
using(new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.RG_BloomPrefilter)))
{
Blitter.BlitCameraTexture(cmd, data.sourceTexture, data.bloomMipDown[0], loadAction, storeAction, material, 0);
}
// Kawase blur passes
using(new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.RG_BloomDownsample)))
{
for (int i = 0; i < mipCount; i++)
{
TextureHandle src = ((i & 1) == 0) ? data.bloomMipDown[0] : data.bloomMipUp[0];
TextureHandle dst = ((i & 1) == 0) ? data.bloomMipUp[0] : data.bloomMipDown[0];
Material mat = data.upsampleMaterials[i];
Blitter.BlitCameraTexture(cmd, src, dst, loadAction, storeAction, mat, 4);
}
}
});
return (((mipCount - 1) & 1) == 0) ? _BloomMipUp[0] : _BloomMipDown[0];
}
}
// Dual Filter, Bandwidth-Efficient Rendering, siggraph2015
TextureHandle BloomDual(RenderGraph renderGraph, TextureHandle source, int mipCount)
{
using (var builder = renderGraph.AddUnsafePass<BloomPassData>("Blit Bloom Mipmaps (Dual)", out var passData, ProfilingSampler.Get(URPProfileId.Bloom)))
{
passData.mipCount = mipCount;
passData.material = m_Materials.bloom;
passData.upsampleMaterials = m_Materials.bloomUpsample;
passData.sourceTexture = source;
passData.bloomMipDown = _BloomMipDown;
passData.bloomMipUp = _BloomMipUp;
// TODO RENDERGRAPH: properly setup dependencies between passes
builder.AllowPassCulling(false);
builder.UseTexture(source, AccessFlags.Read);
for (int i = 0; i < mipCount; i++)
{
builder.UseTexture(_BloomMipDown[i], AccessFlags.ReadWrite);
builder.UseTexture(_BloomMipUp[i], AccessFlags.ReadWrite);
}
builder.SetRenderFunc(static (BloomPassData data, UnsafeGraphContext context) =>
{
// TODO: can't call BlitTexture with unsafe command buffer
var cmd = CommandBufferHelpers.GetNativeCommandBuffer(context.cmd);
var material = data.material;
int mipCount = data.mipCount;
var loadAction = RenderBufferLoadAction.DontCare; // Blit - always write all pixels
var storeAction = RenderBufferStoreAction.Store; // Blit - always read by then next Blit
// Prefilter
using(new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.RG_BloomPrefilter)))
{
Blitter.BlitCameraTexture(cmd, data.sourceTexture, data.bloomMipDown[0], loadAction, storeAction, material, 0);
}
// ARM: Bandwidth-Efficient Rendering, siggraph2015
// Downsample - dual pyramid, fixed Kawase0 blur on shrinking targets.
using(new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.RG_BloomDownsample)))
{
TextureHandle lastDown = data.bloomMipDown[0];
for (int i = 1; i < mipCount; i++)
{
TextureHandle src = data.bloomMipDown[i - 1];
TextureHandle dst = data.bloomMipDown[i];
Blitter.BlitCameraTexture(cmd, src, dst, loadAction, storeAction, material, 5);
}
}
using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.RG_BloomUpsample)))
{
for (int i = mipCount - 2; i >= 0; i--)
{
TextureHandle src = (i == mipCount - 2) ? data.bloomMipDown[i + 1] : data.bloomMipUp[i + 1];
TextureHandle dst = data.bloomMipUp[i];
Blitter.BlitCameraTexture(cmd, src, dst, loadAction, storeAction, material, 6);
}
}
});
// 1st mip is the prefilter.
return mipCount == 1 ? passData.bloomMipDown[0] : passData.bloomMipUp[0];