浏览代码

Run code formatter.

/main
Tim Cooper 7 年前
当前提交
fafb59af
共有 498 个文件被更改,包括 3445 次插入4208 次删除
  1. 22
      TestProjects/GraphicsTests/Assets/ImageTemplates/Editor/TemplatePreprocessor.cs
  2. 78
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/PlayModeTest/ComparerShader.shader
  3. 2
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/010_MultiplePointLights/Scripts/Boomerang.cs
  4. 2
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/010_MultiplePointLights/Scripts/RotateAround.cs
  5. 55
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/013_CameraMulti_Splitscreen/Scripts/AutoSizeGrid.cs
  6. 41
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/028_PostProcessing_Custom/Scripts/HalfToneOpaque.cs
  7. 16
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/028_PostProcessing_Custom/Scripts/HalftoneOpaque.shader
  8. 19
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/028_PostProcessing_Custom/Scripts/InvertOpaque.cs
  9. 6
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/028_PostProcessing_Custom/Scripts/InvertOpaque.shader
  10. 22
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/029_Particles/PlaySystems.cs
  11. 106
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/029_Particles/Shaders/CustomParticleData.shader
  12. 22
      TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/037_Particles/Scripts/LookAt.cs
  13. 16
      TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/Framework/PlayModeTestFramework.cs
  14. 2
      TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/Framework/TestFixture.cs
  15. 42
      TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/Framework/TestFramework.cs
  16. 28
      TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/Framework/TestResultWindow.cs
  17. 44
      TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/HDRenderPipeline/PlayModeTest/PlayModeTestsUI.cs
  18. 26
      TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/LWPipeline/040_UpgradeScene/LWSceneConverter.cs
  19. 26
      TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/Framework/AdditionalTestSceneInfos.cs
  20. 16
      TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/Framework/GotoNextScene.cs
  21. 44
      TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/Framework/SetupSceneForRenderPipelineTest.cs
  22. 19
      TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/Framework/TestFrameworkPlayMode.cs
  23. 147
      TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/Framework/TestFrameworkTools.cs
  24. 16
      TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/LWPipeline/040_UpgradeScene/RandomAnimationPoint.cs
  25. 3
      TestProjects/ShaderGraph/Assets/Testing/Editor/TestMaterialGraph.cs
  26. 3
      TestProjects/ShaderGraph/Assets/Testing/Editor/TestNode.cs
  27. 2
      TestProjects/ShaderGraph/Assets/Testing/Editor/TestSlot.cs
  28. 4
      build.py
  29. 4
      com.unity.render-pipelines.core/CoreRP/Camera/CameraSwitcher.cs
  30. 2
      com.unity.render-pipelines.core/CoreRP/Common/CommandBufferPool.cs
  31. 2
      com.unity.render-pipelines.core/CoreRP/Common/ComponentSingleton.cs
  32. 4
      com.unity.render-pipelines.core/CoreRP/Common/ObservableList.cs
  33. 4
      com.unity.render-pipelines.core/CoreRP/Common/RectInt.cs
  34. 2
      com.unity.render-pipelines.core/CoreRP/Common/SerializedDictionary.cs
  35. 2
      com.unity.render-pipelines.core/CoreRP/CoreResources/BlitCubeTextureFace.shader
  36. 2
      com.unity.render-pipelines.core/CoreRP/CoreResources/CubeToPano.shader
  37. 2
      com.unity.render-pipelines.core/CoreRP/CoreResources/GPUCopy.compute
  38. 28
      com.unity.render-pipelines.core/CoreRP/CoreResources/GPUCopy.cs
  39. 28
      com.unity.render-pipelines.core/CoreRP/CoreResources/GPUCopyAsset.cs
  40. 1
      com.unity.render-pipelines.core/CoreRP/CoreResources/TexturePadding.cs
  41. 6
      com.unity.render-pipelines.core/CoreRP/Debugging/DebugManager.cs
  42. 2
      com.unity.render-pipelines.core/CoreRP/Debugging/DebugUI.Containers.cs
  43. 2
      com.unity.render-pipelines.core/CoreRP/Debugging/DebugUI.Fields.cs
  44. 4
      com.unity.render-pipelines.core/CoreRP/Debugging/DebugUI.Panel.cs
  45. 2
      com.unity.render-pipelines.core/CoreRP/Debugging/DebugUpdater.cs
  46. 2
      com.unity.render-pipelines.core/CoreRP/Debugging/MousePositionDebug.cs
  47. 8
      com.unity.render-pipelines.core/CoreRP/Debugging/Prefabs/Scripts/DebugUIHandlerPanel.cs
  48. 10
      com.unity.render-pipelines.core/CoreRP/Debugging/Prefabs/Scripts/DebugUIHandlerWidget.cs
  49. 3
      com.unity.render-pipelines.core/CoreRP/Debugging/Prefabs/Scripts/UIFoldout.cs
  50. 6
      com.unity.render-pipelines.core/CoreRP/Debugging/ProfilingSample.cs
  51. 2
      com.unity.render-pipelines.core/CoreRP/Editor/CameraEditorUtils.cs
  52. 10
      com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorDrawers.cs
  53. 2
      com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorStyles.cs
  54. 2
      com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorUtils.cs
  55. 4
      com.unity.render-pipelines.core/CoreRP/Editor/CoreResources/GPUCopyAssetEditor.cs
  56. 18
      com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugState.cs
  57. 6
      com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugUIDrawer.cs
  58. 42
      com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugUIHandlerCanvasEditor.cs
  59. 26
      com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugWindow.cs
  60. 2
      com.unity.render-pipelines.core/CoreRP/Editor/Debugging/UIFoldoutEditor.cs
  61. 2
      com.unity.render-pipelines.core/CoreRP/Editor/IncludePaths/CoreShaderIncludePaths.cs
  62. 2
      com.unity.render-pipelines.core/CoreRP/Editor/PropertyFetcher.cs
  63. 2
      com.unity.render-pipelines.core/CoreRP/Editor/SceneRenderPipeline.cs
  64. 4
      com.unity.render-pipelines.core/CoreRP/Editor/ShaderGenerator/CSharpToHLSL.cs
  65. 450
      com.unity.render-pipelines.core/CoreRP/Editor/TextureCombiner/TextureCombiner.cs
  66. 168
      com.unity.render-pipelines.core/CoreRP/Editor/TextureCombiner/TextureCombiner.shader
  67. 2
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/Drawers/ColorParameterDrawer.cs
  68. 2
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/Drawers/FloatParameterDrawer.cs
  69. 2
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/Drawers/IntParameterDrawer.cs
  70. 2
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/Drawers/Vector4ParameterDrawer.cs
  71. 2
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/SerializedDataParameter.cs
  72. 12
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeComponentEditor.cs
  73. 22
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeComponentListEditor.cs
  74. 2
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeComponentProvider.cs
  75. 2
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeParameterDrawer.cs
  76. 2
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeProfileEditor.cs
  77. 4
      com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeProfileFactory.cs
  78. 33
      com.unity.render-pipelines.core/CoreRP/Inputs/InputRegistering.cs
  79. 2
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/BC6H.hlsl
  80. 1001
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl
  81. 2
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonLighting.hlsl
  82. 552
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Debug.hlsl
  83. 4
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Random.hlsl
  84. 32
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/Shadow.hlsl
  85. 972
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl
  86. 132
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowMoments.hlsl
  87. 722
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowSampling.hlsl
  88. 322
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowSamplingTent.hlsl
  89. 208
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowTexFetch.hlsl
  90. 2
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Wind.hlsl
  91. 49
      com.unity.render-pipelines.core/CoreRP/Shadow/AdditionalShadowData.cs
  92. 797
      com.unity.render-pipelines.core/CoreRP/Shadow/Shadow.cs
  93. 340
      com.unity.render-pipelines.core/CoreRP/Shadow/ShadowBase.cs
  94. 34
      com.unity.render-pipelines.core/CoreRP/Shadow/ShadowBase.cs.hlsl
  95. 428
      com.unity.render-pipelines.core/CoreRP/Shadow/ShadowBlurMoments.compute
  96. 181
      com.unity.render-pipelines.core/CoreRP/Shadow/ShadowUtilities.cs
  97. 53
      com.unity.render-pipelines.core/CoreRP/Shadow/VectorArray.cs
  98. 22
      com.unity.render-pipelines.core/CoreRP/Textures/BufferedRTHandleSystem.cs
  99. 2
      com.unity.render-pipelines.core/CoreRP/Textures/DepthBits.cs
  100. 12
      com.unity.render-pipelines.core/CoreRP/Textures/EncodeBC6H.cs

22
TestProjects/GraphicsTests/Assets/ImageTemplates/Editor/TemplatePreprocessor.cs


using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

/// This script forces all textures in the folder 'ImageTemplates' to have no compression, meaning import times will be much faster, especially when switching platforms
/// </summary>
public class TemplatePreprocessor : AssetPostprocessor {
void OnPreprocessTexture()
{
if (assetPath.Contains("ImageTemplates"))
{
TextureImporter textureImporter = (TextureImporter)assetImporter;
textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
}
}
public class TemplatePreprocessor : AssetPostprocessor
{
void OnPreprocessTexture()
{
if (assetPath.Contains("ImageTemplates"))
{
TextureImporter textureImporter = (TextureImporter)assetImporter;
textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
}
}
}

78
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/PlayModeTest/ComparerShader.shader


Shader "GraphicTests/ComparerShader"
{
Properties
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
_CompareTex("Texture", 2D) = "white" {}
[Enum(Red, 0, Green, 1, Blue, 2, Color, 3, Greyscale, 4, Heatmap, 5)]

_ResultSplit ("Result Split", Range(0,1)) = 0.1
_LineWidth("Line Width", float) = 0.001
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
sampler2D _CompareTex;

float _CorrectGamma = 0;
float _Split, _ResultSplit, _LineWidth;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
// Folowing color conversion code source : https://github.com/nschloe/colorio

200. * (XYZ2LabFunc(xyz.y / yn) - XYZ2LabFunc(xyz.z / zn))
);
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 frag (v2f i) : SV_Target
{
fixed4 c1 = tex2D(_MainTex, i.uv);
float2 uv2 = i.uv;
if (_FlipV2 > 0) uv2.y = 1 - uv2.y;

o.rgb = pow(o.rgb, 0.4545454545);
return o;
}
ENDCG
}
}
}
ENDCG
}
}
}

2
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/010_MultiplePointLights/Scripts/Boomerang.cs


using System.Collections;
using System.Collections;
using UnityEngine;
public class Boomerang : MonoBehaviour

2
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/010_MultiplePointLights/Scripts/RotateAround.cs


using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

55
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/013_CameraMulti_Splitscreen/Scripts/AutoSizeGrid.cs


using System.Collections;
using System.Collections;
public class AutoSizeGrid : MonoBehaviour {
public class AutoSizeGrid : MonoBehaviour
{
public GridLayoutGroup layout;
public bool dynamic = false;
private int rows = 2;
private int columns = 2;
public GridLayoutGroup layout;
public bool dynamic = false;
private int rows = 2;
private int columns = 2;
// Use this for initialization
void Start()
{
SetCellSize();
}
// Use this for initialization
void Start () {
SetCellSize ();
}
// Update is called once per frame
void Update () {
#if UNITY_EDITOR
SetCellSize ();
#else
if(dynamic){
SetCellSize ();
}
#endif
}
// Update is called once per frame
void Update()
{
#if UNITY_EDITOR
SetCellSize();
#else
if (dynamic)
{
SetCellSize();
}
#endif
}
void SetCellSize(){
Vector2 vec = new Vector2 (Screen.width / columns, Screen.height / rows);
layout.cellSize = vec / transform.parent.localScale.x;
}
void SetCellSize()
{
Vector2 vec = new Vector2(Screen.width / columns, Screen.height / rows);
layout.cellSize = vec / transform.parent.localScale.x;
}
}

41
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/028_PostProcessing_Custom/Scripts/HalfToneOpaque.cs


using System;
using System;
public sealed class HalfToneOpaque : PostProcessEffectSettings {
[Range(-2f, 2f), Tooltip("Pattern Midpoint")]
public FloatParameter midpoint = new FloatParameter{ value = 0f };
[Range(0.001f, 0.1f), Tooltip("Pattern Scale")]
public FloatParameter scale = new FloatParameter{ value = 0.025f };
[Range(1, 10), Tooltip("Steps")]
public IntParameter steps = new IntParameter{ value = 4};
public TextureParameter pattern = new TextureParameter{ value = null};
public sealed class HalfToneOpaque : PostProcessEffectSettings
{
[Range(-2f, 2f), Tooltip("Pattern Midpoint")]
public FloatParameter midpoint = new FloatParameter { value = 0f };
[Range(0.001f, 0.1f), Tooltip("Pattern Scale")]
public FloatParameter scale = new FloatParameter { value = 0.025f };
[Range(1, 10), Tooltip("Steps")]
public IntParameter steps = new IntParameter { value = 4};
public TextureParameter pattern = new TextureParameter { value = null};
public sealed class HalfToneOpaqueRenderer : PostProcessEffectRenderer<HalfToneOpaque> {
public override void Render(PostProcessRenderContext context){
var sheet = context.propertySheets.Get(Shader.Find("Hidden/Custom/LWtest/HalftoneOpaque"));
sheet.properties.SetTexture ("_Pattern", settings.pattern);
sheet.properties.SetFloat("_Blend", settings.midpoint);
sheet.properties.SetFloat("_Scale", settings.scale);
sheet.properties.SetFloat("_Steps", settings.steps);
context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
}
public sealed class HalfToneOpaqueRenderer : PostProcessEffectRenderer<HalfToneOpaque>
{
public override void Render(PostProcessRenderContext context)
{
var sheet = context.propertySheets.Get(Shader.Find("Hidden/Custom/LWtest/HalftoneOpaque"));
sheet.properties.SetTexture("_Pattern", settings.pattern);
sheet.properties.SetFloat("_Blend", settings.midpoint);
sheet.properties.SetFloat("_Scale", settings.scale);
sheet.properties.SetFloat("_Steps", settings.steps);
context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
}
}

16
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/028_PostProcessing_Custom/Scripts/HalftoneOpaque.shader


Shader "Hidden/Custom/LWtest/HalftoneOpaque"
Shader "Hidden/Custom/LWtest/HalftoneOpaque"
Properties
{
_Pattern ("Pattern", 2D) = "grey" {}
[IntRange]_Steps ("Steps", Range(1, 10)) = 4
}
HLSLINCLUDE
Properties
{
_Pattern ("Pattern", 2D) = "grey" {}
[IntRange]_Steps ("Steps", Range(1, 10)) = 4
}
HLSLINCLUDE
#include "../../../../../../../PostProcessing/PostProcessing/Shaders/StdLib.hlsl"

float4 Frag(VaryingsDefault i) : SV_Target
{
float4 color = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.texcoord);
float luminance = 1 + dot(color.rgb, float3(0.2126729, 0.7151522, 0.0721750)) * 0.25;
float3 pattern = SAMPLE_TEXTURE2D(_Pattern, sampler_Pattern, i.texcoord * (_ScreenParams.xy * _Scale * luminance)).rgb;

19
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/028_PostProcessing_Custom/Scripts/InvertOpaque.cs


using System;
using System;
public sealed class InvertOpaque : PostProcessEffectSettings {
public sealed class InvertOpaque : PostProcessEffectSettings
{
public sealed class InvertOpaqueRenderer : PostProcessEffectRenderer<InvertOpaque> {
public override void Render(PostProcessRenderContext context){
var sheet = context.propertySheets.Get(Shader.Find("Hidden/Custom/LWtest/InvertOpaque"));
context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
}
public sealed class InvertOpaqueRenderer : PostProcessEffectRenderer<InvertOpaque>
{
public override void Render(PostProcessRenderContext context)
{
var sheet = context.propertySheets.Get(Shader.Find("Hidden/Custom/LWtest/InvertOpaque"));
context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, 0);
}
}

6
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/028_PostProcessing_Custom/Scripts/InvertOpaque.shader


Shader "Hidden/Custom/LWtest/InvertOpaque"
Shader "Hidden/Custom/LWtest/InvertOpaque"
HLSLINCLUDE
HLSLINCLUDE
#include "//Assets/PostProcessing/PostProcessing/Shaders/StdLib.hlsl"

{
float4 color = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.texcoord);
return float4(1-color.rgb, color.a);
}

22
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/029_Particles/PlaySystems.cs


using System.Collections;
using System.Collections;
public class PlaySystems : MonoBehaviour {
public class PlaySystems : MonoBehaviour
{
[Range(0, 1)]
[Range(0, 1)]
void OnEnable () {
foreach(ParticleSystem ps in particleSystems){
void OnEnable()
{
foreach (ParticleSystem ps in particleSystems)
{
if (ps != null)
{
float life = ps.main.duration * simPoint;

}
}
void OnDisable()
void OnDisable()
if(ps != null)
ps.Stop();
if (ps != null)
ps.Stop();
}
}
}

106
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/029_Particles/Shaders/CustomParticleData.shader


Shader "Custom/LightweightPipeline/CustomParticleData"
Shader "Custom/LightweightPipeline/CustomParticleData"
Properties
{
_Color("Color", Color) = (1,1,1,1)
}
SubShader
{
Properties
{
_Color("Color", Color) = (1,1,1,1)
}
SubShader
{
LOD 100
LOD 100
Blend SrcAlpha OneMinusSrcAlpha
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
struct appdata
{
float4 vertex : POSITION;
float4 uv : TEXCOORD0;
float3 uv2 : TEXCOORD1;
};
#include "UnityCG.cginc"
struct v2f
{
float4 uv : TEXCOORD0;
float3 uv2 : TEXCOORD1;
struct appdata
{
float4 vertex : POSITION;
float4 uv : TEXCOORD0;
float3 uv2 : TEXCOORD1;
};
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.uv2 = v.uv2;
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = float4(i.uv.zw, i.uv2.x, 1);
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
ENDCG
}
}
struct v2f
{
float4 uv : TEXCOORD0;
float3 uv2 : TEXCOORD1;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.uv2 = v.uv2;
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = float4(i.uv.zw, i.uv2.x, 1);
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
ENDCG
}
}
}

22
TestProjects/GraphicsTests/Assets/Tests/GraphicsTests/RenderPipeline/LightweightPipeline/Scenes/037_Particles/Scripts/LookAt.cs


using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LookAt : MonoBehaviour {
public class LookAt : MonoBehaviour
{
// Use this for initialization
void Start () {
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update () {
}
// Update is called once per frame
void Update()
{
}
}
}

16
TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/Framework/PlayModeTestFramework.cs


{
static string scenesRootPath = "/Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes";
enum Platforms { PC, PS4};
enum Platforms { PC, PS4 };
Platforms platform = Platforms.PC;
bool developmentBuild = false;

PlayModeTestFramework window = GetWindow<PlayModeTestFramework>();
// find all the scenes
window.allPaths = System.IO.Directory.GetFiles(Application.dataPath+scenesRootPath, "*.unity", System.IO.SearchOption.AllDirectories);
window.allPaths = System.IO.Directory.GetFiles(Application.dataPath + scenesRootPath, "*.unity", System.IO.SearchOption.AllDirectories);
for (int i = 0; i < window.allPaths.Length; ++i)
{

{
EditorBuildSettingsScene[] prevScenes = EditorBuildSettings.scenes;
EditorBuildSettingsScene[] testScenes = new EditorBuildSettingsScene[allPaths.Length+1];
EditorBuildSettingsScene[] testScenes = new EditorBuildSettingsScene[allPaths.Length + 1];
testScenes[0] = new EditorBuildSettingsScene(Application.dataPath+ "/Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/PlayModeTest/PlayModeTests.unity", true);
testScenes[0] = new EditorBuildSettingsScene(Application.dataPath + "/Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/PlayModeTest/PlayModeTests.unity", true);
for (int i=0; i<allPaths.Length;++i)
for (int i = 0; i < allPaths.Length; ++i)
testScenes[i+1] = new EditorBuildSettingsScene(allPaths[i], true);
testScenes[i + 1] = new EditorBuildSettingsScene(allPaths[i], true);
}
Debug.Log("Do build in : " + Application.dataPath + "/../Builds/GraphicTests/GraphicTestBuildPC.exe");

if (!AssetDatabase.IsValidFolder("Assets/Resources")) AssetDatabase.CreateFolder("Assets", "Resources");
for (int i=0; i<templates.Length;++i)
for (int i = 0; i < templates.Length; ++i)
newPaths[i] = "Assets/Resources/" + System.IO.Path.GetFileName( oldPaths[i] );
newPaths[i] = "Assets/Resources/" + System.IO.Path.GetFileName(oldPaths[i]);
//Debug.Log("Move " + oldPaths[i] + " to " + newPaths[i]);

2
TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/Framework/TestFixture.cs


}
public ParameterizedTestFixture(string eq1, string eq2)
: this(eq1, eq2, null) { }
: this(eq1, eq2, null) {}
public ParameterizedTestFixture(int eq1, int eq2, int neq)
{

42
TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/Framework/TestFramework.cs


// Change the SRP before a full batch of tests
public virtual string _SRP_ID { get { return "NONE"; } }
[MenuItem("Internal/GraphicTest Tools/Set Tests Pipelines",false, 0)]
[MenuItem("Internal/GraphicTest Tools/Set Tests Pipelines", false, 0)]
"Graphic Tests",
"Do you want to run the test(s) on all available Render Pipeline assets or only the first (main) one ?",
"Hell YEAH, go for it !",
"No thanks, just one please.");
"Graphic Tests",
"Do you want to run the test(s) on all available Render Pipeline assets or only the first (main) one ?",
"Hell YEAH, go for it !",
"No thanks, just one please.");
}
private static bool? _doOnlyFirstRenderPipelineAsset;

{
string absolutePath = TestFrameworkTools.s_Path.Aggregate(TestFrameworkTools.s_RootPath, Path.Combine);
string filePath = Path.Combine(absolutePath, TestFrameworkTools.renderPipelineAssets[_SRP_ID] );
string filePath = Path.Combine(absolutePath, TestFrameworkTools.renderPipelineAssets[_SRP_ID]);
filePath = filePath.Replace(Application.dataPath, "");

wantedTestsRenderPipeAsset = GetRenderPipelineAsset(_SRP_ID);
if (wantedTestsRenderPipeAsset != beforeTestsRenderPipeAsset)
UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset = wantedTestsRenderPipeAsset;
}

public void RestoreSceneManagerSetup()
{
if ( (sceneManagerSetupBeforeTest == null) || ( sceneManagerSetupBeforeTest.Length == 0 ) )
if ((sceneManagerSetupBeforeTest == null) || (sceneManagerSetupBeforeTest.Length == 0))
{
EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
}

}
}
public int qualityLevel = 0;
public void SetupQualitySettings()

throw new Exception("Missing QualitySetting");
}
QualitySettings.SetQualityLevel( qualityNames.IndexOf("Graphic Tests"));
QualitySettings.SetQualityLevel(qualityNames.IndexOf("Graphic Tests"));
QualitySettings.masterTextureLimit = 0;
QualitySettings.anisotropicFiltering = AnisotropicFiltering.ForceEnable;

QualitySettings.asyncUploadBufferSize = 4;
QualitySettings.antiAliasing = 0;
QualitySettings.SetQualityLevel( qualityNames.IndexOf("Graphic Tests"), true);
QualitySettings.SetQualityLevel(qualityNames.IndexOf("Graphic Tests"), true);
}
public void RestoreQualitySettings()

// the actual test
public static IEnumerator TestScene(TestFrameworkTools.TestInfo testInfo)
{
var prjRelativeGraphsPath = TestFrameworkTools.s_Path.Aggregate(TestFrameworkTools.s_RootPath, Path.Combine);
var filePath = Path.Combine(prjRelativeGraphsPath, testInfo.relativePath);
var prjRelativeGraphsPath = TestFrameworkTools.s_Path.Aggregate(TestFrameworkTools.s_RootPath, Path.Combine);
var filePath = Path.Combine(prjRelativeGraphsPath, testInfo.relativePath);
// open the scene
// open the scene
SetupSceneForRenderPipelineTest testSetup = Object.FindObjectOfType<SetupSceneForRenderPipelineTest> ();
Assert.IsNotNull(testSetup, "No SetupSceneForRenderPipelineTest in scene " + testInfo.name);
Assert.IsNotNull(testSetup.cameraToUse, "No configured camera in <SetupSceneForRenderPipelineTest>");
SetupSceneForRenderPipelineTest testSetup = Object.FindObjectOfType<SetupSceneForRenderPipelineTest>();
Assert.IsNotNull(testSetup, "No SetupSceneForRenderPipelineTest in scene " + testInfo.name);
Assert.IsNotNull(testSetup.cameraToUse, "No configured camera in <SetupSceneForRenderPipelineTest>");
for (int r = 0; r < (doOnlyFirstRenderPipelineAsset?1:testSetup.renderPipelines.Length); ++r)
for (int r = 0; r < (doOnlyFirstRenderPipelineAsset ? 1 : testSetup.renderPipelines.Length); ++r)
if (r==0)
if (r == 0)
testSetup.Setup();
else
testSetup.Setup(r);

// Add associated renderpipeline label image if it exists
string rpLabelPath = AssetDatabase.GetAssetPath(testSetup.renderPipelines[r]);
Texture2D rpLabel = AssetDatabase.LoadAssetAtPath<Texture2D>(rpLabelPath.Remove(rpLabelPath.Length - 5)+"png");
Texture2D rpLabel = AssetDatabase.LoadAssetAtPath<Texture2D>(rpLabelPath.Remove(rpLabelPath.Length - 5) + "png");
if (rpLabel != null)
{
Color[] rpLabelPixels = rpLabel.GetPixels();

public override string _SRP_ID { get { return "HDRP"; } }
[UnityTest]
public IEnumerator HDRP_Test([ValueSource(typeof(TestFrameworkTools.CollectScenes), "HDRP")]TestFrameworkTools.TestInfo testInfo)
public IEnumerator HDRP_Test([ValueSource(typeof(TestFrameworkTools.CollectScenes), "HDRP")] TestFrameworkTools.TestInfo testInfo)
{
return TestScene(testInfo);
}

public override string _SRP_ID { get { return "LWRP"; } }
[UnityTest]
public IEnumerator LWRP_Test([ValueSource(typeof(TestFrameworkTools.CollectScenes), "LWRP")]TestFrameworkTools.TestInfo testInfo)
public IEnumerator LWRP_Test([ValueSource(typeof(TestFrameworkTools.CollectScenes), "LWRP")] TestFrameworkTools.TestInfo testInfo)
{
return TestScene(testInfo);
}

28
TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/Framework/TestResultWindow.cs


diffMaterial = new Material(Shader.Find("GraphicTests/ComparerShader"));
diffMaterial.hideFlags = HideFlags.HideAndDontSave;
switch(TestFrameworkTools.comparisonMethod)
switch (TestFrameworkTools.comparisonMethod)
break;
break;
break;
break;
break;
break;
}
DontDestroyOnLoad(diffMaterial);

tmpPath = "";
GetTemplateImage();
string templatePath = Path.Combine( TestFrameworkTools.s_RootPath, "ImageTemplates");
string templatePath = Path.Combine(TestFrameworkTools.s_RootPath, "ImageTemplates");
templateLocation = Path.Combine(templatePath, string.Format("{0}.{1}", tmpPath, "png"));
GetDiffMaterial();

GUILayout.BeginHorizontal(GUILayout.Height(topBarHeight));
{
if (GUILayout.Button(reloadContent))
Reload(sceneAsset.name+".unity");
Reload(sceneAsset.name + ".unity");
if (GUILayout.Button(wipeResultContent))
{

GUILayout.Label("Diff. type: ");
diffStyle = EditorGUILayout.IntPopup(diffStyle, diffStylesList, diffStylesValues,
GUILayout.Width(200f));
GUILayout.Width(200f));
}
GUILayout.EndHorizontal();

GUI.color = Color.green;
if (rect1.width > 0) GUI.Box(rect1, "Template");
GUI.color = Color.black;
if (rect2.width > 0) GUI.Box(rect2, "Diff" );
if (rect2.width > 0) GUI.Box(rect2, "Diff");
GUI.color = Color.blue;
if (rect3.width > 0) GUI.Box(rect3, "Result");

Rect textureRect = new Rect(leftBarWidth, topBarHeight * 3, position.width - leftBarWidth,position.height - topBarHeight * 3);
Rect textureRect = new Rect(leftBarWidth, topBarHeight * 3, position.width - leftBarWidth, position.height - topBarHeight * 3);
GUI.enabled = true;
CheckDataObjects();

{
TreeViewItem parent = hdrpParent;
string folder = Path.GetDirectoryName( info.templatePath ).Split("\\"[0]).Last();
string folder = Path.GetDirectoryName(info.templatePath).Split("\\"[0]).Last();
if (hdrpFolders.ContainsKey(folder))
{
parent = hdrpFolders[folder];

var prjRelativeGraphsPath = TestFrameworkTools.s_Path.Aggregate(TestFrameworkTools.s_RootPath, Path.Combine);
var filePath = Path.Combine(prjRelativeGraphsPath, info.relativePath);
filePath = string.Format("Assets{0}", filePath.Replace(Application.dataPath, "") );
filePath = string.Format("Assets{0}", filePath.Replace(Application.dataPath, ""));
SceneAsset sceneObject = AssetDatabase.LoadAssetAtPath<SceneAsset>(filePath);

{
TreeViewItem parent = lwrpParent;
string folder = Path.GetDirectoryName( info.templatePath ).Split("\\"[0]).Last();
string folder = Path.GetDirectoryName(info.templatePath).Split("\\"[0]).Last();
if (lwrpFolders.ContainsKey(folder))
{
parent = lwrpFolders[folder];

protected override void SelectionChanged(IList<int> selectedIds)
{
if (selectedIds.Count < 1 ) return;
if (selectedIds.Count < 1) return;
if ( item.hasChildren ) return; // not a scene (final) item
if (item.hasChildren) return; // not a scene (final) item
//TestResultViewItem testItem = (TestResultViewItem)item;

44
TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/HDRenderPipeline/PlayModeTest/PlayModeTestsUI.cs


{
get
{
if (_instance == null )
if (_instance == null)
{
_instance = FindObjectOfType<PlayModeTestsUI>();
}

[SerializeField] RawImage resultImage;
Material resultComparerMaterial;
[SerializeField] Gradient fillGradient = new Gradient() { colorKeys = new GradientColorKey[] {
new GradientColorKey( Color.red, 0.5f),
new GradientColorKey( Color.yellow, 0.75f),
new GradientColorKey( Color.green, 0.97f),
} };
[SerializeField] Gradient fillGradient = new Gradient() {
colorKeys = new GradientColorKey[] {
new GradientColorKey(Color.red, 0.5f),
new GradientColorKey(Color.yellow, 0.75f),
new GradientColorKey(Color.green, 0.97f),
}
};
int numOfResults = 1;
List<GameObject> testResults;

Image waitingImage;
// Use this for initialization
void Start ()
void Start()
{
// kill itself if already in scene.
if (Exists)

// Set scroll view content to fit all results
scrollView.content.anchorMin = new Vector2(0f, 0f);
scrollView.content.anchorMax = new Vector2(1f, 0f);
scrollView.content.offsetMin = new Vector2(0f, - (UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings - 1f) * 200f);
scrollView.content.offsetMin = new Vector2(0f, -(UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings - 1f) * 200f);
scrollView.content.offsetMax = new Vector2(0f, 0f);
// Init results arrays

singleTestResult.offsetMax = new Vector2(0, singleTestResult.offsetMin.y + 200f);
int sceneIndex = i;
singleTestResult.GetComponent<Button>().onClick.AddListener(delegate () { LoadSceneResult(sceneIndex); });
singleTestResult.GetComponent<Button>().onClick.AddListener(delegate() { LoadSceneResult(sceneIndex); });
//* Test the values
SetResult(i, 1.0f * i / (numOfResults - 1), 0.5f);

scrollView.Rebuild( UnityEngine.UI.CanvasUpdate.PostLayout );
scrollView.Rebuild(UnityEngine.UI.CanvasUpdate.PostLayout);
eventSystem = GetComponentInChildren<EventSystem>();
eventSystem.SetSelectedGameObject(testResults[0]);

scenePanel.SetActive(false);
resultComparerMaterial = Instantiate( resultImage.material );
resultComparerMaterial = Instantiate(resultImage.material);
resultImage.material = resultComparerMaterial;
// Initialize render textures

resultsMaxValue[_index].text = maxResults[_index].ToString() + "%";
resultsMaxFill[_index].localScale = new Vector3(_maxValue, 1f, 1f);
resultsAvgFill[_index].GetComponent<Image>().color = fillGradient.Evaluate(1f-_maxValue);
resultsAvgFill[_index].GetComponent<Image>().color = fillGradient.Evaluate(1f - _maxValue);
}
void CalculateOverall()

for (int i=0; i<numOfResults; ++i)
for (int i = 0; i < numOfResults; ++i)
{
overallAvgResult += 1.0f * avgResults[i];
overallMaxResult += 1.0f * maxResults[i];

overallMaxFill.localScale = new Vector3(overallMaxResult * 0.01f, 1f, 1f);
overallMaxText.text = Mathf.RoundToInt(overallMaxResult).ToString() + "%";
overallMaxFill.GetComponent<Image>().color = fillGradient.Evaluate(1f- overallMaxResult * 0.01f);
overallMaxFill.GetComponent<Image>().color = fillGradient.Evaluate(1f - overallMaxResult * 0.01f);
}
IEnumerator CalculateAllResults()

waitingImage.fillAmount = 0f;
for (int i=0; i<numOfResults;++i)
for (int i = 0; i < numOfResults; ++i)
waitingImage.fillAmount = 1f * (1f+i) / numOfResults;
waitingImage.fillAmount = 1f * (1f + i) / numOfResults;
waitingImage.color = Color.Lerp(Color.blue, Color.green, 1f * i / (numOfResults - 1));
}

sumOfSquaredColorDistances += (diff.r + diff.g + diff.b) / 3.0f;
}
return new Vector2( Mathf.Sqrt(sumOfSquaredColorDistances / numberOfPixels), maxSquaredColorDistance );
return new Vector2(Mathf.Sqrt(sumOfSquaredColorDistances / numberOfPixels), maxSquaredColorDistance);
if ((_index <0 ) || (_index >= ( UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings-1))) return;
if ((_index < 0) || (_index >= (UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings - 1))) return;
Debug.Log("Load Scene Results : " + _index);

}
// Update is called once per frame
void Update ()
void Update()
{
if (resultsPanel.activeSelf)
{

scenePanel.SetActive(false);
}
}
}
}
}

26
TestProjects/GraphicsTests/Assets/Tests/Scripts/Editor/GraphicTests/LWPipeline/040_UpgradeScene/LWSceneConverter.cs


using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

using UnityEditor.Experimental.Rendering.LightweightPipeline;
public class LWSceneConverter : MonoBehaviour
public class LWSceneConverter : MonoBehaviour
//[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Convert Legacy Scene Materials", false, 3)]
//[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Convert Legacy Scene Materials", false, 3)]
static void CollectMaterialsInScene ()
static void CollectMaterialsInScene()
{
_materials.Add(RenderSettings.skybox);

List<Renderer> renderers = new List<Renderer>();
foreach(GameObject go in rootItems)
{
foreach (GameObject go in rootItems)
{
foreach(Renderer rend in renderers)
{
foreach (Renderer rend in renderers)
{
if (rend != null)
{
Material[] mat = rend.sharedMaterials;

}
//[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Revert Legacy Scene Materials", false, 4)]
static void RevertMaterials(){
static void RevertMaterials()
{
CollectMaterialsInScene();
foreach (Material mat in _materials)

GraphicsSettings.renderPipelineAsset = null;
}
static string GetBackupPath(string path){
static string GetBackupPath(string path)
{
string[] splitPath = path.Split(new char[] { '/' });
splitPath[splitPath.Length - 2] = "Backup";
string newPath = splitPath[0];

}
return newPath;
}
}

26
TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/Framework/AdditionalTestSceneInfos.cs


using System.Collections;
using System.Collections;
[CreateAssetMenu(fileName = "AdditionalTestSceneInfos", menuName = "Render Pipeline/Tests/AdditionalTestSceneInfos", order = 20)]
public class AdditionalTestSceneInfos : ScriptableObject
{
public AdditionalTestSceneInfo[] additionalInfos;
[CreateAssetMenu(fileName = "AdditionalTestSceneInfos", menuName = "Render Pipeline/Tests/AdditionalTestSceneInfos", order = 20)]
public class AdditionalTestSceneInfos : ScriptableObject
{
public AdditionalTestSceneInfo[] additionalInfos;
[System.Serializable]
public struct AdditionalTestSceneInfo
{
public string name;
public string comment;
}
}
}
[System.Serializable]
public struct AdditionalTestSceneInfo
{
public string name;
public string comment;
}
}
}

16
TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/Framework/GotoNextScene.cs


using UnityEngine;
using UnityEngine;
public class GotoNextScene : MonoBehaviour
public class GotoNextScene : MonoBehaviour
public int m_NextSceneIndex = 0;
public int m_NextSceneIndex = 0;
void Update()
{
if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began)
SceneManager.LoadScene(m_NextSceneIndex);
}
void Update()
{
if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began)
SceneManager.LoadScene(m_NextSceneIndex);
}
}

44
TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/Framework/SetupSceneForRenderPipelineTest.cs


namespace UnityEngine.Experimental.Rendering
{
public class SetupSceneForRenderPipelineTest : MonoBehaviour, IMonoBehaviourTest
{
private RenderPipelineAsset m_OriginalAsset;
public RenderPipelineAsset[] renderPipelines;
public class SetupSceneForRenderPipelineTest : MonoBehaviour, IMonoBehaviourTest
{
private RenderPipelineAsset m_OriginalAsset;
public RenderPipelineAsset[] renderPipelines;
public bool hdr = false;
public int msaaSamples = 1;
public bool hdr = false;
public int msaaSamples = 1;
public int width = 1280;
public int height = 720;
public int width = 1280;
public int height = 720;
public UnityEvent thingToDoBeforeTest;

public void Update()
{
if ( waitedFrames < waitForFrames )
if (waitedFrames < waitForFrames)
{
++waitedFrames;
}

}
}
public void Setup()
{
m_OriginalAsset = GraphicsSettings.renderPipelineAsset;
public void Setup()
{
m_OriginalAsset = GraphicsSettings.renderPipelineAsset;
{
if (m_OriginalAsset != renderPipelines[index])
{
{
if (m_OriginalAsset != renderPipelines[index])
{
GraphicsSettings.renderPipelineAsset = renderPipelines[index];
GraphicsSettings.renderPipelineAsset = renderPipelines[index];
HDRenderPipelineAsset m_Asset = (HDRenderPipelineAsset) renderPipelines[index];
additionalCameraData.UpdateDirtyFrameSettings(true, m_Asset.GetFrameSettings() );
HDRenderPipelineAsset m_Asset = (HDRenderPipelineAsset)renderPipelines[index];
additionalCameraData.UpdateDirtyFrameSettings(true, m_Asset.GetFrameSettings());
public void TearDown()
{
public void TearDown()
{
if (GraphicsSettings.renderPipelineAsset != m_OriginalAsset)
{
GraphicsSettings.renderPipelineAsset = m_OriginalAsset;

//EditorApplication.isPlaying = false;
}
}
public bool IsTestFinished
{

}
}
}
}
}

19
TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/Framework/TestFrameworkPlayMode.cs


#if UNITY_EDITOR
UnityEditor.EditorBuildSettingsScene[] oldScenes;
#endif
public void Setup()
{
#if UNITY_EDITOR

foreach ( TestFrameworkTools.TestInfo testInfo in TestFrameworkTools.CollectScenesPlayMode.GetScenesForPipelineID(pipelineID))
foreach (TestFrameworkTools.TestInfo testInfo in TestFrameworkTools.CollectScenesPlayMode.GetScenesForPipelineID(pipelineID))
sceneSetups.Add(new UnityEditor.EditorBuildSettingsScene {
sceneSetups.Add(new UnityEditor.EditorBuildSettingsScene
{
path = testInfo.relativePath,
enabled = true
});

public IEnumerator TestScene(TestFrameworkTools.TestInfo testInfo)
{
// open the scene
UnityEngine.SceneManagement.SceneManager.LoadScene( testInfo.sceneListIndex , UnityEngine.SceneManagement.LoadSceneMode.Single);
UnityEngine.SceneManagement.SceneManager.LoadScene(testInfo.sceneListIndex , UnityEngine.SceneManagement.LoadSceneMode.Single);
yield return null; // wait one "frame" to let the scene load

// Setup Render Target
Camera testCamera = testSetup.cameraToUse;
var rtDesc = new RenderTextureDescriptor(
testSetup.width,
testSetup.height,
(testSetup.hdr && testCamera.allowHDR) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32,
24);
testSetup.width,
testSetup.height,
(testSetup.hdr && testCamera.allowHDR) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32,
24);
//rtDesc.sRGB = PlayerSettings.colorSpace == ColorSpace.Linear;
rtDesc.msaaSamples = testSetup.msaaSamples;

public override string pipelineID { get { return "HDRP"; } }
[UnityTest]
new public IEnumerator TestScene([ValueSource(typeof(TestFrameworkTools.CollectScenesPlayMode), "HDRP")]TestFrameworkTools.TestInfo testInfo)
new public IEnumerator TestScene([ValueSource(typeof(TestFrameworkTools.CollectScenesPlayMode), "HDRP")] TestFrameworkTools.TestInfo testInfo)
{
return base.TestScene(testInfo);
}

147
TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/Framework/TestFrameworkTools.cs


public static float compareThreshold = 0.01f;
public static int frameWait = 100;
public enum ComparisonMethod {RMSE, Jzazbz, Lab}
public enum ComparisonMethod { RMSE, Jzazbz, Lab }
public static ComparisonMethod comparisonMethod = ComparisonMethod.Lab;
public static readonly string s_RootPath = Directory.GetParent(Directory.GetFiles(Application.dataPath, "SRPMARKER", SearchOption.AllDirectories).First()).ToString();

{ "HDRP", "HDRenderPipeline/Scenes" },
{ "LWRP", "LightweightPipeline/Scenes" }
};
// info that gets generated for use
// in a dod way
public struct TestInfo

else
return string.Format("{0}: {1}", name, comment);
}
public static Dictionary<string, AdditionalTestSceneInfos.AdditionalTestSceneInfo> GetAdditionalInfos ( string path)
public static Dictionary<string, AdditionalTestSceneInfos.AdditionalTestSceneInfo> GetAdditionalInfos(string path)
{
Dictionary<string, AdditionalTestSceneInfos.AdditionalTestSceneInfo> o = new Dictionary<string, AdditionalTestSceneInfos.AdditionalTestSceneInfo>();

{
for (int i=0 ; i<additionalTestSceneInfos.additionalInfos.Length ; ++i)
for (int i = 0; i < additionalTestSceneInfos.additionalInfos.Length; ++i)
{
o[additionalTestSceneInfos.additionalInfos[i].name] = additionalTestSceneInfos.additionalInfos[i];
}

// Get the play mode scenes
List<string> playModeScenes = new List<string>();
foreach( TestInfo ti in CollectScenesPlayMode.GetScenesForPipeline( _pipelinePath ) )
foreach (TestInfo ti in CollectScenesPlayMode.GetScenesForPipeline(_pipelinePath))
var additionalInfos = GetAdditionalInfos( "Assets"+Path.Combine(filesPath.Replace(Application.dataPath, ""), "AdditionalTestSceneInfos.asset") );
var additionalInfos = GetAdditionalInfos("Assets" + Path.Combine(filesPath.Replace(Application.dataPath, ""), "AdditionalTestSceneInfos.asset"));
// construct all the needed test infos
for (int i = 0; i < allPaths_List.Count; ++i)

TestInfo testInfo = new TestInfo()
{
name = p.Name,
comment = additionalInfos.ContainsKey(sceneNum)? additionalInfos[sceneNum].comment:null,
comment = additionalInfos.ContainsKey(sceneNum) ? additionalInfos[sceneNum].comment : null,
relativePath = splitPaths.Last(),
templatePath = splitPaths.Last(),
threshold = compareThreshold,

string listFilePath = Path.Combine(filesPath, "EditorPlayModeTests.asset");
EditorPlayModeTests listFile = (EditorPlayModeTests) AssetDatabase.LoadMainAssetAtPath(listFilePath);
if ( listFile == null)
EditorPlayModeTests listFile = (EditorPlayModeTests)AssetDatabase.LoadMainAssetAtPath(listFilePath);
if (listFile == null)
{
AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<EditorPlayModeTests>(), listFilePath);
AssetDatabase.Refresh();

else
{
// Get the additional infos
var additionalInfos = GetAdditionalInfos( Path.Combine(filesPath, "AdditionalTestSceneInfos.asset") );
var additionalInfos = GetAdditionalInfos(Path.Combine(filesPath, "AdditionalTestSceneInfos.asset"));
for ( int i=0 ; i<listFile.scenesPath.Length ; ++i)
for (int i = 0; i < listFile.scenesPath.Length; ++i)
var p = new FileInfo( Path.Combine(filesPath, path ) );
var p = new FileInfo(Path.Combine(filesPath, path));
var split = s_Path.Aggregate("", Path.Combine);
split = string.Format("{0}{1}", split, Path.DirectorySeparatorChar);
var splitPaths = p.FullName.Split(new[] { split }, StringSplitOptions.RemoveEmptyEntries);

TestInfo testInfo = new TestInfo
{
name = p.Name,
comment = additionalInfos.ContainsKey(sceneNum)? additionalInfos[sceneNum].comment:null,
comment = additionalInfos.ContainsKey(sceneNum) ? additionalInfos[sceneNum].comment : null,
relativePath = p.ToString(),
templatePath = splitPaths.Last(),
threshold = compareThreshold,

}
}
#else
yield return "null";
yield return "null";
#endif
}
}

if (pixels1.Length != pixels2.Length)
return false;
for (int y = 0 ; y < captured.height ; y+=compareTileSize)
for (int y = 0; y < captured.height; y += compareTileSize)
for (int x = 0 ; x < captured.width ; x+=compareTileSize)
for (int x = 0; x < captured.width; x += compareTileSize)
for (int y2 = y ; y2 < Mathf.Min(captured.height, y+compareTileSize) ; ++y2)
for (int y2 = y; y2 < Mathf.Min(captured.height, y + compareTileSize); ++y2)
for (int x2 = x ; x2 < Mathf.Min(captured.width, x+compareTileSize) ; ++x2)
for (int x2 = x; x2 < Mathf.Min(captured.width, x + compareTileSize); ++x2)
Color p1 = pixels1[ y2 * captured.width + x2 ];
Color p2 = pixels2[ y2 * captured.width + x2 ];
Color p1 = pixels1[y2 * captured.width + x2];
Color p2 = pixels2[y2 * captured.width + x2];
Color diff;
switch (comparisonMethod)

break;
break;
break;
break;
break;
break;
float result = sumOffData / numberOfPixels;
if (result > threshold)
return false;

*/
}
public static Texture2D RenderSetupToTexture( SetupSceneForRenderPipelineTest _testSetup)
public static Texture2D RenderSetupToTexture(SetupSceneForRenderPipelineTest _testSetup)
_testSetup.width,
_testSetup.height,
(_testSetup.hdr && testCamera.allowHDR) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32,
24);
_testSetup.width,
_testSetup.height,
(_testSetup.hdr && testCamera.allowHDR) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32,
24);
#if UNITY_EDITOR
rtDesc.sRGB = PlayerSettings.colorSpace == ColorSpace.Linear;

return GetTemplateImage(testInfo);
}
public static void TestWithMessages( bool? _comparison, string _fail = "Test failed", string _pass = null )
public static void TestWithMessages(bool? _comparison, string _fail = "Test failed", string _pass = null)
{
if (_comparison.HasValue)
{

// Folowing color conversion code source : https://github.com/nschloe/colorio
// RGB to XYZ 100 : file:///C:/Users/Remy/Downloads/srgb.pdf
static Vector3 RGB2XYZ ( Color color )
static Vector3 RGB2XYZ(Color color)
) * 100;
) * 100;
static Vector3 RGB2JzAzBz (Color color)
static Vector3 RGB2JzAzBz(Color color)
Vector3 xyz = RGB2XYZ( color);
Vector3 xyz = RGB2XYZ(color);
float b = 1.15f;
float g = 0.66f;

float n = 0.15930175781f; // 2610/2^14
float p= 134.034375f; // 1.7*2523/2^5
float p = 134.034375f; // 1.7*2523/2^5
float x2 = b * xyz.x - (b-1) * xyz.z;
float y2 = g * xyz.y - (g-1) * xyz.x;
float x2 = b * xyz.x - (b - 1) * xyz.z;
float y2 = g * xyz.y - (g - 1) * xyz.x;
0.41478372f * x2 + 0.579999f * y2 + 0.0146480f * xyz.z,
-0.2015100f * x2 + 1.120649f * y2 + 0.0531008f * xyz.z,
-0.0166008f * x2 + 0.264800f * y2 + 0.6684799f * xyz.z
);
0.41478372f * x2 + 0.579999f * y2 + 0.0146480f * xyz.z,
-0.2015100f * x2 + 1.120649f * y2 + 0.0531008f * xyz.z,
-0.0166008f * x2 + 0.264800f * y2 + 0.6684799f * xyz.z
);
Vector3 lmsPowN = Vec3Pow(lms/10000f, n);
Vector3 lmsPowN = Vec3Pow(lms / 10000f, n);
Vector3.one * c1 + c2 * lmsPowN ,
Vector3.one + c3 * lmsPowN
);
Vector3.one * c1 + c2 * lmsPowN ,
Vector3.one + c3 * lmsPowN
);
Vector3 lms2 = Vec3Pow( tmp , p ) ;
Vector3 lms2 = Vec3Pow(tmp , p);
0.5f * lms2.x + 0.5f * lms2.y,
3.524000f * lms2.x + -4.066708f * lms2.y + 0.542708f * lms2.z,
0.199076f * lms2.x + 1.096799f * lms2.y + -1.295875f * lms2.z
);
0.5f * lms2.x + 0.5f * lms2.y,
3.524000f * lms2.x + -4.066708f * lms2.y + 0.542708f * lms2.z,
0.199076f * lms2.x + 1.096799f * lms2.y + -1.295875f * lms2.z
);
jab.x = (((1f+d)*jab.x)/(1f+d*jab.x))-d0;
jab.x = (((1f + d) * jab.x) / (1f + d * jab.x)) - d0;
static float JzAzBzDiff( Vector3 v1, Vector3 v2)
static float JzAzBzDiff(Vector3 v1, Vector3 v2)
float c1 = Mathf.Sqrt(v1.y*v1.y + v1.z*v1.z);
float c2 = Mathf.Sqrt(v2.y*v2.y + v2.z*v2.z);
float c1 = Mathf.Sqrt(v1.y * v1.y + v1.z * v1.z);
float c2 = Mathf.Sqrt(v2.y * v2.y + v2.z * v2.z);
float h1 = Mathf.Atan(v1.z/v1.y);
float h2 = Mathf.Atan(v2.z/v2.y);
float h1 = Mathf.Atan(v1.z / v1.y);
float h2 = Mathf.Atan(v2.z / v2.y);
float deltaH = 2*Mathf.Sqrt( c1*c2 ) * Mathf.Sin((h1-h2)/2f);
float deltaH = 2 * Mathf.Sqrt(c1 * c2) * Mathf.Sin((h1 - h2) / 2f);
return Mathf.Sqrt( Mathf.Pow( v1.x-v2.x ,2f) + Mathf.Pow(c1-c2, 2f) + deltaH * deltaH );
return Mathf.Sqrt(Mathf.Pow(v1.x - v2.x , 2f) + Mathf.Pow(c1 - c2, 2f) + deltaH * deltaH);
static Vector3 RGB2Lab( Color color )
static Vector3 RGB2Lab(Color color)
Vector3 xyz = RGB2XYZ( color);
Vector3 xyz = RGB2XYZ(color);
float xn = 95.047f;
float yn = 100f;

116f * XYZ2LabFunc( xyz.y / yn ) - 16f,
500f * ( XYZ2LabFunc(xyz.x / xn) - XYZ2LabFunc(xyz.y/yn) ),
116f * XYZ2LabFunc(xyz.y / yn) - 16f,
500f * (XYZ2LabFunc(xyz.x / xn) - XYZ2LabFunc(xyz.y / yn)),
);
);
static float XYZ2LabFunc( float f )
static float XYZ2LabFunc(float f)
float delta = 6f/29f;
float delta = 6f / 29f;
if ( f > delta )
return Mathf.Pow(f, 1f/3f);
if (f > delta)
return Mathf.Pow(f, 1f / 3f);
return f/(3*delta*delta) + 4f / 29f;
return f / (3 * delta * delta) + 4f / 29f;
static Vector3 Vec3Pow (Vector3 v, float p)
static Vector3 Vec3Pow(Vector3 v, float p)
);
);
static Vector3 Vec3Divide(Vector3 a, Vector3 b )
static Vector3 Vec3Divide(Vector3 a, Vector3 b)
return new Vector3(a.x/b.x, a.y/b.y, a.z/b.z);
return new Vector3(a.x / b.x, a.y / b.y, a.z / b.z);
}
}
}

16
TestProjects/GraphicsTests/Assets/Tests/Scripts/GraphicTests/LWPipeline/040_UpgradeScene/RandomAnimationPoint.cs


using System.Collections;
using System.Collections;
public class RandomAnimationPoint : MonoBehaviour {
public class RandomAnimationPoint : MonoBehaviour
{
public Animator anim;
public Animator anim;
{
{
if (anim != null)
{
Random.InitState(seed);

}
}
void OnRenderObject(){
if(anim != null)
void OnRenderObject()
{
if (anim != null)
}

3
TestProjects/ShaderGraph/Assets/Testing/Editor/TestMaterialGraph.cs


namespace UnityEditor.ShaderGraph
namespace UnityEditor.ShaderGraph
}
}

3
TestProjects/ShaderGraph/Assets/Testing/Editor/TestNode.cs


namespace UnityEditor.ShaderGraph
namespace UnityEditor.ShaderGraph
}
}

2
TestProjects/ShaderGraph/Assets/Testing/Editor/TestSlot.cs


using UnityEditor.Graphing;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{

4
build.py


"com.unity.render-pipelines.lightweight",
"com.unity.render-pipelines.high-definition",
"com.unity.shadergraph"
]
]
try:
import unity_package_build
build_log = unity_package_build.setup()

4
com.unity.render-pipelines.core/CoreRP/Camera/CameraSwitcher.cs


m_OriginalCamera = GetComponent<Camera>();
m_CurrentCamera = m_OriginalCamera;
if(m_OriginalCamera == null)
if (m_OriginalCamera == null)
{
Debug.LogError("Camera Switcher needs a Camera component attached");
return;

void SetCameraIndex(int index)
{
if(index > 0 || index < GetCameraCount())
if (index > 0 || index < GetCameraCount())
{
m_CurrentCameraIndex = index;

2
com.unity.render-pipelines.core/CoreRP/Common/CommandBufferPool.cs


using System.Collections.Generic;
using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine.Rendering;

2
com.unity.render-pipelines.core/CoreRP/Common/ComponentSingleton.cs


namespace UnityEngine.Experimental.Rendering
namespace UnityEngine.Experimental.Rendering
{
// Use this class to get a static instance of a component
// Mainly used to have a default instance

4
com.unity.render-pipelines.core/CoreRP/Common/ObservableList.cs


using System;
using System;
using System.Collections;
using System.Collections.Generic;

}
public ObservableList()
: this(0) { }
: this(0) {}
public ObservableList(int capacity)
{

4
com.unity.render-pipelines.core/CoreRP/Common/RectInt.cs


namespace UnityEngine.Experimental.Rendering
{
public struct RectInt
public struct RectInt
{
public static readonly RectInt zero = new RectInt(0, 0, 0, 0);

this.height = height;
}
}
}
}

2
com.unity.render-pipelines.core/CoreRP/Common/SerializedDictionary.cs


using System;
using System;
using System.Collections.Generic;
namespace UnityEngine.Experimental.Rendering

2
com.unity.render-pipelines.core/CoreRP/CoreResources/BlitCubeTextureFace.shader


Shader "Hidden/SRP/BlitCubeTextureFace"
Shader "Hidden/SRP/BlitCubeTextureFace"
{
SubShader
{

2
com.unity.render-pipelines.core/CoreRP/CoreResources/CubeToPano.shader


uint2 pixCoord = ((uint2) i.vertex.xy);
half3 dir = SphericalTexCoordinateToDirection(i.texcoord.xy);
return (half4) UNITY_SAMPLE_TEXCUBE_LOD(_srcCubeTexture, dir, (float) _cubeMipLvl);
}

2
com.unity.render-pipelines.core/CoreRP/CoreResources/GPUCopy.compute


{
_Result1[_RectOffset + dispatchThreadId] = LOAD_TEXTURE2D(_Source4, _RectOffset + dispatchThreadId).x;
}

28
com.unity.render-pipelines.core/CoreRP/CoreResources/GPUCopy.cs


static readonly int _Result1 = Shader.PropertyToID("_Result1");
static readonly int _Source4 = Shader.PropertyToID("_Source4");
void SampleCopyChannel(
CommandBuffer cmd,
CommandBuffer cmd,
RenderTargetIdentifier source,
RenderTargetIdentifier source,
int _target,
RenderTargetIdentifier target,
int kernel8,

unsafe
unsafe
{
RectInt* dispatch1Rects = stackalloc RectInt[3];
int dispatch1RectCount = 0;

rect,
8,
out main,
out topRow,
out rightCol,
out topRight))
rect,
8,
out main,
out topRow,
out rightCol,
out topRight))
{
if (topRow.width > 0 && topRow.height > 0)
{

cmd.SetComputeIntParams(m_Shader, _RectOffset, (int)r.x, (int)r.y);
cmd.DispatchCompute(m_Shader, kernel8, (int)Mathf.Max(r.width / 8, 1), (int)Mathf.Max(r.height / 8, 1), 1);
}
for (int i = 0, c = dispatch1RectCount; i < c; ++i)
{
var r = dispatch1Rects[i];

}
}
public void SampleCopyChannel_xyzw2x(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, RectInt rect)
{
SampleCopyChannel(cmd, rect, _Source4, source, _Result1, target, k_SampleKernel_xyzw2x_8, k_SampleKernel_xyzw2x_1);
}
public void SampleCopyChannel_xyzw2x(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, RectInt rect)
{
SampleCopyChannel(cmd, rect, _Source4, source, _Result1, target, k_SampleKernel_xyzw2x_8, k_SampleKernel_xyzw2x_1);
}
}
}

28
com.unity.render-pipelines.core/CoreRP/CoreResources/GPUCopyAsset.cs


using System;
using System;
using System.Collections.Generic;
using System.Text;

/// Declares what should be generated in utility code.
/// It will generate a compute shader and a C# class to use the compute shader with a ComputeBuffer
///
///
///
///
///
///
///
///
/// Initialization:
/// - You must set the generated ComputeShader as argument of the constructor of the generated GPUCopy C# class
/// </summary>

}
csm.AppendLine(@" void SampleCopyChannel(
CommandBuffer cmd,
CommandBuffer cmd,
RenderTargetIdentifier source,
RenderTargetIdentifier source,
int _target,
RenderTargetIdentifier target,
int kernel8,

unsafe
unsafe
{
RectInt* dispatch1Rects = stackalloc RectInt[3];
int dispatch1RectCount = 0;

rect,
rect,
out topRow,
out topRow,
out rightCol,
out topRight))
{

cmd.SetComputeIntParams(m_Shader, _RectOffset, (int)r.x, (int)r.y);
cmd.DispatchCompute(m_Shader, kernel8, (int)Mathf.Max(r.width / 8, 1), (int)Mathf.Max(r.height / 8, 1), 1);
}
for (int i = 0, c = dispatch1RectCount; i < c; ++i)
{
var r = dispatch1Rects[i];

cck.AppendLine(@"void KERNEL_NAME(uint2 dispatchThreadId : SV_DispatchThreadID)");
cck.AppendLine("{");
cck.AppendLine(string.Format(" _Result{0}[_RectOffset + dispatchThreadId] = LOAD_TEXTURE2D(_Source{1}, _RectOffset + dispatchThreadId).{2};",
o.targetChannel.ToString(), o.sourceChannel.ToString(), o.subscript));
o.targetChannel.ToString(), o.sourceChannel.ToString(), o.subscript));
cck.AppendLine("}");
cck.AppendLine();

// CSharp method
csm.AppendLine(string.Format(@" public void SampleCopyChannel_{0}2{1}(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier target, RectInt rect)", channelName, o.subscript));
csm.AppendLine (" {");
csm.AppendLine(" {");
csm.AppendLine (" }");
csm.AppendLine(" }");
}
csc.AppendLine(" }");

1
com.unity.render-pipelines.core/CoreRP/CoreResources/TexturePadding.cs


m_KMainTop = m_CS.FindKernel("KMainTop");
m_KMainRight = m_CS.FindKernel("KMainRight");
}
public void Pad(CommandBuffer cmd, RenderTexture inOutTexture, RectInt from, RectInt to)
{
if (from.width < to.width)

6
com.unity.render-pipelines.core/CoreRP/Debugging/DebugManager.cs


public static DebugManager instance { get { return s_Instance; } }
// Explicit static constructor to tell the C# compiler not to mark type as beforefieldinit
static DebugManager() { }
static DebugManager() {}
ReadOnlyCollection<DebugUI.Panel> m_ReadOnlyPanels;
readonly List<DebugUI.Panel> m_Panels = new List<DebugUI.Panel>();

}
}
public event Action<bool> onDisplayRuntimeUIChanged = delegate { };
public event Action onSetDirty = delegate { };
public event Action<bool> onDisplayRuntimeUIChanged = delegate {};
public event Action onSetDirty = delegate {};
public bool refreshEditorRequested;

2
com.unity.render-pipelines.core/CoreRP/Debugging/DebugUI.Containers.cs


namespace UnityEngine.Experimental.Rendering
namespace UnityEngine.Experimental.Rendering
{
public partial class DebugUI
{

2
com.unity.render-pipelines.core/CoreRP/Debugging/DebugUI.Fields.cs


}
}
public class BoolField : Field<bool> { }
public class BoolField : Field<bool> {}
public class IntField : Field<int>
{

4
com.unity.render-pipelines.core/CoreRP/Debugging/DebugUI.Panel.cs


using System;
using System;
namespace UnityEngine.Experimental.Rendering
{

public bool editorForceUpdate { get { return (flags & Flags.EditorForceUpdate) != 0; } }
public ObservableList<Widget> children { get; private set; }
public event Action<Panel> onSetDirty = delegate { };
public event Action<Panel> onSetDirty = delegate {};
public Panel()
{

2
com.unity.render-pipelines.core/CoreRP/Debugging/DebugUpdater.cs


namespace UnityEngine.Experimental.Rendering
namespace UnityEngine.Experimental.Rendering
{
public class DebugUpdater : MonoBehaviour
{

2
com.unity.render-pipelines.core/CoreRP/Debugging/MousePositionDebug.cs


var go = new GameObject("__GameViewEventCatcher");
go.hideFlags = HideFlags.HideAndDontSave;
s_Instance = go.AddComponent<GameViewEventCatcher>();
}
void Update()

break;
}
}
#endif
public void Build()

8
com.unity.render-pipelines.core/CoreRP/Debugging/Prefabs/Scripts/DebugUIHandlerPanel.cs


float GetYPosInScroll(RectTransform target)
{
var pivotOffset = new Vector3(
(0.5f - target.pivot.x) * target.rect.size.x,
(0.5f - target.pivot.y) * target.rect.size.y,
0f
);
(0.5f - target.pivot.x) * target.rect.size.x,
(0.5f - target.pivot.y) * target.rect.size.y,
0f
);
var localPos = target.localPosition + pivotOffset;
var worldPos = target.parent.TransformPoint(localPos);
return m_ScrollTransform.TransformPoint(worldPos).y;

10
com.unity.render-pipelines.core/CoreRP/Debugging/Prefabs/Scripts/DebugUIHandlerWidget.cs


protected DebugUI.Widget m_Widget;
protected virtual void OnEnable() { }
protected virtual void OnEnable() {}
internal virtual void SetWidget(DebugUI.Widget widget)
{

return true;
}
public virtual void OnDeselection() { }
public virtual void OnDeselection() {}
public virtual void OnAction() { }
public virtual void OnAction() {}
public virtual void OnIncrement(bool fast) { }
public virtual void OnIncrement(bool fast) {}
public virtual void OnDecrement(bool fast) { }
public virtual void OnDecrement(bool fast) {}
public virtual DebugUIHandlerWidget Previous()
{

3
com.unity.render-pipelines.core/CoreRP/Debugging/Prefabs/Scripts/UIFoldout.cs


using UnityEngine.UI;
using UnityEngine.UI;
namespace UnityEngine.Experimental.Rendering.UI
{

{
SetState(isOn, false);
}
#pragma warning restore 108,114
public void SetState(bool state)

6
com.unity.render-pipelines.core/CoreRP/Debugging/ProfilingSample.cs


bool m_Disposed;
CustomSampler m_Sampler;
public ProfilingSample(CommandBuffer cmd, string name,CustomSampler sampler = null)
public ProfilingSample(CommandBuffer cmd, string name, CustomSampler sampler = null)
{
m_Cmd = cmd;
m_Name = name;

}
// Shortcut to string.Format() using only one argument (reduces Gen0 GC pressure)
public ProfilingSample(CommandBuffer cmd, string format, object arg) : this(cmd,string.Format(format, arg))
public ProfilingSample(CommandBuffer cmd, string format, object arg) : this(cmd, string.Format(format, arg))
public ProfilingSample(CommandBuffer cmd, string format, params object[] args) : this(cmd,string.Format(format, args))
public ProfilingSample(CommandBuffer cmd, string format, params object[] args) : this(cmd, string.Format(format, args))
{
}

2
com.unity.render-pipelines.core/CoreRP/Editor/CameraEditorUtils.cs


using UnityEngine;
using UnityEngine;
using Object = UnityEngine.Object;
namespace UnityEditor.Experimental.Rendering

10
com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorDrawers.cs


using System;
using System;
using System.Collections.Generic;
using UnityEditor.AnimatedValues;
using UnityEngine;

public delegate AnimBool AnimBoolGetter(TUIState s, TData p, Editor owner);
public static readonly IDrawer space = Action((state, data, owner) => EditorGUILayout.Space());
public static readonly IDrawer noop = Action((state, data, owner) => { });
public static readonly IDrawer noop = Action((state, data, owner) => {});
public static IDrawer Group(params IDrawer[] drawers)
{

drawers[i].Draw(s, d, o);
EditorGUIUtility.labelWidth = l;
}
);
);
}
public static IDrawer Action(params ActionDrawer[] drawers)

CoreEditorDrawer<T2UIState, T2Data>.IDrawer[] m_SourceDrawers;
public SelectDrawerInternal(StateSelect<T2UIState> stateSelect,
DataSelect<T2Data> dataSelect,
params CoreEditorDrawer<T2UIState, T2Data>.IDrawer[] otherDrawers)
DataSelect<T2Data> dataSelect,
params CoreEditorDrawer<T2UIState, T2Data>.IDrawer[] otherDrawers)
{
m_SourceDrawers = otherDrawers;
m_StateSelect = stateSelect;

2
com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorStyles.cs


using UnityEngine;
using UnityEngine;
namespace UnityEditor.Experimental.Rendering
{

2
com.unity.render-pipelines.core/CoreRP/Editor/CoreEditorUtils.cs


using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

4
com.unity.render-pipelines.core/CoreRP/Editor/CoreResources/GPUCopyAssetEditor.cs


using System.Collections;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;

var assetpath = AssetDatabase.GetAssetPath(target);
var dirpath = Path.GetDirectoryName(assetpath);
var targetpathcs = dirpath + "/GPUCopy.cs";
var targetpathcc =dirpath + "/GPUCopy.compute";
var targetpathcc = dirpath + "/GPUCopy.compute";
string cc, cs;
m_Target.Generate(out cc, out cs);

18
com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugState.cs


using System;
using System;
using UnityEngine;
using UnityEngine.Experimental.Rendering;

// Builtins
[Serializable, DebugState(typeof(DebugUI.BoolField), typeof(DebugUI.Foldout))]
public sealed class DebugStateBool : DebugState<bool> { }
public sealed class DebugStateBool : DebugState<bool> {}
public sealed class DebugStateInt : DebugState<int> { }
public sealed class DebugStateInt : DebugState<int> {}
public sealed class DebugStateUInt : DebugState<uint> { }
public sealed class DebugStateUInt : DebugState<uint> {}
public sealed class DebugStateFloat : DebugState<float> { }
public sealed class DebugStateFloat : DebugState<float> {}
public sealed class DebugStateColor : DebugState<Color> { }
public sealed class DebugStateColor : DebugState<Color> {}
public sealed class DebugStateVector2 : DebugState<Vector2> { }
public sealed class DebugStateVector2 : DebugState<Vector2> {}
public sealed class DebugStateVector3 : DebugState<Vector3> { }
public sealed class DebugStateVector3 : DebugState<Vector3> {}
public sealed class DebugStateVector4 : DebugState<Vector4> { }
public sealed class DebugStateVector4 : DebugState<Vector4> {}
}

6
com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugUIDrawer.cs


using System;
using System;
using UnityEngine;
using UnityEngine.Experimental.Rendering;

}
public virtual void Begin(DebugUI.Widget widget, DebugState state)
{ }
{}
public virtual bool OnGUI(DebugUI.Widget widget, DebugState state)
{

public virtual void End(DebugUI.Widget widget, DebugState state)
{ }
{}
protected void Apply(DebugUI.IValueField widget, DebugState state, object value)
{

42
com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugUIHandlerCanvasEditor.cs


using System;
using System;
using System.Linq;
using UnityEditor;
using UnityEditor.Experimental.Rendering;

{
drawHeaderCallback = rect => EditorGUI.LabelField(rect, "Widget Prefabs"),
drawElementCallback = (rect, index, isActive, isFocused) =>
{
var element = m_PrefabList.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 2f;
const float kTypeWidth = 100f;
{
var element = m_PrefabList.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 2f;
const float kTypeWidth = 100f;
// Type selector
var typeProp = element.FindPropertyRelative("type");
int typeIndex = ArrayUtility.IndexOf(s_Types, typeProp.stringValue);
typeIndex = Mathf.Max(typeIndex, 0);
typeIndex = EditorGUI.Popup(new Rect(rect.x, rect.y, kTypeWidth, EditorGUIUtility.singleLineHeight), typeIndex, s_DisplayTypes);
typeProp.stringValue = s_Types[typeIndex];
// Type selector
var typeProp = element.FindPropertyRelative("type");
int typeIndex = ArrayUtility.IndexOf(s_Types, typeProp.stringValue);
typeIndex = Mathf.Max(typeIndex, 0);
typeIndex = EditorGUI.Popup(new Rect(rect.x, rect.y, kTypeWidth, EditorGUIUtility.singleLineHeight), typeIndex, s_DisplayTypes);
typeProp.stringValue = s_Types[typeIndex];
// Prefab
EditorGUI.PropertyField(
new Rect(rect.x + kTypeWidth + 2f, rect.y, rect.width - kTypeWidth - 2f, EditorGUIUtility.singleLineHeight),
element.FindPropertyRelative("prefab"), GUIContent.none);
},
// Prefab
EditorGUI.PropertyField(
new Rect(rect.x + kTypeWidth + 2f, rect.y, rect.width - kTypeWidth - 2f, EditorGUIUtility.singleLineHeight),
element.FindPropertyRelative("prefab"), GUIContent.none);
},
{
var prefab = list.serializedProperty.GetArrayElementAtIndex(list.index).FindPropertyRelative("prefab").objectReferenceValue as GameObject;
if (prefab)
EditorGUIUtility.PingObject(prefab.gameObject);
}
{
var prefab = list.serializedProperty.GetArrayElementAtIndex(list.index).FindPropertyRelative("prefab").objectReferenceValue as GameObject;
if (prefab)
EditorGUIUtility.PingObject(prefab.gameObject);
}
};
}

26
com.unity.render-pipelines.core/CoreRP/Editor/Debugging/DebugWindow.cs


using System;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Callbacks;

#pragma warning disable 414
[Serializable]
sealed class WidgetStateDictionary : SerializedDictionary<string, DebugState> { }
sealed class WidgetStateDictionary : SerializedDictionary<string, DebugState> {}
sealed class DebugWindowSettings : ScriptableObject
{

// serialize is the same)
var attrType = typeof(DebugStateAttribute);
var stateTypes = assemblyTypes
.Where(
t => t.IsSubclassOf(typeof(DebugState))
&& t.IsDefined(attrType, false)
&& !t.IsAbstract
);
.Where(
t => t.IsSubclassOf(typeof(DebugState))
&& t.IsDefined(attrType, false)
&& !t.IsAbstract
);
s_WidgetStateMap = new Dictionary<Type, Type>();

// Drawers
attrType = typeof(DebugUIDrawerAttribute);
var types = assemblyTypes
.Where(
t => t.IsSubclassOf(typeof(DebugUIDrawer))
&& t.IsDefined(attrType, false)
&& !t.IsAbstract
);
.Where(
t => t.IsSubclassOf(typeof(DebugUIDrawer))
&& t.IsDefined(attrType, false)
&& !t.IsAbstract
);
s_WidgetDrawerMap = new Dictionary<Type, DebugUIDrawer>();

{
foreach (var state in m_WidgetStates)
{
if(state.Value == null)
if (state.Value == null)
{
return false;
}

2
com.unity.render-pipelines.core/CoreRP/Editor/Debugging/UIFoldoutEditor.cs


using UnityEngine.Experimental.Rendering.UI;
using UnityEngine.Experimental.Rendering.UI;
namespace UnityEditor.Experimental.Rendering.UI
{

2
com.unity.render-pipelines.core/CoreRP/Editor/IncludePaths/CoreShaderIncludePaths.cs


using System.Linq;
using System.Linq;
using UnityEngine;
using System.IO;

2
com.unity.render-pipelines.core/CoreRP/Editor/PropertyFetcher.cs


using System;
using System;
using System.Linq.Expressions;
using UnityEngine.Assertions;

2
com.unity.render-pipelines.core/CoreRP/Editor/SceneRenderPipeline.cs


using System;
using System;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;

4
com.unity.render-pipelines.core/CoreRP/Editor/ShaderGenerator/CSharpToHLSL.cs


ShaderTypeGenerator gen;
if (s_TypeName.TryGetValue(type.FullName, out gen))
{
Debug.LogError( "Duplicate typename with the GenerateHLSL attribute detected: " + type.FullName +
" declared in both " + gen.type.Assembly.FullName + " and " + type.Assembly.FullName + ". Skipping the second instance.");
Debug.LogError("Duplicate typename with the GenerateHLSL attribute detected: " + type.FullName +
" declared in both " + gen.type.Assembly.FullName + " and " + type.Assembly.FullName + ". Skipping the second instance.");
}
s_TypeName[type.FullName] = new ShaderTypeGenerator(type, attr as GenerateHLSL);
}

450
com.unity.render-pipelines.core/CoreRP/Editor/TextureCombiner/TextureCombiner.cs


using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

{
public static Texture2D _midGrey;
public static Texture2D midGrey
{
get
{
if (_midGrey == null)
_midGrey = TextureFromColor(Color.grey);
public static Texture2D _midGrey;
public static Texture2D midGrey
{
get
{
if (_midGrey == null)
_midGrey = TextureFromColor(Color.grey);
return _midGrey;
}
}
return _midGrey;
}
}
private static Dictionary<Color, Texture2D> singleColorTextures = new Dictionary<Color, Texture2D>();
private static Dictionary<Color, Texture2D> singleColorTextures = new Dictionary<Color, Texture2D>();
public static Texture2D TextureFromColor(Color color)
{
if (color == Color.white) return Texture2D.whiteTexture;
if (color == Color.black) return Texture2D.blackTexture;
public static Texture2D TextureFromColor(Color color)
{
if (color == Color.white) return Texture2D.whiteTexture;
if (color == Color.black) return Texture2D.blackTexture;
bool makeTexture = !singleColorTextures.ContainsKey(color);
if (!makeTexture)
makeTexture = (singleColorTextures[color] == null);
bool makeTexture = !singleColorTextures.ContainsKey(color);
if (!makeTexture)
makeTexture = (singleColorTextures[color] == null);
if (makeTexture)
{
Texture2D tex = new Texture2D(1,1, TextureFormat.ARGB32, false, true);
tex.SetPixel(0,0,color);
tex.Apply();
if (makeTexture)
{
Texture2D tex = new Texture2D(1, 1, TextureFormat.ARGB32, false, true);
tex.SetPixel(0, 0, color);
tex.Apply();
singleColorTextures[color] = tex;
}
return singleColorTextures[color];
}
singleColorTextures[color] = tex;
}
public static Texture GetTextureSafe( Material srcMaterial, string propertyName, Color fallback)
{
return GetTextureSafe( srcMaterial, propertyName, TextureFromColor(fallback) );
}
return singleColorTextures[color];
}
public static Texture GetTextureSafe( Material srcMaterial, string propertyName, Texture fallback)
{
if (!srcMaterial.HasProperty(propertyName))
return fallback;
public static Texture GetTextureSafe(Material srcMaterial, string propertyName, Color fallback)
{
return GetTextureSafe(srcMaterial, propertyName, TextureFromColor(fallback));
}
Texture tex = srcMaterial.GetTexture(propertyName);
if (tex == null)
return fallback;
else
return tex;
}
public static Texture GetTextureSafe(Material srcMaterial, string propertyName, Texture fallback)
{
if (!srcMaterial.HasProperty(propertyName))
return fallback;
public static TextureFormat[] TextureFormatsWithouthAlpha = new TextureFormat[]{
TextureFormat.ASTC_RGB_10x10 ,
TextureFormat.ASTC_RGB_12x12 ,
TextureFormat.ASTC_RGB_4x4 ,
TextureFormat.ASTC_RGB_5x5 ,
TextureFormat.ASTC_RGB_6x6 ,
TextureFormat.ASTC_RGB_8x8 ,
TextureFormat.BC4 ,
TextureFormat.BC5 ,
TextureFormat.DXT1 ,
TextureFormat.DXT1Crunched ,
TextureFormat.EAC_R ,
TextureFormat.EAC_R_SIGNED ,
TextureFormat.EAC_RG ,
TextureFormat.EAC_RG_SIGNED ,
TextureFormat.ETC2_RGB ,
TextureFormat.ETC_RGB4 ,
TextureFormat.ETC_RGB4_3DS ,
TextureFormat.ETC_RGB4Crunched ,
TextureFormat.PVRTC_RGB2 ,
TextureFormat.PVRTC_RGB4 ,
TextureFormat.R16 ,
TextureFormat.R8 ,
TextureFormat.RFloat ,
TextureFormat.RG16 ,
TextureFormat.RGB24 ,
TextureFormat.RGB565 ,
TextureFormat.RGB9e5Float ,
TextureFormat.RGFloat ,
TextureFormat.RGHalf ,
TextureFormat.RHalf ,
TextureFormat.YUY2
};
Texture tex = srcMaterial.GetTexture(propertyName);
if (tex == null)
return fallback;
else
return tex;
}
public static bool TextureHasAlpha ( Texture2D tex )
{
if (tex == null) return false;
public static TextureFormat[] TextureFormatsWithouthAlpha = new TextureFormat[] {
TextureFormat.ASTC_RGB_10x10 ,
TextureFormat.ASTC_RGB_12x12 ,
TextureFormat.ASTC_RGB_4x4 ,
TextureFormat.ASTC_RGB_5x5 ,
TextureFormat.ASTC_RGB_6x6 ,
TextureFormat.ASTC_RGB_8x8 ,
TextureFormat.BC4 ,
TextureFormat.BC5 ,
TextureFormat.DXT1 ,
TextureFormat.DXT1Crunched ,
TextureFormat.EAC_R ,
TextureFormat.EAC_R_SIGNED ,
TextureFormat.EAC_RG ,
TextureFormat.EAC_RG_SIGNED ,
TextureFormat.ETC2_RGB ,
TextureFormat.ETC_RGB4 ,
TextureFormat.ETC_RGB4_3DS ,
TextureFormat.ETC_RGB4Crunched ,
TextureFormat.PVRTC_RGB2 ,
TextureFormat.PVRTC_RGB4 ,
TextureFormat.R16 ,
TextureFormat.R8 ,
TextureFormat.RFloat ,
TextureFormat.RG16 ,
TextureFormat.RGB24 ,
TextureFormat.RGB565 ,
TextureFormat.RGB9e5Float ,
TextureFormat.RGFloat ,
TextureFormat.RGHalf ,
TextureFormat.RHalf ,
TextureFormat.YUY2
};
bool o = true;
int i=0;
public static bool TextureHasAlpha(Texture2D tex)
{
if (tex == null) return false;
while ( i < TextureFormatsWithouthAlpha.Length && o)
{
o = tex.format != TextureFormatsWithouthAlpha[i];
++i;
}
bool o = true;
int i = 0;
return o;
}
while (i < TextureFormatsWithouthAlpha.Length && o)
{
o = tex.format != TextureFormatsWithouthAlpha[i];
++i;
}
private Texture m_rSource;
private Texture m_gSource;
private Texture m_bSource;
private Texture m_aSource;
return o;
}
// Chanels are : r=0, g=1, b=2, a=3, greyscale from rgb = 4
// If negative, the chanel is inverted
private int m_rChanel;
private int m_gChanel;
private int m_bChanel;
private int m_aChanel;
private Texture m_rSource;
private Texture m_gSource;
private Texture m_bSource;
private Texture m_aSource;
// Chanels remaping
private Vector4[] m_remapings = new Vector4[]{
new Vector4(0f, 1f, 0f, 0f),
new Vector4(0f, 1f, 0f, 0f),
new Vector4(0f, 1f, 0f, 0f),
new Vector4(0f, 1f, 0f, 0f)
};
// Chanels are : r=0, g=1, b=2, a=3, greyscale from rgb = 4
// If negative, the chanel is inverted
private int m_rChanel;
private int m_gChanel;
private int m_bChanel;
private int m_aChanel;
private bool m_bilinearFilter;
// Chanels remaping
private Vector4[] m_remapings = new Vector4[] {
new Vector4(0f, 1f, 0f, 0f),
new Vector4(0f, 1f, 0f, 0f),
new Vector4(0f, 1f, 0f, 0f),
new Vector4(0f, 1f, 0f, 0f)
};
private Dictionary<Texture, Texture> m_RawTextures;
private bool m_bilinearFilter;
public TextureCombiner( Texture rSource, int rChanel, Texture gSource, int gChanel, Texture bSource, int bChanel, Texture aSource, int aChanel, bool bilinearFilter = true )
{
m_rSource = rSource;
m_gSource = gSource;
m_bSource = bSource;
m_aSource = aSource;
m_rChanel = rChanel;
m_gChanel = gChanel;
m_bChanel = bChanel;
m_aChanel = aChanel;
m_bilinearFilter = bilinearFilter;
}
private Dictionary<Texture, Texture> m_RawTextures;
public void SetRemapping( int channel, float min, float max)
{
if (channel > 3 || channel < 0) return;
public TextureCombiner(Texture rSource, int rChanel, Texture gSource, int gChanel, Texture bSource, int bChanel, Texture aSource, int aChanel, bool bilinearFilter = true)
{
m_rSource = rSource;
m_gSource = gSource;
m_bSource = bSource;
m_aSource = aSource;
m_rChanel = rChanel;
m_gChanel = gChanel;
m_bChanel = bChanel;
m_aChanel = aChanel;
m_bilinearFilter = bilinearFilter;
}
public void SetRemapping(int channel, float min, float max)
{
if (channel > 3 || channel < 0) return;
m_remapings[channel].x = min;
m_remapings[channel].y = max;
}
m_remapings[channel].x = min;
m_remapings[channel].y = max;
}
public Texture2D Combine(string savePath)
{
int xMin = int.MaxValue;
int yMin = int.MaxValue;
if (m_rSource.width > 4 && m_rSource.width < xMin) xMin = m_rSource.width;
if (m_gSource.width > 4 && m_gSource.width < xMin) xMin = m_gSource.width;
if (m_bSource.width > 4 && m_bSource.width < xMin) xMin = m_bSource.width;
if (m_aSource.width > 4 && m_aSource.width < xMin) xMin = m_aSource.width;
if (xMin == int.MaxValue) xMin = 4;
public Texture2D Combine( string savePath )
{
int xMin = int.MaxValue;
int yMin = int.MaxValue;
if (m_rSource.height > 4 && m_rSource.height < yMin) yMin = m_rSource.height;
if (m_gSource.height > 4 && m_gSource.height < yMin) yMin = m_gSource.height;
if (m_bSource.height > 4 && m_bSource.height < yMin) yMin = m_bSource.height;
if (m_aSource.height > 4 && m_aSource.height < yMin) yMin = m_aSource.height;
if (yMin == int.MaxValue) yMin = 4;
if (m_rSource.width > 4 && m_rSource.width < xMin) xMin = m_rSource.width;
if (m_gSource.width > 4 && m_gSource.width < xMin) xMin = m_gSource.width;
if (m_bSource.width > 4 && m_bSource.width < xMin) xMin = m_bSource.width;
if (m_aSource.width > 4 && m_aSource.width < xMin) xMin = m_aSource.width;
if (xMin == int.MaxValue) xMin = 4;
if (m_rSource.height > 4 && m_rSource.height < yMin) yMin = m_rSource.height;
if (m_gSource.height > 4 && m_gSource.height < yMin) yMin = m_gSource.height;
if (m_bSource.height > 4 && m_bSource.height < yMin) yMin = m_bSource.height;
if (m_aSource.height > 4 && m_aSource.height < yMin) yMin = m_aSource.height;
if (yMin == int.MaxValue) yMin = 4;
Texture2D combined = new Texture2D(xMin, yMin, TextureFormat.RGBAFloat, true, true);
combined.hideFlags = HideFlags.DontUnloadUnusedAsset;
Texture2D combined = new Texture2D(xMin, yMin, TextureFormat.RGBAFloat, true, true);
combined.hideFlags = HideFlags.DontUnloadUnusedAsset;
Material combinerMaterial = new Material(Shader.Find("Hidden/SRP_Core/TextureCombiner"));
combinerMaterial.hideFlags = HideFlags.DontUnloadUnusedAsset;
Material combinerMaterial = new Material(Shader.Find("Hidden/SRP_Core/TextureCombiner"));
combinerMaterial.hideFlags = HideFlags.DontUnloadUnusedAsset;
combinerMaterial.SetTexture("_RSource", GetRawTexture(m_rSource));
combinerMaterial.SetTexture("_GSource", GetRawTexture(m_gSource));
combinerMaterial.SetTexture("_BSource", GetRawTexture(m_bSource));
combinerMaterial.SetTexture("_ASource", GetRawTexture(m_aSource));
combinerMaterial.SetTexture("_RSource", GetRawTexture(m_rSource));
combinerMaterial.SetTexture("_GSource", GetRawTexture(m_gSource));
combinerMaterial.SetTexture("_BSource", GetRawTexture(m_bSource));
combinerMaterial.SetTexture("_ASource", GetRawTexture(m_aSource));
combinerMaterial.SetFloat("_RChannel", m_rChanel);
combinerMaterial.SetFloat("_GChannel", m_gChanel);
combinerMaterial.SetFloat("_BChannel", m_bChanel);
combinerMaterial.SetFloat("_AChannel", m_aChanel);
combinerMaterial.SetFloat("_RChannel", m_rChanel);
combinerMaterial.SetFloat("_GChannel", m_gChanel);
combinerMaterial.SetFloat("_BChannel", m_bChanel);
combinerMaterial.SetFloat("_AChannel", m_aChanel);
combinerMaterial.SetVector("_RRemap", m_remapings[0]);
combinerMaterial.SetVector("_GRemap", m_remapings[1]);
combinerMaterial.SetVector("_BRemap", m_remapings[2]);
combinerMaterial.SetVector("_ARemap", m_remapings[3]);
combinerMaterial.SetVector("_RRemap", m_remapings[0]);
combinerMaterial.SetVector("_GRemap", m_remapings[1]);
combinerMaterial.SetVector("_BRemap", m_remapings[2]);
combinerMaterial.SetVector("_ARemap", m_remapings[3]);
RenderTexture combinedRT = new RenderTexture(xMin, yMin, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.sRGB);
RenderTexture combinedRT = new RenderTexture(xMin, yMin, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.sRGB);
Graphics.Blit(Texture2D.whiteTexture, combinedRT, combinerMaterial);
Graphics.Blit(Texture2D.whiteTexture, combinedRT, combinerMaterial);
// Readback the render texture
RenderTexture previousActive = RenderTexture.active;
RenderTexture.active = combinedRT;
combined.ReadPixels(new Rect(0, 0, xMin, yMin), 0, 0, false);
combined.Apply();
RenderTexture.active = previousActive;
// Readback the render texture
RenderTexture previousActive = RenderTexture.active;
RenderTexture.active = combinedRT;
combined.ReadPixels(new Rect(0, 0, xMin, yMin), 0, 0, false);
combined.Apply();
RenderTexture.active = previousActive;
byte[] bytes = new byte[0];
byte[] bytes = new byte[0];
if (savePath.EndsWith("png"))
bytes = ImageConversion.EncodeToPNG(combined);
if (savePath.EndsWith("exr"))
bytes = ImageConversion.EncodeToEXR(combined);
if (savePath.EndsWith("jpg"))
bytes = ImageConversion.EncodeToJPG(combined);
if (savePath.EndsWith("png"))
bytes = ImageConversion.EncodeToPNG(combined);
if (savePath.EndsWith("exr"))
bytes = ImageConversion.EncodeToEXR(combined);
if (savePath.EndsWith("jpg"))
bytes = ImageConversion.EncodeToJPG(combined);
string systemPath = Path.Combine(Application.dataPath.Remove(Application.dataPath.Length - 6), savePath);
File.WriteAllBytes(systemPath, bytes);
string systemPath = Path.Combine(Application.dataPath.Remove(Application.dataPath.Length-6), savePath);
File.WriteAllBytes(systemPath, bytes);
Object.DestroyImmediate(combined);
Object.DestroyImmediate(combined);
AssetDatabase.ImportAsset(savePath);
AssetDatabase.ImportAsset(savePath);
TextureImporter combinedImporter = (TextureImporter)AssetImporter.GetAtPath(savePath);
combinedImporter.sRGBTexture = false;
combinedImporter.SaveAndReimport();
TextureImporter combinedImporter = (TextureImporter) AssetImporter.GetAtPath(savePath);
combinedImporter.sRGBTexture = false;
combinedImporter.SaveAndReimport();
if (savePath.EndsWith("exr"))
{
// The options for the platform string are: "Standalone", "iPhone", "Android", "WebGL", "Windows Store Apps", "PSP2", "PS4", "XboxOne", "Nintendo 3DS", "WiiU", "tvOS".
combinedImporter.SetPlatformTextureSettings(new TextureImporterPlatformSettings() {name = "Standalone", format = TextureImporterFormat.DXT5, overridden = true });
}
if (savePath.EndsWith("exr"))
{
// The options for the platform string are: "Standalone", "iPhone", "Android", "WebGL", "Windows Store Apps", "PSP2", "PS4", "XboxOne", "Nintendo 3DS", "WiiU", "tvOS".
combinedImporter.SetPlatformTextureSettings(new TextureImporterPlatformSettings(){name = "Standalone", format = TextureImporterFormat.DXT5, overridden = true });
}
combined = AssetDatabase.LoadAssetAtPath<Texture2D>(savePath);
combined = AssetDatabase.LoadAssetAtPath<Texture2D>(savePath);
//cleanup "raw" textures
foreach (KeyValuePair<Texture, Texture> prop in m_RawTextures)
{
if (AssetDatabase.Contains(prop.Value))
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(prop.Value));
}
Object.DestroyImmediate(combinerMaterial);
//cleanup "raw" textures
foreach( KeyValuePair<Texture, Texture> prop in m_RawTextures )
{
if (AssetDatabase.Contains(prop.Value))
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(prop.Value));
}
Object.DestroyImmediate(combinerMaterial);
m_RawTextures.Clear();
m_RawTextures.Clear();
return combined;
}
return combined;
}
private Texture GetRawTexture(Texture original, bool sRGBFallback = false)
{
if (m_RawTextures == null) m_RawTextures = new Dictionary<Texture, Texture>();
if (!m_RawTextures.ContainsKey(original))
{
if (AssetDatabase.Contains(original))
{
string path = AssetDatabase.GetAssetPath(original);
string rawPath = "Assets/raw_" + Path.GetFileName(path);
private Texture GetRawTexture (Texture original, bool sRGBFallback = false)
{
if (m_RawTextures == null) m_RawTextures = new Dictionary<Texture, Texture>();
if (!m_RawTextures.ContainsKey(original))
{
if ( AssetDatabase.Contains(original))
{
string path = AssetDatabase.GetAssetPath(original);
string rawPath = "Assets/raw_"+Path.GetFileName(path);
AssetDatabase.CopyAsset(path, rawPath);
AssetDatabase.CopyAsset(path, rawPath);
AssetDatabase.ImportAsset(rawPath);
AssetDatabase.ImportAsset(rawPath);
TextureImporter rawImporter = (TextureImporter)AssetImporter.GetAtPath(rawPath);
rawImporter.textureType = TextureImporterType.Default;
rawImporter.mipmapEnabled = false;
rawImporter.isReadable = true;
rawImporter.filterMode = m_bilinearFilter ? FilterMode.Bilinear : FilterMode.Point;
rawImporter.npotScale = TextureImporterNPOTScale.None;
rawImporter.wrapMode = TextureWrapMode.Clamp;
TextureImporter rawImporter = (TextureImporter) AssetImporter.GetAtPath(rawPath);
rawImporter.textureType = TextureImporterType.Default;
rawImporter.mipmapEnabled = false;
rawImporter.isReadable = true;
rawImporter.filterMode = m_bilinearFilter? FilterMode.Bilinear : FilterMode.Point;
rawImporter.npotScale = TextureImporterNPOTScale.None;
rawImporter.wrapMode = TextureWrapMode.Clamp;
Texture2D originalTex2D = original as Texture2D;
rawImporter.sRGBTexture = (originalTex2D == null) ? sRGBFallback : (AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(original)) as TextureImporter).sRGBTexture;
Texture2D originalTex2D = original as Texture2D;
rawImporter.sRGBTexture = (originalTex2D == null)? sRGBFallback : ( AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(original)) as TextureImporter).sRGBTexture;
rawImporter.maxTextureSize = 8192;
rawImporter.maxTextureSize = 8192;
rawImporter.textureCompression = TextureImporterCompression.Uncompressed;
rawImporter.textureCompression = TextureImporterCompression.Uncompressed;
rawImporter.SaveAndReimport();
rawImporter.SaveAndReimport();
m_RawTextures.Add(original, AssetDatabase.LoadAssetAtPath<Texture>(rawPath));
}
else
m_RawTextures.Add(original, original);
}
m_RawTextures.Add(original, AssetDatabase.LoadAssetAtPath<Texture>(rawPath));
}
else
m_RawTextures.Add(original, original);
}
return m_RawTextures[original];
}
return m_RawTextures[original];
}
}

168
com.unity.render-pipelines.core/CoreRP/Editor/TextureCombiner/TextureCombiner.shader


Shader "Hidden/SRP_Core/TextureCombiner"
Shader "Hidden/SRP_Core/TextureCombiner"
Properties
{
// Chanels are : r=0, g=1, b=2, a=3, greyscale from rgb = 4
// If the chanel value is negative, we invert the value
Properties
{
// Chanels are : r=0, g=1, b=2, a=3, greyscale from rgb = 4
// If the chanel value is negative, we invert the value
[Linear][NoScaleOffset] _RSource ("R Source", 2D) = "white" {}
_RChannel ("R Channel", float) = 0
_RRemap ("R Remap", Vector) = (0, 1, 0, 0)
[Linear][NoScaleOffset] _GSource ("G Source", 2D) = "white" {}
_GChannel ("G Channel", float) = 1
_GRemap ("G Remap", Vector) = (0, 1, 0, 0)
[Linear][NoScaleOffset] _BSource ("B Source", 2D) = "white" {}
_BChannel ("B Channel", float) = 2
_BRemap ("B Remap", Vector) = (0, 1, 0, 0)
[Linear][NoScaleOffset] _ASource ("A Source", 2D) = "white" {}
_AChannel ("A Channel", float) = 3
_ARemap ("A Remap", Vector) = (0, 1, 0, 0)
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
[Linear][NoScaleOffset] _RSource ("R Source", 2D) = "white" {}
_RChannel ("R Channel", float) = 0
_RRemap ("R Remap", Vector) = (0, 1, 0, 0)
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
[Linear][NoScaleOffset] _GSource ("G Source", 2D) = "white" {}
_GChannel ("G Channel", float) = 1
_GRemap ("G Remap", Vector) = (0, 1, 0, 0)
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
[Linear][NoScaleOffset] _BSource ("B Source", 2D) = "white" {}
_BChannel ("B Channel", float) = 2
_BRemap ("B Remap", Vector) = (0, 1, 0, 0)
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
[Linear][NoScaleOffset] _ASource ("A Source", 2D) = "white" {}
_AChannel ("A Channel", float) = 3
_ARemap ("A Remap", Vector) = (0, 1, 0, 0)
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
sampler2D _RSource, _GSource, _BSource, _ASource;
float _RChannel, _GChannel, _BChannel, _AChannel;
float4 _RRemap, _GRemap, _BRemap, _ARemap;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
float PlotSourcetoChanel(float4 source, float param, float2 remap)
{
if (param < 0 )
{
param = -param;
source = float4(1,1,1,1) - source;
}
#include "UnityCG.cginc"
float o;
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
if (param >= 4)
o = source.r * 0.3 + source.g * 0.59 + source.b * 0.11; // Photoshop desaturation : G*.59+R*.3+B*.11
else
o = source[param];
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
return o * ( remap.y - remap.x) + remap.x ;
}
sampler2D _RSource, _GSource, _BSource, _ASource;
float _RChannel, _GChannel, _BChannel, _AChannel;
float4 _RRemap, _GRemap, _BRemap, _ARemap;
float PlotSourcetoChanel(float4 source, float param)
{
return PlotSourcetoChanel(source, param, float2(0,1) );
}
float4 frag (v2f i) : SV_Target
{
float4 col = float4(0,0,0,0);
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
col.r = PlotSourcetoChanel( tex2D(_RSource, i.uv), _RChannel, _RRemap );
col.g = PlotSourcetoChanel( tex2D(_GSource, i.uv), _GChannel, _GRemap );
col.b = PlotSourcetoChanel( tex2D(_BSource, i.uv), _BChannel, _BRemap );
col.a = PlotSourcetoChanel( tex2D(_ASource, i.uv), _AChannel, _ARemap );
float PlotSourcetoChanel(float4 source, float param, float2 remap)
{
if (param < 0 )
{
param = -param;
source = float4(1,1,1,1) - source;
}
float o;
if (param >= 4)
o = source.r * 0.3 + source.g * 0.59 + source.b * 0.11; // Photoshop desaturation : G*.59+R*.3+B*.11
else
o = source[param];
return col;
}
ENDCG
}
}
return o * ( remap.y - remap.x) + remap.x ;
}
float PlotSourcetoChanel(float4 source, float param)
{
return PlotSourcetoChanel(source, param, float2(0,1) );
}
float4 frag (v2f i) : SV_Target
{
float4 col = float4(0,0,0,0);
col.r = PlotSourcetoChanel( tex2D(_RSource, i.uv), _RChannel, _RRemap );
col.g = PlotSourcetoChanel( tex2D(_GSource, i.uv), _GChannel, _GRemap );
col.b = PlotSourcetoChanel( tex2D(_BSource, i.uv), _BChannel, _BRemap );
col.a = PlotSourcetoChanel( tex2D(_ASource, i.uv), _AChannel, _ARemap );
return col;
}
ENDCG
}
}
}

2
com.unity.render-pipelines.core/CoreRP/Editor/Volume/Drawers/ColorParameterDrawer.cs


using UnityEngine;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering

2
com.unity.render-pipelines.core/CoreRP/Editor/Volume/Drawers/FloatParameterDrawer.cs


using UnityEngine;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering

2
com.unity.render-pipelines.core/CoreRP/Editor/Volume/Drawers/IntParameterDrawer.cs


using UnityEngine;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering

2
com.unity.render-pipelines.core/CoreRP/Editor/Volume/Drawers/Vector4ParameterDrawer.cs


using UnityEngine;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering

2
com.unity.render-pipelines.core/CoreRP/Editor/Volume/SerializedDataParameter.cs


using System;
using System;
using System.Linq;
using System.Reflection;
using UnityEngine.Assertions;

12
com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeComponentEditor.cs


// Look for all the valid parameter drawers
var types = CoreUtils.GetAllAssemblyTypes()
.Where(
t => t.IsSubclassOf(typeof(VolumeParameterDrawer))
&& t.IsDefined(typeof(VolumeParameterDrawerAttribute), false)
&& !t.IsAbstract
);
.Where(
t => t.IsSubclassOf(typeof(VolumeParameterDrawer))
&& t.IsDefined(typeof(VolumeParameterDrawerAttribute), false)
&& !t.IsAbstract
);
// Store them
foreach (var type in types)

.Where(t =>
(t.IsPublic && t.GetCustomAttributes(typeof(NonSerializedAttribute), false).Length == 0) ||
(t.GetCustomAttributes(typeof(SerializeField), false).Length > 0)
)
)
.Where(t => t.GetCustomAttributes(typeof(HideInInspector), false).Length == 0)
.ToList();

22
com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeComponentListEditor.cs


using System;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

// Gets the list of all available component editors
var editorTypes = CoreUtils.GetAllAssemblyTypes()
.Where(
t => t.IsSubclassOf(typeof(VolumeComponentEditor))
&& t.IsDefined(typeof(VolumeComponentEditorAttribute), false)
&& !t.IsAbstract
);
.Where(
t => t.IsSubclassOf(typeof(VolumeComponentEditor))
&& t.IsDefined(typeof(VolumeComponentEditorAttribute), false)
&& !t.IsAbstract
);
// Map them to their corresponding component type
foreach (var editorType in editorTypes)

CoreEditorUtils.DrawSplitter();
bool displayContent = CoreEditorUtils.DrawHeaderToggle(
title,
editor.baseProperty,
editor.activeProperty,
pos => OnContextClick(pos, editor.target, id)
);
title,
editor.baseProperty,
editor.activeProperty,
pos => OnContextClick(pos, editor.target, id)
);
if (displayContent)
{

2
com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeComponentProvider.cs


using System;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.Rendering;

2
com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeParameterDrawer.cs


using System;
using System;
using UnityEngine;
namespace UnityEditor.Experimental.Rendering

2
com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeProfileEditor.cs


using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Experimental.Rendering
{

4
com.unity.render-pipelines.core/CoreRP/Editor/Volume/VolumeProfileFactory.cs


using UnityEngine;
using UnityEngine;
using UnityEditor.ProjectWindowCallback;
using System.IO;
using UnityEngine.Experimental.Rendering;

"New Volume Profile.asset",
null,
null
);
);
}
public static VolumeProfile CreateVolumeProfileAtPath(string path)

33
com.unity.render-pipelines.core/CoreRP/Inputs/InputRegistering.cs


using System.Collections.Generic;
using System.Collections.Generic;
namespace UnityEngine.Experimental
{

public enum Axis { X, Y, Third, Fourth, Fifth, Sixth, Seventh, Eigth }
public enum Joy { All, First, Second }
public string name = "";
public string desc = "";
public string btnNegative = "";
public string btnPositive = "";
public string altBtnNegative = "";
public string altBtnPositive = "";
public float gravity = 0.0f;
public float deadZone = 0.0f;
public float sensitivity = 0.0f;
public bool snap = false;
public bool invert = false;
public Kind kind = Kind.Axis;
public Axis axis = Axis.X;
public Joy joystick = Joy.All;
public string name = "";
public string desc = "";
public string btnNegative = "";
public string btnPositive = "";
public string altBtnNegative = "";
public string altBtnPositive = "";
public float gravity = 0.0f;
public float deadZone = 0.0f;
public float sensitivity = 0.0f;
public bool snap = false;
public bool invert = false;
public Kind kind = Kind.Axis;
public Axis axis = Axis.X;
public Joy joystick = Joy.All;
static bool InputAlreadyRegistered(string name, InputManagerEntry.Kind kind, SerializedProperty spAxes)
{
for (var i = 0; i < spAxes.arraySize; ++i)

var soInputManager = new SerializedObject(inputManager);
var spAxes = soInputManager.FindProperty("m_Axes");
foreach(InputManagerEntry entry in entries)
foreach (InputManagerEntry entry in entries)
{
WriteEntry(spAxes, entry);
}

2
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/BC6H.hlsl


// Ref: https://github.com/knarkowicz/GPURealTimeBC6H/blob/master/bin/compress.hlsl
// Ref: https://github.com/knarkowicz/GPURealTimeBC6H/blob/master/bin/compress.hlsl
// Doc: https://msdn.microsoft.com/en-us/library/windows/desktop/hh308952(v=vs.85).aspx
// Measure compression error

1001
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl
文件差异内容过多而无法显示
查看文件

2
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/CommonLighting.hlsl


// Return specular occlusion based on ambient occlusion (usually get from SSAO) and view/roughness info
real GetSpecularOcclusionFromAmbientOcclusion(real NdotV, real ambientOcclusion, real roughness)
{
return saturate(PositivePow(NdotV + ambientOcclusion, exp2(-16.0 * roughness - 1.0)) - 1.0 + ambientOcclusion);
return saturate(PositivePow(NdotV + ambientOcclusion, exp2(-16.0 * roughness - 1.0)) - 1.0 + ambientOcclusion);
}
// ref: Practical Realtime Strategies for Accurate Indirect Occlusion

552
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Debug.hlsl


#ifndef UNITY_DEBUG_INCLUDED
#define UNITY_DEBUG_INCLUDED
// Given an enum (represented by an int here), return a color.
// Use for DebugView of enum
real3 GetIndexColor(int index)
{
real3 outColor = real3(1.0, 0.0, 0.0);
if (index == 0)
outColor = real3(1.0, 0.5, 0.5);
else if (index == 1)
outColor = real3(0.5, 1.0, 0.5);
else if (index == 2)
outColor = real3(0.5, 0.5, 1.0);
else if (index == 3)
outColor = real3(1.0, 1.0, 0.5);
else if (index == 4)
outColor = real3(1.0, 0.5, 1.0);
else if (index == 5)
outColor = real3(0.5, 1.0, 1.0);
else if (index == 6)
outColor = real3(0.25, 0.75, 1.0);
else if (index == 7)
outColor = real3(1.0, 0.75, 0.25);
else if (index == 8)
outColor = real3(0.75, 1.0, 0.25);
else if (index == 9)
outColor = real3(0.75, 0.25, 1.0);
else if (index == 10)
outColor = real3(0.25, 1.0, 0.75);
else if (index == 11)
outColor = real3(0.75, 0.75, 0.25);
else if (index == 12)
outColor = real3(0.75, 0.25, 0.75);
else if (index == 13)
outColor = real3(0.25, 0.75, 0.75);
else if (index == 14)
outColor = real3(0.25, 0.25, 0.75);
else if (index == 15)
outColor = real3(0.75, 0.25, 0.25);
return outColor;
}
bool SampleDebugFont(int2 pixCoord, uint digit)
{
if (pixCoord.x < 0 || pixCoord.y < 0 || pixCoord.x >= 5 || pixCoord.y >= 9 || digit > 9)
return false;
#define PACK_BITS25(_x0,_x1,_x2,_x3,_x4,_x5,_x6,_x7,_x8,_x9,_x10,_x11,_x12,_x13,_x14,_x15,_x16,_x17,_x18,_x19,_x20,_x21,_x22,_x23,_x24) (_x0|(_x1<<1)|(_x2<<2)|(_x3<<3)|(_x4<<4)|(_x5<<5)|(_x6<<6)|(_x7<<7)|(_x8<<8)|(_x9<<9)|(_x10<<10)|(_x11<<11)|(_x12<<12)|(_x13<<13)|(_x14<<14)|(_x15<<15)|(_x16<<16)|(_x17<<17)|(_x18<<18)|(_x19<<19)|(_x20<<20)|(_x21<<21)|(_x22<<22)|(_x23<<23)|(_x24<<24))
#define _ 0
#define x 1
uint fontData[9][2] = {
{ PACK_BITS25(_,_,x,_,_, _,_,x,_,_, _,x,x,x,_, x,x,x,x,x, _,_,_,x,_), PACK_BITS25(x,x,x,x,x, _,x,x,x,_, x,x,x,x,x, _,x,x,x,_, _,x,x,x,_) },
{ PACK_BITS25(_,x,_,x,_, _,x,x,_,_, x,_,_,_,x, _,_,_,_,x, _,_,_,x,_), PACK_BITS25(x,_,_,_,_, x,_,_,_,x, _,_,_,_,x, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, x,_,x,_,_, x,_,_,_,x, _,_,_,x,_, _,_,x,x,_), PACK_BITS25(x,_,_,_,_, x,_,_,_,_, _,_,_,x,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,_,_,x, _,_,x,_,_, _,x,_,x,_), PACK_BITS25(x,_,x,x,_, x,_,_,_,_, _,_,_,x,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,_,x,_, _,x,x,x,_, _,x,_,x,_), PACK_BITS25(x,x,_,_,x, x,x,x,x,_, _,_,x,_,_, _,x,x,x,_, _,x,x,x,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,x,_,_, _,_,_,_,x, x,_,_,x,_), PACK_BITS25(_,_,_,_,x, x,_,_,_,x, _,_,x,_,_, x,_,_,_,x, _,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,x,_,_,_, _,_,_,_,x, x,x,x,x,x), PACK_BITS25(_,_,_,_,x, x,_,_,_,x, _,x,_,_,_, x,_,_,_,x, _,_,_,_,x) },
{ PACK_BITS25(_,x,_,x,_, _,_,x,_,_, x,_,_,_,_, x,_,_,_,x, _,_,_,x,_), PACK_BITS25(x,_,_,_,x, x,_,_,_,x, _,x,_,_,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(_,_,x,_,_, x,x,x,x,x, x,x,x,x,x, _,x,x,x,_, _,_,_,x,_), PACK_BITS25(_,x,x,x,_, _,x,x,x,_, _,x,_,_,_, _,x,x,x,_, _,x,x,x,_) }
};
#undef _
#undef x
#undef PACK_BITS25
return (fontData[8 - pixCoord.y][digit >= 5] >> ((digit % 5) * 5 + pixCoord.x)) & 1;
}
bool SampleDebugFontNumber(int2 pixCoord, uint number)
{
pixCoord.y -= 4;
if (number <= 9)
{
return SampleDebugFont(pixCoord - int2(6, 0), number);
}
else
{
return (SampleDebugFont(pixCoord, number / 10) | SampleDebugFont(pixCoord - int2(6, 0), number % 10));
}
}
float4 GetStreamingMipColor(uint mipCount, float4 mipInfo)
{
// alpha is amount to blend with source color (0.0 = use original, 1.0 = use new color)
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
uint originalTextureMipCount = uint(mipInfo.y);
// If material/shader mip info (original mip level) has not been set its not a streamed texture
if (originalTextureMipCount == 0)
return float4(1.0, 1.0, 1.0, 0.0);
uint desiredMipLevel = uint(mipInfo.z);
uint mipCountDesired = uint(originalTextureMipCount)-uint(desiredMipLevel);
if (mipCount == 0)
{
// Magenta if mip count invalid
return float4(1.0, 0.0, 1.0, 1.0);
}
else if (mipCount < mipCountDesired)
{
// red tones when not at the desired mip level (reduction due to budget). Brighter is further from original, alpha 0 when at desired
float ratioToDesired = float(mipCount) / float(mipCountDesired);
return float4(1.0, 0.0, 0.0, 1.0 - ratioToDesired);
}
else if (mipCount >= originalTextureMipCount)
{
// original color when at (or beyond) original mip count
return float4(1.0, 1.0, 1.0, 0.0);
}
else
{
// green tones when not at the original mip level. Brighter is closer to original, alpha 0 when at original
float ratioToOriginal = float(mipCount) / float(originalTextureMipCount);
return float4(0.0, 1.0, 0.0, 1.0 - ratioToOriginal);
}
}
float4 GetSimpleMipCountColor(uint mipCount)
{
// Grey scale for mip counts where mip count of 12 = white
float mipCountColor = float(mipCount) / 12.0;
float4 color = float4(mipCountColor, mipCountColor, mipCountColor, 1.0f);
// alpha is amount to blend with source color (0.0 = use original, 1.0 = use new color)
// Magenta is no valid mip count
// Original colour if greater than 12
return mipCount==0 ? float4(1.0, 0.0, 1.0, 1.0) : (mipCount > 12 ? float4(1.0, 1.0, 1.0, 0.0) : color );
}
float4 GetMipLevelColor(float2 uv, float4 texelSize)
{
// Push down into colors list to "optimal level" in following table.
// .zw is texture width,height so *2 is down one mip, *4 is down two mips
texelSize.zw *= 4.0;
float mipLevel = ComputeTextureLOD(uv, texelSize.wz);
mipLevel = clamp(mipLevel, 0.0, 5.0 - 0.0001);
float4 colors[6] = {
float4(0.0, 0.0, 1.0, 0.8), // 0 BLUE = too little texture detail
float4(0.0, 0.5, 1.0, 0.4), // 1
float4(1.0, 1.0, 1.0, 0.0), // 2 = optimal level
float4(1.0, 0.7, 0.0, 0.2), // 3 (YELLOW tint)
float4(1.0, 0.3, 0.0, 0.6), // 4 (clamped mipLevel 4.9999)
float4(1.0, 0.0, 0.0, 0.8) // 5 RED = too much texture detail (max blended value)
};
int mipLevelInt = floor(mipLevel);
float t = frac(mipLevel);
float4 a = colors[mipLevelInt];
float4 b = colors[mipLevelInt + 1];
float4 color = lerp(a, b, t);
return color;
}
float3 GetDebugMipColor(float3 originalColor, Texture2D tex, float4 texelSize, float2 uv)
{
// https://aras-p.info/blog/2011/05/03/a-way-to-visualize-mip-levels/
float4 mipColor= GetMipLevelColor(uv, texelSize);
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugMipCountColor(float3 originalColor, Texture2D tex)
{
uint mipCount = GetMipCount(tex);
float4 mipColor = GetSimpleMipCountColor(mipCount);
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugStreamingMipColor(Texture2D tex, float4 mipInfo)
{
uint mipCount = GetMipCount(tex);
return GetStreamingMipColor(mipCount, mipInfo).xyz;
}
float3 GetDebugStreamingMipColorBlended(float3 originalColor, Texture2D tex, float4 mipInfo)
{
uint mipCount = GetMipCount(tex);
float4 mipColor = GetStreamingMipColor(mipCount, mipInfo);
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugMipColorIncludingMipReduction(float3 originalColor, Texture2D tex, float4 texelSize, float2 uv, float4 mipInfo)
{
uint originalTextureMipCount = uint(mipInfo.y);
if (originalTextureMipCount != 0)
{
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
// Mip count has been reduced but the texelSize was not updated to take that into account
uint mipCount = GetMipCount(tex);
uint mipReductionLevel = originalTextureMipCount - mipCount;
uint mipReductionFactor = 1 << mipReductionLevel;
if (mipReductionFactor)
{
float oneOverMipReductionFactor = 1.0 / mipReductionFactor;
// texelSize.xy *= mipReductionRatio; // Unused in GetDebugMipColor so lets not re-calculate it
texelSize.zw *= oneOverMipReductionFactor;
}
}
return GetDebugMipColor(originalColor, tex, texelSize, uv);
}
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
float3 GetDebugMipReductionColor(Texture2D tex, float4 mipInfo)
{
float3 outColor = float3(1.0, 0.0, 1.0); // Can't calculate without original mip count - return magenta
uint originalTextureMipCount = uint(mipInfo.y);
if (originalTextureMipCount != 0)
{
// Mip count has been reduced but the texelSize was not updated to take that into account
uint mipCount = GetMipCount(tex);
uint mipReductionLevel = originalTextureMipCount - mipCount;
float mipCol = float(mipReductionLevel) / 12.0;
outColor = float3(0, mipCol, 0);
}
return outColor;
}
// Convert an arbitrary range to color base on threshold provide to the function, threshold must be in growing order
real3 GetColorCodeFunction(real value, real4 threshold)
{
const real3 red = { 1.0, 0.0, 0.0 };
const real3 lightGreen = { 0.5, 1.0, 0.5 };
const real3 darkGreen = { 0.1, 1.0, 0.1 };
const real3 yellow = { 1.0, 1.0, 0.0 };
real3 outColor = red;
if (value < threshold[0])
{
outColor = red;
}
else if (value >= threshold[0] && value < threshold[1])
{
real scale = (value - threshold[0]) / (threshold[1] - threshold[0]);
outColor = lerp(red, darkGreen, scale);
}
else if (value >= threshold[1] && value < threshold[2])
{
real scale = (value - threshold[1]) / (threshold[2] - threshold[1]);
outColor = lerp(darkGreen, lightGreen, scale);
}
else if (value >= threshold[2] && value < threshold[3])
{
real scale = (value - threshold[2]) / (threshold[2] - threshold[2]);
outColor = lerp(lightGreen, yellow, scale);
}
else
{
outColor = yellow;
}
return outColor;
}
#endif // UNITY_DEBUG_INCLUDED
#ifndef UNITY_DEBUG_INCLUDED
#define UNITY_DEBUG_INCLUDED
// Given an enum (represented by an int here), return a color.
// Use for DebugView of enum
real3 GetIndexColor(int index)
{
real3 outColor = real3(1.0, 0.0, 0.0);
if (index == 0)
outColor = real3(1.0, 0.5, 0.5);
else if (index == 1)
outColor = real3(0.5, 1.0, 0.5);
else if (index == 2)
outColor = real3(0.5, 0.5, 1.0);
else if (index == 3)
outColor = real3(1.0, 1.0, 0.5);
else if (index == 4)
outColor = real3(1.0, 0.5, 1.0);
else if (index == 5)
outColor = real3(0.5, 1.0, 1.0);
else if (index == 6)
outColor = real3(0.25, 0.75, 1.0);
else if (index == 7)
outColor = real3(1.0, 0.75, 0.25);
else if (index == 8)
outColor = real3(0.75, 1.0, 0.25);
else if (index == 9)
outColor = real3(0.75, 0.25, 1.0);
else if (index == 10)
outColor = real3(0.25, 1.0, 0.75);
else if (index == 11)
outColor = real3(0.75, 0.75, 0.25);
else if (index == 12)
outColor = real3(0.75, 0.25, 0.75);
else if (index == 13)
outColor = real3(0.25, 0.75, 0.75);
else if (index == 14)
outColor = real3(0.25, 0.25, 0.75);
else if (index == 15)
outColor = real3(0.75, 0.25, 0.25);
return outColor;
}
bool SampleDebugFont(int2 pixCoord, uint digit)
{
if (pixCoord.x < 0 || pixCoord.y < 0 || pixCoord.x >= 5 || pixCoord.y >= 9 || digit > 9)
return false;
#define PACK_BITS25(_x0,_x1,_x2,_x3,_x4,_x5,_x6,_x7,_x8,_x9,_x10,_x11,_x12,_x13,_x14,_x15,_x16,_x17,_x18,_x19,_x20,_x21,_x22,_x23,_x24) (_x0|(_x1<<1)|(_x2<<2)|(_x3<<3)|(_x4<<4)|(_x5<<5)|(_x6<<6)|(_x7<<7)|(_x8<<8)|(_x9<<9)|(_x10<<10)|(_x11<<11)|(_x12<<12)|(_x13<<13)|(_x14<<14)|(_x15<<15)|(_x16<<16)|(_x17<<17)|(_x18<<18)|(_x19<<19)|(_x20<<20)|(_x21<<21)|(_x22<<22)|(_x23<<23)|(_x24<<24))
#define _ 0
#define x 1
uint fontData[9][2] = {
{ PACK_BITS25(_,_,x,_,_, _,_,x,_,_, _,x,x,x,_, x,x,x,x,x, _,_,_,x,_), PACK_BITS25(x,x,x,x,x, _,x,x,x,_, x,x,x,x,x, _,x,x,x,_, _,x,x,x,_) },
{ PACK_BITS25(_,x,_,x,_, _,x,x,_,_, x,_,_,_,x, _,_,_,_,x, _,_,_,x,_), PACK_BITS25(x,_,_,_,_, x,_,_,_,x, _,_,_,_,x, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, x,_,x,_,_, x,_,_,_,x, _,_,_,x,_, _,_,x,x,_), PACK_BITS25(x,_,_,_,_, x,_,_,_,_, _,_,_,x,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,_,_,x, _,_,x,_,_, _,x,_,x,_), PACK_BITS25(x,_,x,x,_, x,_,_,_,_, _,_,_,x,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,_,x,_, _,x,x,x,_, _,x,_,x,_), PACK_BITS25(x,x,_,_,x, x,x,x,x,_, _,_,x,_,_, _,x,x,x,_, _,x,x,x,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,_,x,_,_, _,_,_,_,x, x,_,_,x,_), PACK_BITS25(_,_,_,_,x, x,_,_,_,x, _,_,x,_,_, x,_,_,_,x, _,_,_,_,x) },
{ PACK_BITS25(x,_,_,_,x, _,_,x,_,_, _,x,_,_,_, _,_,_,_,x, x,x,x,x,x), PACK_BITS25(_,_,_,_,x, x,_,_,_,x, _,x,_,_,_, x,_,_,_,x, _,_,_,_,x) },
{ PACK_BITS25(_,x,_,x,_, _,_,x,_,_, x,_,_,_,_, x,_,_,_,x, _,_,_,x,_), PACK_BITS25(x,_,_,_,x, x,_,_,_,x, _,x,_,_,_, x,_,_,_,x, x,_,_,_,x) },
{ PACK_BITS25(_,_,x,_,_, x,x,x,x,x, x,x,x,x,x, _,x,x,x,_, _,_,_,x,_), PACK_BITS25(_,x,x,x,_, _,x,x,x,_, _,x,_,_,_, _,x,x,x,_, _,x,x,x,_) }
};
#undef _
#undef x
#undef PACK_BITS25
return (fontData[8 - pixCoord.y][digit >= 5] >> ((digit % 5) * 5 + pixCoord.x)) & 1;
}
bool SampleDebugFontNumber(int2 pixCoord, uint number)
{
pixCoord.y -= 4;
if (number <= 9)
{
return SampleDebugFont(pixCoord - int2(6, 0), number);
}
else
{
return (SampleDebugFont(pixCoord, number / 10) | SampleDebugFont(pixCoord - int2(6, 0), number % 10));
}
}
float4 GetStreamingMipColor(uint mipCount, float4 mipInfo)
{
// alpha is amount to blend with source color (0.0 = use original, 1.0 = use new color)
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
uint originalTextureMipCount = uint(mipInfo.y);
// If material/shader mip info (original mip level) has not been set its not a streamed texture
if (originalTextureMipCount == 0)
return float4(1.0, 1.0, 1.0, 0.0);
uint desiredMipLevel = uint(mipInfo.z);
uint mipCountDesired = uint(originalTextureMipCount)-uint(desiredMipLevel);
if (mipCount == 0)
{
// Magenta if mip count invalid
return float4(1.0, 0.0, 1.0, 1.0);
}
else if (mipCount < mipCountDesired)
{
// red tones when not at the desired mip level (reduction due to budget). Brighter is further from original, alpha 0 when at desired
float ratioToDesired = float(mipCount) / float(mipCountDesired);
return float4(1.0, 0.0, 0.0, 1.0 - ratioToDesired);
}
else if (mipCount >= originalTextureMipCount)
{
// original color when at (or beyond) original mip count
return float4(1.0, 1.0, 1.0, 0.0);
}
else
{
// green tones when not at the original mip level. Brighter is closer to original, alpha 0 when at original
float ratioToOriginal = float(mipCount) / float(originalTextureMipCount);
return float4(0.0, 1.0, 0.0, 1.0 - ratioToOriginal);
}
}
float4 GetSimpleMipCountColor(uint mipCount)
{
// Grey scale for mip counts where mip count of 12 = white
float mipCountColor = float(mipCount) / 12.0;
float4 color = float4(mipCountColor, mipCountColor, mipCountColor, 1.0f);
// alpha is amount to blend with source color (0.0 = use original, 1.0 = use new color)
// Magenta is no valid mip count
// Original colour if greater than 12
return mipCount==0 ? float4(1.0, 0.0, 1.0, 1.0) : (mipCount > 12 ? float4(1.0, 1.0, 1.0, 0.0) : color );
}
float4 GetMipLevelColor(float2 uv, float4 texelSize)
{
// Push down into colors list to "optimal level" in following table.
// .zw is texture width,height so *2 is down one mip, *4 is down two mips
texelSize.zw *= 4.0;
float mipLevel = ComputeTextureLOD(uv, texelSize.wz);
mipLevel = clamp(mipLevel, 0.0, 5.0 - 0.0001);
float4 colors[6] = {
float4(0.0, 0.0, 1.0, 0.8), // 0 BLUE = too little texture detail
float4(0.0, 0.5, 1.0, 0.4), // 1
float4(1.0, 1.0, 1.0, 0.0), // 2 = optimal level
float4(1.0, 0.7, 0.0, 0.2), // 3 (YELLOW tint)
float4(1.0, 0.3, 0.0, 0.6), // 4 (clamped mipLevel 4.9999)
float4(1.0, 0.0, 0.0, 0.8) // 5 RED = too much texture detail (max blended value)
};
int mipLevelInt = floor(mipLevel);
float t = frac(mipLevel);
float4 a = colors[mipLevelInt];
float4 b = colors[mipLevelInt + 1];
float4 color = lerp(a, b, t);
return color;
}
float3 GetDebugMipColor(float3 originalColor, Texture2D tex, float4 texelSize, float2 uv)
{
// https://aras-p.info/blog/2011/05/03/a-way-to-visualize-mip-levels/
float4 mipColor= GetMipLevelColor(uv, texelSize);
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugMipCountColor(float3 originalColor, Texture2D tex)
{
uint mipCount = GetMipCount(tex);
float4 mipColor = GetSimpleMipCountColor(mipCount);
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugStreamingMipColor(Texture2D tex, float4 mipInfo)
{
uint mipCount = GetMipCount(tex);
return GetStreamingMipColor(mipCount, mipInfo).xyz;
}
float3 GetDebugStreamingMipColorBlended(float3 originalColor, Texture2D tex, float4 mipInfo)
{
uint mipCount = GetMipCount(tex);
float4 mipColor = GetStreamingMipColor(mipCount, mipInfo);
return lerp(originalColor, mipColor.rgb, mipColor.a);
}
float3 GetDebugMipColorIncludingMipReduction(float3 originalColor, Texture2D tex, float4 texelSize, float2 uv, float4 mipInfo)
{
uint originalTextureMipCount = uint(mipInfo.y);
if (originalTextureMipCount != 0)
{
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
// Mip count has been reduced but the texelSize was not updated to take that into account
uint mipCount = GetMipCount(tex);
uint mipReductionLevel = originalTextureMipCount - mipCount;
uint mipReductionFactor = 1 << mipReductionLevel;
if (mipReductionFactor)
{
float oneOverMipReductionFactor = 1.0 / mipReductionFactor;
// texelSize.xy *= mipReductionRatio; // Unused in GetDebugMipColor so lets not re-calculate it
texelSize.zw *= oneOverMipReductionFactor;
}
}
return GetDebugMipColor(originalColor, tex, texelSize, uv);
}
// mipInfo :
// x = quality setings minStreamingMipLevel
// y = original mip count for texture
// z = desired on screen mip level
// w = 0
float3 GetDebugMipReductionColor(Texture2D tex, float4 mipInfo)
{
float3 outColor = float3(1.0, 0.0, 1.0); // Can't calculate without original mip count - return magenta
uint originalTextureMipCount = uint(mipInfo.y);
if (originalTextureMipCount != 0)
{
// Mip count has been reduced but the texelSize was not updated to take that into account
uint mipCount = GetMipCount(tex);
uint mipReductionLevel = originalTextureMipCount - mipCount;
float mipCol = float(mipReductionLevel) / 12.0;
outColor = float3(0, mipCol, 0);
}
return outColor;
}
// Convert an arbitrary range to color base on threshold provide to the function, threshold must be in growing order
real3 GetColorCodeFunction(real value, real4 threshold)
{
const real3 red = { 1.0, 0.0, 0.0 };
const real3 lightGreen = { 0.5, 1.0, 0.5 };
const real3 darkGreen = { 0.1, 1.0, 0.1 };
const real3 yellow = { 1.0, 1.0, 0.0 };
real3 outColor = red;
if (value < threshold[0])
{
outColor = red;
}
else if (value >= threshold[0] && value < threshold[1])
{
real scale = (value - threshold[0]) / (threshold[1] - threshold[0]);
outColor = lerp(red, darkGreen, scale);
}
else if (value >= threshold[1] && value < threshold[2])
{
real scale = (value - threshold[1]) / (threshold[2] - threshold[1]);
outColor = lerp(darkGreen, lightGreen, scale);
}
else if (value >= threshold[2] && value < threshold[3])
{
real scale = (value - threshold[2]) / (threshold[2] - threshold[2]);
outColor = lerp(lightGreen, yellow, scale);
}
else
{
outColor = yellow;
}
return outColor;
}
#endif // UNITY_DEBUG_INCLUDED

4
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Random.hlsl


uint JenkinsHash(uint3 v)
{
return JenkinsHash(v.x ^ JenkinsHash(v.yz));
return JenkinsHash(v.x ^ JenkinsHash(v.yz));
return JenkinsHash(v.x ^ JenkinsHash(v.yzw));
return JenkinsHash(v.x ^ JenkinsHash(v.yzw));
}
// Construct a float with half-open range [0, 1) using low 23 bits.

32
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/Shadow.hlsl


# pragma warning( disable : 3557 ) // loop only executes for 1 iteration(s)
#endif
#include "CoreRP/Shadow/ShadowBase.cs.hlsl" // ShadowData definition, auto generated (don't modify)
#include "ShadowTexFetch.hlsl" // Resource sampling definitions (don't modify)
#include "CoreRP/Shadow/ShadowBase.cs.hlsl" // ShadowData definition, auto generated (don't modify)
#include "ShadowTexFetch.hlsl" // Resource sampling definitions (don't modify)
StructuredBuffer<ShadowData> shadowDatas;
StructuredBuffer<int4> payloads;
SHADOWCONTEXT_DECLARE_TEXTURES( SHADOWCONTEXT_MAX_TEX2DARRAY, SHADOWCONTEXT_MAX_TEXCUBEARRAY, SHADOWCONTEXT_MAX_COMPSAMPLER, SHADOWCONTEXT_MAX_SAMPLER )
StructuredBuffer<ShadowData> shadowDatas;
StructuredBuffer<int4> payloads;
SHADOWCONTEXT_DECLARE_TEXTURES( SHADOWCONTEXT_MAX_TEX2DARRAY, SHADOWCONTEXT_MAX_TEXCUBEARRAY, SHADOWCONTEXT_MAX_COMPSAMPLER, SHADOWCONTEXT_MAX_SAMPLER )
};
SHADOW_DEFINE_SAMPLING_FUNCS( SHADOWCONTEXT_MAX_TEX2DARRAY, SHADOWCONTEXT_MAX_TEXCUBEARRAY, SHADOWCONTEXT_MAX_COMPSAMPLER, SHADOWCONTEXT_MAX_SAMPLER )

{
texIdx = (shadowmapId >> 24) & 0xff;
sampIdx = (shadowmapId >> 16) & 0xff;
texIdx = (shadowmapId >> 24) & 0xff;
sampIdx = (shadowmapId >> 16) & 0xff;
shadowType = packedShadowType >> 10;
shadowAlgorithm = packedShadowType & 0x1ff;
shadowType = packedShadowType >> 10;
shadowAlgorithm = packedShadowType & 0x1ff;
shadowType = packedShadowType >> 10;
shadowType = packedShadowType >> 10;
}
// shadow sampling prototypes

real GetDirectionalShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real3 L );
real GetDirectionalShadowAttenuation( ShadowContext shadowContext, real3 positionWS, real3 normalWS, int shadowDataIndex, real3 L, real2 positionSS );
#include "ShadowSampling.hlsl" // sampling patterns (don't modify)
#include "ShadowAlgorithms.hlsl" // engine default algorithms (don't modify)
#include "ShadowSampling.hlsl" // sampling patterns (don't modify)
#include "ShadowAlgorithms.hlsl" // engine default algorithms (don't modify)
return EvalShadow_PunctualDepth( shadowContext, positionWS, normalWS, shadowDataIndex, L, L_dist );
return EvalShadow_PunctualDepth( shadowContext, positionWS, normalWS, shadowDataIndex, L, L_dist );
return GetPunctualShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, L, L_dist );
return GetPunctualShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, L, L_dist );
}
#endif

return EvalShadow_CascadedDepth_Blend( shadowContext, positionWS, normalWS, shadowDataIndex, L );
return EvalShadow_CascadedDepth_Blend( shadowContext, positionWS, normalWS, shadowDataIndex, L );
return GetDirectionalShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, L );
return GetDirectionalShadowAttenuation( shadowContext, positionWS, normalWS, shadowDataIndex, L );
}
#endif

972
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowAlgorithms.hlsl
文件差异内容过多而无法显示
查看文件

132
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowMoments.hlsl


// for us t is depth, u is E(x) i.d. the blurred depth
float ShadowMoments_ChebyshevsInequality( float2 moments, float depth, float minVariance, float lightLeakBias )
{
// variance sig^2 = E(x^2) - E(x)^2
float variance = max( moments.y - (moments.x * moments.x), minVariance );
// variance sig^2 = E(x^2) - E(x)^2
float variance = max( moments.y - (moments.x * moments.x), minVariance );
// probabilistic upper bound
float mD = depth - moments.x;
float p = variance / (variance + mD * mD);
// probabilistic upper bound
float mD = depth - moments.x;
float p = variance / (variance + mD * mD);
p = saturate( (p - lightLeakBias) / (1.0 - lightLeakBias) );
return max( p, depth <= moments.x );
p = saturate( (p - lightLeakBias) / (1.0 - lightLeakBias) );
return max( p, depth <= moments.x );
// Rescale depth into [-1;1]
depth = 2.0 * depth - 1.0;
float pos = exp( exponents.x * depth );
float neg = -exp(-exponents.y * depth );
return float2( pos, neg );
// Rescale depth into [-1;1]
depth = 2.0 * depth - 1.0;
float pos = exp( exponents.x * depth );
float neg = -exp(-exponents.y * depth );
return float2( pos, neg );
}
// helpers for MSM

{
float dsq = depth * depth;
float4 moments = { depth, dsq, depth * dsq, dsq * dsq };
float4x4 mat = { - 2.07224649 , 13.7948857237, 0.105877704 , 9.7924062118,
32.23703778 , -59.4683975703, -1.9077466311, -33.7652110555,
-68.571074599 , 82.0359750338, 9.3496555107, 47.9456096605,
39.3703274134, -35.364903257 , -6.6543490743, -23.9728048165 };
float dsq = depth * depth;
float4 moments = { depth, dsq, depth * dsq, dsq * dsq };
float4x4 mat = { - 2.07224649 , 13.7948857237, 0.105877704 , 9.7924062118,
32.23703778 , -59.4683975703, -1.9077466311, -33.7652110555,
-68.571074599 , 82.0359750338, 9.3496555107, 47.9456096605,
39.3703274134, -35.364903257 , -6.6543490743, -23.9728048165 };
float4 optimized = mul( moments, mat );
optimized[0] += 0.035955884801;
float4 optimized = mul( moments, mat );
optimized[0] += 0.035955884801;
return optimized;
return optimized;
moments[0] -= 0.035955884801;
float4x4 mat = { 0.2227744146, 0.1549679261, 0.1451988946, 0.163127443,
0.0771972861, 0.1394629426, 0.2120202157, 0.2591432266,
0.7926986636, 0.7963415838, 0.7258694464, 0.6539092497,
0.0319417555, -0.1722823173, -0.2758014811, -0.3376131734 };
return mul( moments, mat );
moments[0] -= 0.035955884801;
float4x4 mat = { 0.2227744146, 0.1549679261, 0.1451988946, 0.163127443,
0.0771972861, 0.1394629426, 0.2120202157, 0.2591432266,
0.7926986636, 0.7963415838, 0.7258694464, 0.6539092497,
0.0319417555, -0.1722823173, -0.2758014811, -0.3376131734 };
return mul( moments, mat );
}
// Note: Don't call this with all moments being equal or 0.0, otherwise this code degenerates into lots of +/-inf calculations

// Bias input data to avoid artifacts
z[0] = depth;
b = lerp( moments, 0.5.xxxx, momentBias );
// Bias input data to avoid artifacts
z[0] = depth;
b = lerp( moments, 0.5.xxxx, momentBias );
// Compute a Cholesky factorization of the Hankel matrix B storing only non-trivial entries or related products
float L32D22 = mad( -b[0], b[1], b[2] );
float D22 = mad( -b[0], b[0], b[1] );
float sqDepthVar = mad( -b[1], b[1], b[3] );
float D33D22 = dot( float2( sqDepthVar, -L32D22 ), float2( D22, L32D22 ) );
float InvD22 = 1.0 / D22;
float L32 = L32D22 * InvD22;
// Obtain a scaled inverse image of bz = ( 1, z[0], z[0]*z[0] )^T
float3 c = float3( 1.0, z[0], z[0] * z[0] );
// Forward substitution to solve L * c1 = bz;
c[1] -= b.x;
c[2] -= b.y + L32 * c[1];
// Scaling to solve D * c2 = c1
c[1] *= InvD22;
c[2] *= D22 / D33D22;
// Backward substitution to solve L^T * c3 = c2
c[1] -= L32 * c[2];
c[0] -= dot( c.yz, b.xy );
// Solve the quadratic equation c[0] + c[1] * z + c[2] * z^2 to obtain solutions z[1] and z[2]
float p = c[1] / c[2];
float q = c[0] / c[2];
float D = ((p*p) * 0.25) - q;
float r = sqrt( D );
z[1] = -(p * 0.5) - r;
z[2] = -(p * 0.5) + r;
// Compute a Cholesky factorization of the Hankel matrix B storing only non-trivial entries or related products
float L32D22 = mad( -b[0], b[1], b[2] );
float D22 = mad( -b[0], b[0], b[1] );
float sqDepthVar = mad( -b[1], b[1], b[3] );
float D33D22 = dot( float2( sqDepthVar, -L32D22 ), float2( D22, L32D22 ) );
float InvD22 = 1.0 / D22;
float L32 = L32D22 * InvD22;
// Obtain a scaled inverse image of bz = ( 1, z[0], z[0]*z[0] )^T
float3 c = float3( 1.0, z[0], z[0] * z[0] );
// Forward substitution to solve L * c1 = bz;
c[1] -= b.x;
c[2] -= b.y + L32 * c[1];
// Scaling to solve D * c2 = c1
c[1] *= InvD22;
c[2] *= D22 / D33D22;
// Backward substitution to solve L^T * c3 = c2
c[1] -= L32 * c[2];
c[0] -= dot( c.yz, b.xy );
// Solve the quadratic equation c[0] + c[1] * z + c[2] * z^2 to obtain solutions z[1] and z[2]
float p = c[1] / c[2];
float q = c[0] / c[2];
float D = ((p*p) * 0.25) - q;
float r = sqrt( D );
z[1] = -(p * 0.5) - r;
z[2] = -(p * 0.5) + r;
// Construct a solution composed of three Dirac-deltas and evaluate its CDF
float4 switchVal = (z[2] < z[0]) ? float4( z[1], z[0], 1.0, 1.0 )
: ((z[1] < z[0]) ? float4( z[0], z[1], 0.0, 1.0 ) : 0.0.xxxx);
// Construct a solution composed of three Dirac-deltas and evaluate its CDF
float4 switchVal = (z[2] < z[0]) ? float4( z[1], z[0], 1.0, 1.0 )
: ((z[1] < z[0]) ? float4( z[0], z[1], 0.0, 1.0 ) : 0.0.xxxx);
float quotient = (switchVal[0] * z[2] - b[0] * (switchVal[0] + z[2]) + b[1]) / ((z[2] - switchVal[1]) * (z[0] - z[1]));
float attenuation = saturate( switchVal[2] + switchVal[3] * quotient );
float quotient = (switchVal[0] * z[2] - b[0] * (switchVal[0] + z[2]) + b[1]) / ((z[2] - switchVal[1]) * (z[0] - z[1]));
float attenuation = saturate( switchVal[2] + switchVal[3] * quotient );
return saturate( ((1.0 - attenuation) - lightLeakBias) / (1.0 - lightLeakBias) );
return saturate( ((1.0 - attenuation) - lightLeakBias) / (1.0 - lightLeakBias) );
// Use a solution made of four deltas
float zFree = ((b[2] - b[1]) * z[0] + b[2] - b[3]) / ((b[1] - b[0]) * z[0] + b[1] - b[2]);
float w1Factor = (z[0] > zFree) ? 1.0 : 0.0;
float attenuation = saturate( (b[1] - b[0] + (b[2] - b[0] - (zFree + 1.0) * (b[1] - b[0])) * (zFree - w1Factor - z[0]) / (z[0] * (z[0] - zFree))) / (zFree - w1Factor) + 1.0 - b[0] );
// Use a solution made of four deltas
float zFree = ((b[2] - b[1]) * z[0] + b[2] - b[3]) / ((b[1] - b[0]) * z[0] + b[1] - b[2]);
float w1Factor = (z[0] > zFree) ? 1.0 : 0.0;
float attenuation = saturate( (b[1] - b[0] + (b[2] - b[0] - (zFree + 1.0) * (b[1] - b[0])) * (zFree - w1Factor - z[0]) / (z[0] * (z[0] - zFree))) / (zFree - w1Factor) + 1.0 - b[0] );
return saturate( ((1.0 - attenuation) - lightLeakBias) / (1.0 - lightLeakBias) );
return saturate( ((1.0 - attenuation) - lightLeakBias) / (1.0 - lightLeakBias) );
}

722
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowSampling.hlsl


// ------------------------------------------------------------------
//
// 1 tap PCF sampling
// 1 tap PCF sampling
real depthBias = asfloat( shadowContext.payloads[payloadOffset].x );
payloadOffset++;
real depthBias = asfloat( shadowContext.payloads[payloadOffset].x );
payloadOffset++;
// add the depth bias
coord.z += depthBias;
// add the depth bias
coord.z += depthBias;
// sample the texture
return SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, coord, slice ).x;
// sample the texture
return SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, coord, slice ).x;
real depthBias = asfloat( shadowContext.payloads[payloadOffset].x );
payloadOffset++;
real depthBias = asfloat( shadowContext.payloads[payloadOffset].x );
payloadOffset++;
// add the depth bias
coord.z += depthBias;
// add the depth bias
coord.z += depthBias;
// sample the texture
return SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, coord, slice );
// sample the texture
return SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, coord, slice );
// 3x3 tent PCF sampling (4 taps)
// 3x3 tent PCF sampling (4 taps)
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
// add the depth bias
coord.z += depthBias;
// add the depth bias
coord.z += depthBias;
real shadow = 0.0;
real fetchesWeights[4];
real2 fetchesUV[4];
real shadow = 0.0;
real fetchesWeights[4];
real2 fetchesUV[4];
SampleShadow_ComputeSamples_Tent_3x3(shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV);
UNITY_LOOP
for( int i = 0; i < 4; i++ )
{
shadow += fetchesWeights[i] * SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
return shadow;
SampleShadow_ComputeSamples_Tent_3x3(shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV);
UNITY_LOOP
for( int i = 0; i < 4; i++ )
{
shadow += fetchesWeights[i] * SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
return shadow;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
// add the depth bias
coord.z += depthBias;
// add the depth bias
coord.z += depthBias;
real shadow = 0.0;
real fetchesWeights[4];
real2 fetchesUV[4];
real shadow = 0.0;
real fetchesWeights[4];
real2 fetchesUV[4];
SampleShadow_ComputeSamples_Tent_3x3(shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV);
for (int i = 0; i < 4; i++)
{
shadow += fetchesWeights[i] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
return shadow;
SampleShadow_ComputeSamples_Tent_3x3(shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV);
for (int i = 0; i < 4; i++)
{
shadow += fetchesWeights[i] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
return shadow;
// 5x5 tent PCF sampling (9 taps)
// 5x5 tent PCF sampling (9 taps)
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
// add the depth bias
coord.z += depthBias;
// add the depth bias
coord.z += depthBias;
real shadow = 0.0;
real fetchesWeights[9];
real2 fetchesUV[9];
real shadow = 0.0;
real fetchesWeights[9];
real2 fetchesUV[9];
SampleShadow_ComputeSamples_Tent_5x5( shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV );
UNITY_LOOP
for( int i = 0; i < 9; i++ )
{
shadow += fetchesWeights[i] * SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
return shadow;
SampleShadow_ComputeSamples_Tent_5x5( shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV );
UNITY_LOOP
for( int i = 0; i < 9; i++ )
{
shadow += fetchesWeights[i] * SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
return shadow;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
// add the depth bias
coord.z += depthBias;
// add the depth bias
coord.z += depthBias;
real shadow = 0.0;
real fetchesWeights[9];
real2 fetchesUV[9];
real shadow = 0.0;
real fetchesWeights[9];
real2 fetchesUV[9];
SampleShadow_ComputeSamples_Tent_5x5( shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV );
SampleShadow_ComputeSamples_Tent_5x5( shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV );
// the loops are only there to prevent the compiler form coalescing all 9 texture fetches which increases register usage
int i;
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[ 0] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 0].xy, coord.z + dot( fetchesUV[ 0].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 1] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 1].xy, coord.z + dot( fetchesUV[ 1].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 2] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 2].xy, coord.z + dot( fetchesUV[ 2].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 3] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 3].xy, coord.z + dot( fetchesUV[ 3].xy - coord.xy, sampleBias ) ), slice ).x;
}
// the loops are only there to prevent the compiler form coalescing all 9 texture fetches which increases register usage
int i;
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[ 0] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 0].xy, coord.z + dot( fetchesUV[ 0].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 1] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 1].xy, coord.z + dot( fetchesUV[ 1].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 2] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 2].xy, coord.z + dot( fetchesUV[ 2].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 3] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 3].xy, coord.z + dot( fetchesUV[ 3].xy - coord.xy, sampleBias ) ), slice ).x;
}
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[ 4] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 4].xy, coord.z + dot( fetchesUV[ 4].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 5] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 5].xy, coord.z + dot( fetchesUV[ 5].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 6] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 6].xy, coord.z + dot( fetchesUV[ 6].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 7] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 7].xy, coord.z + dot( fetchesUV[ 7].xy - coord.xy, sampleBias ) ), slice ).x;
}
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[ 4] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 4].xy, coord.z + dot( fetchesUV[ 4].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 5] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 5].xy, coord.z + dot( fetchesUV[ 5].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 6] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 6].xy, coord.z + dot( fetchesUV[ 6].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 7] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 7].xy, coord.z + dot( fetchesUV[ 7].xy - coord.xy, sampleBias ) ), slice ).x;
}
shadow += fetchesWeights[ 8] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 8].xy, coord.z + dot( fetchesUV[ 8].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 8] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 8].xy, coord.z + dot( fetchesUV[ 8].xy - coord.xy, sampleBias ) ), slice ).x;
for( int i = 0; i < 9; i++ )
{
shadow += fetchesWeights[i] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
for( int i = 0; i < 9; i++ )
{
shadow += fetchesWeights[i] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
return shadow;
return shadow;
// 7x7 tent PCF sampling (16 taps)
// 7x7 tent PCF sampling (16 taps)
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
// add the depth bias
coord.z += depthBias;
// add the depth bias
coord.z += depthBias;
real shadow = 0.0;
real fetchesWeights[16];
real2 fetchesUV[16];
real shadow = 0.0;
real fetchesWeights[16];
real2 fetchesUV[16];
SampleShadow_ComputeSamples_Tent_7x7( shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV );
UNITY_LOOP
for( int i = 0; i < 16; i++ )
{
shadow += fetchesWeights[i] * SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
SampleShadow_ComputeSamples_Tent_7x7( shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV );
UNITY_LOOP
for( int i = 0; i < 16; i++ )
{
shadow += fetchesWeights[i] * SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
return shadow;
return shadow;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
payloadOffset++;
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
real4 shadowMapTexture_TexelSize = real4( texelSizeRcp.xy, textureSize.xy );
// add the depth bias
coord.z += depthBias;
// add the depth bias
coord.z += depthBias;
real shadow = 0.0;
real fetchesWeights[16];
real2 fetchesUV[16];
real shadow = 0.0;
real fetchesWeights[16];
real2 fetchesUV[16];
SampleShadow_ComputeSamples_Tent_7x7( shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV );
SampleShadow_ComputeSamples_Tent_7x7( shadowMapTexture_TexelSize, coord.xy, fetchesWeights, fetchesUV );
// the loops are only there to prevent the compiler form coalescing all 16 texture fetches which increases register usage
int i;
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[ 0] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 0].xy, coord.z + dot( fetchesUV[ 0].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 1] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 1].xy, coord.z + dot( fetchesUV[ 1].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 2] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 2].xy, coord.z + dot( fetchesUV[ 2].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 3] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 3].xy, coord.z + dot( fetchesUV[ 3].xy - coord.xy, sampleBias ) ), slice ).x;
}
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[ 4] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 4].xy, coord.z + dot( fetchesUV[ 4].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 5] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 5].xy, coord.z + dot( fetchesUV[ 5].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 6] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 6].xy, coord.z + dot( fetchesUV[ 6].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 7] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 7].xy, coord.z + dot( fetchesUV[ 7].xy - coord.xy, sampleBias ) ), slice ).x;
}
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[ 8] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 8].xy, coord.z + dot( fetchesUV[ 8].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 9] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 9].xy, coord.z + dot( fetchesUV[ 9].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[10] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[10].xy, coord.z + dot( fetchesUV[10].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[11] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[11].xy, coord.z + dot( fetchesUV[11].xy - coord.xy, sampleBias ) ), slice ).x;
}
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[12] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[12].xy, coord.z + dot( fetchesUV[12].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[13] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[13].xy, coord.z + dot( fetchesUV[13].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[14] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[14].xy, coord.z + dot( fetchesUV[14].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[15] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[15].xy, coord.z + dot( fetchesUV[15].xy - coord.xy, sampleBias ) ), slice ).x;
}
// the loops are only there to prevent the compiler form coalescing all 16 texture fetches which increases register usage
int i;
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[ 0] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 0].xy, coord.z + dot( fetchesUV[ 0].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 1] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 1].xy, coord.z + dot( fetchesUV[ 1].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 2] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 2].xy, coord.z + dot( fetchesUV[ 2].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 3] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 3].xy, coord.z + dot( fetchesUV[ 3].xy - coord.xy, sampleBias ) ), slice ).x;
}
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[ 4] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 4].xy, coord.z + dot( fetchesUV[ 4].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 5] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 5].xy, coord.z + dot( fetchesUV[ 5].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 6] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 6].xy, coord.z + dot( fetchesUV[ 6].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 7] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 7].xy, coord.z + dot( fetchesUV[ 7].xy - coord.xy, sampleBias ) ), slice ).x;
}
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[ 8] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 8].xy, coord.z + dot( fetchesUV[ 8].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[ 9] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[ 9].xy, coord.z + dot( fetchesUV[ 9].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[10] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[10].xy, coord.z + dot( fetchesUV[10].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[11] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[11].xy, coord.z + dot( fetchesUV[11].xy - coord.xy, sampleBias ) ), slice ).x;
}
UNITY_LOOP
for( i = 0; i < 1; i++ )
{
shadow += fetchesWeights[12] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[12].xy, coord.z + dot( fetchesUV[12].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[13] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[13].xy, coord.z + dot( fetchesUV[13].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[14] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[14].xy, coord.z + dot( fetchesUV[14].xy - coord.xy, sampleBias ) ), slice ).x;
shadow += fetchesWeights[15] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[15].xy, coord.z + dot( fetchesUV[15].xy - coord.xy, sampleBias ) ), slice ).x;
}
for( int i = 0; i < 16; i++ )
{
shadow += fetchesWeights[i] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
for( int i = 0; i < 16; i++ )
{
shadow += fetchesWeights[i] * SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( fetchesUV[i].xy, coord.z + dot( fetchesUV[i].xy - coord.xy, sampleBias ) ), slice ).x;
}
return shadow;
return shadow;
// 9 tap adaptive PCF sampling
// 9 tap adaptive PCF sampling
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
real filterSize = params.y;
payloadOffset++;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
real filterSize = params.y;
payloadOffset++;
texelSizeRcp *= filterSize;
texelSizeRcp *= filterSize;
// add the depth bias
tcs.z += depthBias;
// add the depth bias
tcs.z += depthBias;
// Terms0 are weights for the individual samples, the other terms are offsets in texel space
real4 vShadow3x3PCFTerms0 = real4( 20.0 / 267.0, 33.0 / 267.0, 55.0 / 267.0, 0.0 );
real4 vShadow3x3PCFTerms1 = real4( texelSizeRcp.x, texelSizeRcp.y, -texelSizeRcp.x, -texelSizeRcp.y );
real4 vShadow3x3PCFTerms2 = real4( texelSizeRcp.x, texelSizeRcp.y, 0.0, 0.0 );
real4 vShadow3x3PCFTerms3 = real4(-texelSizeRcp.x, -texelSizeRcp.y, 0.0, 0.0 );
// Terms0 are weights for the individual samples, the other terms are offsets in texel space
real4 vShadow3x3PCFTerms0 = real4( 20.0 / 267.0, 33.0 / 267.0, 55.0 / 267.0, 0.0 );
real4 vShadow3x3PCFTerms1 = real4( texelSizeRcp.x, texelSizeRcp.y, -texelSizeRcp.x, -texelSizeRcp.y );
real4 vShadow3x3PCFTerms2 = real4( texelSizeRcp.x, texelSizeRcp.y, 0.0, 0.0 );
real4 vShadow3x3PCFTerms3 = real4(-texelSizeRcp.x, -texelSizeRcp.y, 0.0, 0.0 );
real4 v20Taps;
v20Taps.x = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms1.xy, tcs.z + dot( vShadow3x3PCFTerms1.xy, sampleBias ) ), slice ).x; // 1 1
v20Taps.y = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms1.zy, tcs.z + dot( vShadow3x3PCFTerms1.zy, sampleBias ) ), slice ).x; // -1 1
v20Taps.z = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms1.xw, tcs.z + dot( vShadow3x3PCFTerms1.xw, sampleBias ) ), slice ).x; // 1 -1
v20Taps.w = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms1.zw, tcs.z + dot( vShadow3x3PCFTerms1.zw, sampleBias ) ), slice ).x; // -1 -1
real flSum = dot( v20Taps.xyzw, real4( 0.25, 0.25, 0.25, 0.25 ) );
// fully in light or shadow? -> bail
if( ( flSum == 0.0 ) || ( flSum == 1.0 ) )
return flSum;
real4 v20Taps;
v20Taps.x = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms1.xy, tcs.z + dot( vShadow3x3PCFTerms1.xy, sampleBias ) ), slice ).x; // 1 1
v20Taps.y = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms1.zy, tcs.z + dot( vShadow3x3PCFTerms1.zy, sampleBias ) ), slice ).x; // -1 1
v20Taps.z = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms1.xw, tcs.z + dot( vShadow3x3PCFTerms1.xw, sampleBias ) ), slice ).x; // 1 -1
v20Taps.w = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms1.zw, tcs.z + dot( vShadow3x3PCFTerms1.zw, sampleBias ) ), slice ).x; // -1 -1
real flSum = dot( v20Taps.xyzw, real4( 0.25, 0.25, 0.25, 0.25 ) );
// fully in light or shadow? -> bail
if( ( flSum == 0.0 ) || ( flSum == 1.0 ) )
return flSum;
// we're in a transition area, do 5 more taps
flSum *= vShadow3x3PCFTerms0.x * 4.0;
// we're in a transition area, do 5 more taps
flSum *= vShadow3x3PCFTerms0.x * 4.0;
real4 v33Taps;
v33Taps.x = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms2.xz, tcs.z + dot( vShadow3x3PCFTerms2.xz, sampleBias ) ), slice ).x; // 1 0
v33Taps.y = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms3.xz, tcs.z + dot( vShadow3x3PCFTerms3.xz, sampleBias ) ), slice ).x; // -1 0
v33Taps.z = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms3.zy, tcs.z + dot( vShadow3x3PCFTerms3.zy, sampleBias ) ), slice ).x; // 0 -1
v33Taps.w = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms2.zy, tcs.z + dot( vShadow3x3PCFTerms2.zy, sampleBias ) ), slice ).x; // 0 1
flSum += dot( v33Taps.xyzw, vShadow3x3PCFTerms0.yyyy );
real4 v33Taps;
v33Taps.x = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms2.xz, tcs.z + dot( vShadow3x3PCFTerms2.xz, sampleBias ) ), slice ).x; // 1 0
v33Taps.y = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms3.xz, tcs.z + dot( vShadow3x3PCFTerms3.xz, sampleBias ) ), slice ).x; // -1 0
v33Taps.z = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms3.zy, tcs.z + dot( vShadow3x3PCFTerms3.zy, sampleBias ) ), slice ).x; // 0 -1
v33Taps.w = SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, real3( tcs.xy + vShadow3x3PCFTerms2.zy, tcs.z + dot( vShadow3x3PCFTerms2.zy, sampleBias ) ), slice ).x; // 0 1
flSum += dot( v33Taps.xyzw, vShadow3x3PCFTerms0.yyyy );
flSum += SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, tcs, slice ).x * vShadow3x3PCFTerms0.z;
flSum += SampleCompShadow_T2DA( shadowContext, texIdx, sampIdx, tcs, slice ).x * vShadow3x3PCFTerms0.z;
return flSum;
return flSum;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
real filterSize = params.y;
payloadOffset++;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real depthBias = params.x;
real filterSize = params.y;
payloadOffset++;
texelSizeRcp *= filterSize;
texelSizeRcp *= filterSize;
// add the depth bias
tcs.z += depthBias;
// add the depth bias
tcs.z += depthBias;
// Terms0 are weights for the individual samples, the other terms are offsets in texel space
real4 vShadow3x3PCFTerms0 = real4(20.0 / 267.0, 33.0 / 267.0, 55.0 / 267.0, 0.0);
real4 vShadow3x3PCFTerms1 = real4( texelSizeRcp.x, texelSizeRcp.y, -texelSizeRcp.x, -texelSizeRcp.y);
real4 vShadow3x3PCFTerms2 = real4( texelSizeRcp.x, texelSizeRcp.y, 0.0, 0.0);
real4 vShadow3x3PCFTerms3 = real4(-texelSizeRcp.x, -texelSizeRcp.y, 0.0, 0.0);
// Terms0 are weights for the individual samples, the other terms are offsets in texel space
real4 vShadow3x3PCFTerms0 = real4(20.0 / 267.0, 33.0 / 267.0, 55.0 / 267.0, 0.0);
real4 vShadow3x3PCFTerms1 = real4( texelSizeRcp.x, texelSizeRcp.y, -texelSizeRcp.x, -texelSizeRcp.y);
real4 vShadow3x3PCFTerms2 = real4( texelSizeRcp.x, texelSizeRcp.y, 0.0, 0.0);
real4 vShadow3x3PCFTerms3 = real4(-texelSizeRcp.x, -texelSizeRcp.y, 0.0, 0.0);
real4 v20Taps;
v20Taps.x = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms1.xy, tcs.z + dot( vShadow3x3PCFTerms1.xy, sampleBias ) ), slice ).x; // 1 1
v20Taps.y = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms1.zy, tcs.z + dot( vShadow3x3PCFTerms1.zy, sampleBias ) ), slice ).x; // -1 1
v20Taps.z = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms1.xw, tcs.z + dot( vShadow3x3PCFTerms1.xw, sampleBias ) ), slice ).x; // 1 -1
v20Taps.w = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms1.zw, tcs.z + dot( vShadow3x3PCFTerms1.zw, sampleBias ) ), slice ).x; // -1 -1
real flSum = dot( v20Taps.xyzw, real4( 0.25, 0.25, 0.25, 0.25 ) );
// fully in light or shadow? -> bail
if( ( flSum == 0.0 ) || ( flSum == 1.0 ) )
return flSum;
real4 v20Taps;
v20Taps.x = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms1.xy, tcs.z + dot( vShadow3x3PCFTerms1.xy, sampleBias ) ), slice ).x; // 1 1
v20Taps.y = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms1.zy, tcs.z + dot( vShadow3x3PCFTerms1.zy, sampleBias ) ), slice ).x; // -1 1
v20Taps.z = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms1.xw, tcs.z + dot( vShadow3x3PCFTerms1.xw, sampleBias ) ), slice ).x; // 1 -1
v20Taps.w = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms1.zw, tcs.z + dot( vShadow3x3PCFTerms1.zw, sampleBias ) ), slice ).x; // -1 -1
real flSum = dot( v20Taps.xyzw, real4( 0.25, 0.25, 0.25, 0.25 ) );
// fully in light or shadow? -> bail
if( ( flSum == 0.0 ) || ( flSum == 1.0 ) )
return flSum;
// we're in a transition area, do 5 more taps
flSum *= vShadow3x3PCFTerms0.x * 4.0;
// we're in a transition area, do 5 more taps
flSum *= vShadow3x3PCFTerms0.x * 4.0;
real4 v33Taps;
v33Taps.x = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms2.xz, tcs.z + dot( vShadow3x3PCFTerms2.xz, sampleBias ) ), slice ).x; // 1 0
v33Taps.y = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms3.xz, tcs.z + dot( vShadow3x3PCFTerms3.xz, sampleBias ) ), slice ).x; // -1 0
v33Taps.z = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms3.zy, tcs.z + dot( vShadow3x3PCFTerms3.zy, sampleBias ) ), slice ).x; // 0 -1
v33Taps.w = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms2.zy, tcs.z + dot( vShadow3x3PCFTerms2.zy, sampleBias ) ), slice ).x; // 0 1
flSum += dot( v33Taps.xyzw, vShadow3x3PCFTerms0.yyyy );
real4 v33Taps;
v33Taps.x = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms2.xz, tcs.z + dot( vShadow3x3PCFTerms2.xz, sampleBias ) ), slice ).x; // 1 0
v33Taps.y = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms3.xz, tcs.z + dot( vShadow3x3PCFTerms3.xz, sampleBias ) ), slice ).x; // -1 0
v33Taps.z = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms3.zy, tcs.z + dot( vShadow3x3PCFTerms3.zy, sampleBias ) ), slice ).x; // 0 -1
v33Taps.w = SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, real3( tcs.xy + vShadow3x3PCFTerms2.zy, tcs.z + dot( vShadow3x3PCFTerms2.zy, sampleBias ) ), slice ).x; // 0 1
flSum += dot( v33Taps.xyzw, vShadow3x3PCFTerms0.yyyy );
flSum += SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, tcs, slice ).x * vShadow3x3PCFTerms0.z;
flSum += SAMPLE_TEXTURE2D_ARRAY_SHADOW( tex, compSamp, tcs, slice ).x * vShadow3x3PCFTerms0.z;
return flSum;
return flSum;
// 1 tap VSM sampling
// 1 tap VSM sampling
real depth = 1.0 - tcs.z;
real depth = 1.0 - tcs.z;
real depth = tcs.z;
real depth = tcs.z;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real lightLeakBias = params.x;
real varianceBias = params.y;
payloadOffset++;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real lightLeakBias = params.x;
real varianceBias = params.y;
payloadOffset++;
real2 moments = SampleShadow_T2DA( shadowContext, texIdx, sampIdx, tcs.xy, slice ).xy;
real2 moments = SampleShadow_T2DA( shadowContext, texIdx, sampIdx, tcs.xy, slice ).xy;
return ShadowMoments_ChebyshevsInequality( moments, depth, varianceBias, lightLeakBias );
return ShadowMoments_ChebyshevsInequality( moments, depth, varianceBias, lightLeakBias );
real depth = 1.0 - tcs.z;
real depth = 1.0 - tcs.z;
real depth = tcs.z;
real depth = tcs.z;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real lightLeakBias = params.x;
real varianceBias = params.y;
payloadOffset++;
real2 params = asfloat( shadowContext.payloads[payloadOffset].xy );
real lightLeakBias = params.x;
real varianceBias = params.y;
payloadOffset++;
real2 moments = SAMPLE_TEXTURE2D_ARRAY_LOD( tex, samp, tcs.xy, slice, 0.0 ).xy;
real2 moments = SAMPLE_TEXTURE2D_ARRAY_LOD( tex, samp, tcs.xy, slice, 0.0 ).xy;
return ShadowMoments_ChebyshevsInequality( moments, depth, varianceBias, lightLeakBias );
return ShadowMoments_ChebyshevsInequality( moments, depth, varianceBias, lightLeakBias );
// 1 tap EVSM sampling
// 1 tap EVSM sampling
real depth = 1.0 - tcs.z;
real depth = 1.0 - tcs.z;
real depth = tcs.z;
real depth = tcs.z;
real4 params = asfloat( shadowContext.payloads[payloadOffset] );
real lightLeakBias = params.x;
real varianceBias = params.y;
real2 evsmExponents = params.zw;
payloadOffset++;
real4 params = asfloat( shadowContext.payloads[payloadOffset] );
real lightLeakBias = params.x;
real varianceBias = params.y;
real2 evsmExponents = params.zw;
payloadOffset++;
real2 warpedDepth = ShadowMoments_WarpDepth( depth, evsmExponents );
real2 warpedDepth = ShadowMoments_WarpDepth( depth, evsmExponents );
real4 moments = SampleShadow_T2DA( shadowContext, texIdx, sampIdx, tcs.xy, slice );
real4 moments = SampleShadow_T2DA( shadowContext, texIdx, sampIdx, tcs.xy, slice );
// Derivate of warping at depth
real2 depthScale = evsmExponents * warpedDepth;
real2 minVariance = depthScale * depthScale * varianceBias;
// Derivate of warping at depth
real2 depthScale = evsmExponents * warpedDepth;
real2 minVariance = depthScale * depthScale * varianceBias;
UNITY_BRANCH
if( fourMoments )
{
real posContrib = ShadowMoments_ChebyshevsInequality( moments.xz, warpedDepth.x, minVariance.x, lightLeakBias );
real negContrib = ShadowMoments_ChebyshevsInequality( moments.yw, warpedDepth.y, minVariance.y, lightLeakBias );
return min( posContrib, negContrib );
}
else
{
return ShadowMoments_ChebyshevsInequality( moments.xy, warpedDepth.x, minVariance.x, lightLeakBias );
}
UNITY_BRANCH
if( fourMoments )
{
real posContrib = ShadowMoments_ChebyshevsInequality( moments.xz, warpedDepth.x, minVariance.x, lightLeakBias );
real negContrib = ShadowMoments_ChebyshevsInequality( moments.yw, warpedDepth.y, minVariance.y, lightLeakBias );
return min( posContrib, negContrib );
}
else
{
return ShadowMoments_ChebyshevsInequality( moments.xy, warpedDepth.x, minVariance.x, lightLeakBias );
}
real depth = 1.0 - tcs.z;
real depth = 1.0 - tcs.z;
real depth = tcs.z;
real depth = tcs.z;
real4 params = asfloat( shadowContext.payloads[payloadOffset] );
real lightLeakBias = params.x;
real varianceBias = params.y;
real2 evsmExponents = params.zw;
payloadOffset++;
real4 params = asfloat( shadowContext.payloads[payloadOffset] );
real lightLeakBias = params.x;
real varianceBias = params.y;
real2 evsmExponents = params.zw;
payloadOffset++;
real2 warpedDepth = ShadowMoments_WarpDepth( depth, evsmExponents );
real2 warpedDepth = ShadowMoments_WarpDepth( depth, evsmExponents );
real4 moments = SAMPLE_TEXTURE2D_ARRAY_LOD( tex, samp, tcs.xy, slice, 0.0 );
real4 moments = SAMPLE_TEXTURE2D_ARRAY_LOD( tex, samp, tcs.xy, slice, 0.0 );
// Derivate of warping at depth
real2 depthScale = evsmExponents * warpedDepth;
real2 minVariance = depthScale * depthScale * varianceBias;
// Derivate of warping at depth
real2 depthScale = evsmExponents * warpedDepth;
real2 minVariance = depthScale * depthScale * varianceBias;
UNITY_BRANCH
if( fourMoments )
{
real posContrib = ShadowMoments_ChebyshevsInequality( moments.xz, warpedDepth.x, minVariance.x, lightLeakBias );
real negContrib = ShadowMoments_ChebyshevsInequality( moments.yw, warpedDepth.y, minVariance.y, lightLeakBias );
return min( posContrib, negContrib );
}
else
{
return ShadowMoments_ChebyshevsInequality( moments.xy, warpedDepth.x, minVariance.x, lightLeakBias );
}
UNITY_BRANCH
if( fourMoments )
{
real posContrib = ShadowMoments_ChebyshevsInequality( moments.xz, warpedDepth.x, minVariance.x, lightLeakBias );
real negContrib = ShadowMoments_ChebyshevsInequality( moments.yw, warpedDepth.y, minVariance.y, lightLeakBias );
return min( posContrib, negContrib );
}
else
{
return ShadowMoments_ChebyshevsInequality( moments.xy, warpedDepth.x, minVariance.x, lightLeakBias );
}
// 1 tap MSM sampling
// 1 tap MSM sampling
real4 params = asfloat( shadowContext.payloads[payloadOffset] );
real lightLeakBias = params.x;
real momentBias = params.y;
real depthBias = params.z;
real bpp16 = params.w;
real4 params = asfloat( shadowContext.payloads[payloadOffset] );
real lightLeakBias = params.x;
real momentBias = params.y;
real depthBias = params.z;
real bpp16 = params.w;
real depth = (1.0 - tcs.z) - depthBias;
real depth = (1.0 - tcs.z) - depthBias;
real depth = tcs.z + depthBias;
real depth = tcs.z + depthBias;
payloadOffset++;
payloadOffset++;
real4 moments = SampleShadow_T2DA( shadowContext, texIdx, sampIdx, tcs.xy, slice );
if( bpp16 != 0.0 )
moments = ShadowMoments_Decode16MSM( moments );
real4 moments = SampleShadow_T2DA( shadowContext, texIdx, sampIdx, tcs.xy, slice );
if( bpp16 != 0.0 )
moments = ShadowMoments_Decode16MSM( moments );
real3 z;
real4 b;
ShadowMoments_SolveMSM( moments, depth, momentBias, z, b );
real3 z;
real4 b;
ShadowMoments_SolveMSM( moments, depth, momentBias, z, b );
if( useHamburger )
return ShadowMoments_SolveDelta3MSM( z, b.xy, lightLeakBias );
else
return (z[1] < 0.0 || z[2] > 1.0) ? ShadowMoments_SolveDelta4MSM( z, b, lightLeakBias ) : ShadowMoments_SolveDelta3MSM( z, b.xy, lightLeakBias );
if( useHamburger )
return ShadowMoments_SolveDelta3MSM( z, b.xy, lightLeakBias );
else
return (z[1] < 0.0 || z[2] > 1.0) ? ShadowMoments_SolveDelta4MSM( z, b, lightLeakBias ) : ShadowMoments_SolveDelta3MSM( z, b.xy, lightLeakBias );
real4 params = asfloat( shadowContext.payloads[payloadOffset] );
real lightLeakBias = params.x;
real momentBias = params.y;
real depthBias = params.z;
real bpp16 = params.w;
real4 params = asfloat( shadowContext.payloads[payloadOffset] );
real lightLeakBias = params.x;
real momentBias = params.y;
real depthBias = params.z;
real bpp16 = params.w;
real depth = (1.0 - tcs.z) - depthBias;
real depth = (1.0 - tcs.z) - depthBias;
real depth = tcs.z + depthBias;
real depth = tcs.z + depthBias;
payloadOffset++;
payloadOffset++;
real4 moments = SAMPLE_TEXTURE2D_ARRAY_LOD( tex, samp, tcs.xy, slice, 0.0 );
if( bpp16 != 0.0 )
moments = ShadowMoments_Decode16MSM( moments );
real4 moments = SAMPLE_TEXTURE2D_ARRAY_LOD( tex, samp, tcs.xy, slice, 0.0 );
if( bpp16 != 0.0 )
moments = ShadowMoments_Decode16MSM( moments );
real3 z;
real4 b;
ShadowMoments_SolveMSM( moments, depth, momentBias, z, b );
real3 z;
real4 b;
ShadowMoments_SolveMSM( moments, depth, momentBias, z, b );
if( useHamburger )
return ShadowMoments_SolveDelta3MSM( z, b.xy, lightLeakBias );
else
return (z[1] < 0.0 || z[2] > 1.0) ? ShadowMoments_SolveDelta4MSM( z, b, lightLeakBias ) : ShadowMoments_SolveDelta3MSM( z, b.xy, lightLeakBias );
if( useHamburger )
return ShadowMoments_SolveDelta3MSM( z, b.xy, lightLeakBias );
else
return (z[1] < 0.0 || z[2] > 1.0) ? ShadowMoments_SolveDelta4MSM( z, b, lightLeakBias ) : ShadowMoments_SolveDelta3MSM( z, b.xy, lightLeakBias );
}
//-----------------------------------------------------------------------------------------------------

UNITY_BRANCH
switch( algorithm )
{
case GPUSHADOWALGORITHM_PCF_1TAP : return SampleShadow_PCF_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCF_9TAP : return SampleShadow_PCF_9tap_Adaptive( shadowContext, payloadOffset, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCF_TENT_3X3 : return SampleShadow_PCF_Tent_3x3( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCF_TENT_5X5 : return SampleShadow_PCF_Tent_5x5( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCF_TENT_7X7 : return SampleShadow_PCF_Tent_7x7( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_VSM : return SampleShadow_VSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_EVSM_2 : return SampleShadow_EVSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx, false );
case GPUSHADOWALGORITHM_EVSM_4 : return SampleShadow_EVSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx, true );
case GPUSHADOWALGORITHM_MSM_HAM : return SampleShadow_MSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx, true );
case GPUSHADOWALGORITHM_MSM_HAUS : return SampleShadow_MSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx, false );
default: return 1.0;
}
UNITY_BRANCH
switch( algorithm )
{
case GPUSHADOWALGORITHM_PCF_1TAP : return SampleShadow_PCF_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCF_9TAP : return SampleShadow_PCF_9tap_Adaptive( shadowContext, payloadOffset, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCF_TENT_3X3 : return SampleShadow_PCF_Tent_3x3( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCF_TENT_5X5 : return SampleShadow_PCF_Tent_5x5( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCF_TENT_7X7 : return SampleShadow_PCF_Tent_7x7( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_VSM : return SampleShadow_VSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_EVSM_2 : return SampleShadow_EVSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx, false );
case GPUSHADOWALGORITHM_EVSM_4 : return SampleShadow_EVSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx, true );
case GPUSHADOWALGORITHM_MSM_HAM : return SampleShadow_MSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx, true );
case GPUSHADOWALGORITHM_MSM_HAUS : return SampleShadow_MSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx, false );
default: return 1.0;
}
UNITY_BRANCH
switch( algorithm )
{
case GPUSHADOWALGORITHM_PCF_1TAP : return SampleShadow_PCF_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCF_9TAP : return SampleShadow_PCF_9tap_Adaptive( shadowContext, payloadOffset, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCF_TENT_3X3 : return SampleShadow_PCF_Tent_3x3( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCF_TENT_5X5 : return SampleShadow_PCF_Tent_5x5( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCF_TENT_7X7 : return SampleShadow_PCF_Tent_7x7( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
UNITY_BRANCH
switch( algorithm )
{
case GPUSHADOWALGORITHM_PCF_1TAP : return SampleShadow_PCF_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCF_9TAP : return SampleShadow_PCF_9tap_Adaptive( shadowContext, payloadOffset, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCF_TENT_3X3 : return SampleShadow_PCF_Tent_3x3( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCF_TENT_5X5 : return SampleShadow_PCF_Tent_5x5( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCF_TENT_7X7 : return SampleShadow_PCF_Tent_7x7( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
default: return 1.0;
}
default: return 1.0;
}
UNITY_BRANCH
switch( algorithm )
{
case GPUSHADOWALGORITHM_VSM : return SampleShadow_VSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, samp );
case GPUSHADOWALGORITHM_EVSM_2 : return SampleShadow_EVSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, samp, false );
case GPUSHADOWALGORITHM_EVSM_4 : return SampleShadow_EVSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, samp, true );
case GPUSHADOWALGORITHM_MSM_HAM : return SampleShadow_MSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, samp, true );
case GPUSHADOWALGORITHM_MSM_HAUS : return SampleShadow_MSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, samp, false );
default: return 1.0;
}
UNITY_BRANCH
switch( algorithm )
{
case GPUSHADOWALGORITHM_VSM : return SampleShadow_VSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, samp );
case GPUSHADOWALGORITHM_EVSM_2 : return SampleShadow_EVSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, samp, false );
case GPUSHADOWALGORITHM_EVSM_4 : return SampleShadow_EVSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, samp, true );
case GPUSHADOWALGORITHM_MSM_HAM : return SampleShadow_MSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, samp, true );
case GPUSHADOWALGORITHM_MSM_HAUS : return SampleShadow_MSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, tex, samp, false );
default: return 1.0;
}
}

322
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowSamplingTent.hlsl


// _ _ _ _ <-- texels
real SampleShadow_GetTriangleTexelArea(real triangleHeight)
{
return triangleHeight - 0.5;
return triangleHeight - 0.5;
}
// Assuming a isoceles triangle of 1.5 texels height and 3 texels wide lying on 4 texels.

// X Y Z W <-- result indices (in computedArea.xyzw and computedAreaUncut.xyzw)
void SampleShadow_GetTexelAreas_Tent_3x3(real offset, out real4 computedArea, out real4 computedAreaUncut)
{
// Compute the exterior areas
real offset01SquaredHalved = (offset + 0.5) * (offset + 0.5) * 0.5;
computedAreaUncut.x = computedArea.x = offset01SquaredHalved - offset;
computedAreaUncut.w = computedArea.w = offset01SquaredHalved;
// Compute the exterior areas
real offset01SquaredHalved = (offset + 0.5) * (offset + 0.5) * 0.5;
computedAreaUncut.x = computedArea.x = offset01SquaredHalved - offset;
computedAreaUncut.w = computedArea.w = offset01SquaredHalved;
// Compute the middle areas
// For Y : We find the area in Y of as if the left section of the isoceles triangle would
// intersect the axis between Y and Z (ie where offset = 0).
computedAreaUncut.y = SampleShadow_GetTriangleTexelArea(1.5 - offset);
// This area is superior to the one we are looking for if (offset < 0) thus we need to
// subtract the area of the triangle defined by (0,1.5-offset), (0,1.5+offset), (-offset,1.5).
real clampedOffsetLeft = min(offset,0);
real areaOfSmallLeftTriangle = clampedOffsetLeft * clampedOffsetLeft;
computedArea.y = computedAreaUncut.y - areaOfSmallLeftTriangle;
// Compute the middle areas
// For Y : We find the area in Y of as if the left section of the isoceles triangle would
// intersect the axis between Y and Z (ie where offset = 0).
computedAreaUncut.y = SampleShadow_GetTriangleTexelArea(1.5 - offset);
// This area is superior to the one we are looking for if (offset < 0) thus we need to
// subtract the area of the triangle defined by (0,1.5-offset), (0,1.5+offset), (-offset,1.5).
real clampedOffsetLeft = min(offset,0);
real areaOfSmallLeftTriangle = clampedOffsetLeft * clampedOffsetLeft;
computedArea.y = computedAreaUncut.y - areaOfSmallLeftTriangle;
// We do the same for the Z but with the right part of the isoceles triangle
computedAreaUncut.z = SampleShadow_GetTriangleTexelArea(1.5 + offset);
real clampedOffsetRight = max(offset,0);
real areaOfSmallRightTriangle = clampedOffsetRight * clampedOffsetRight;
computedArea.z = computedAreaUncut.z - areaOfSmallRightTriangle;
// We do the same for the Z but with the right part of the isoceles triangle
computedAreaUncut.z = SampleShadow_GetTriangleTexelArea(1.5 + offset);
real clampedOffsetRight = max(offset,0);
real areaOfSmallRightTriangle = clampedOffsetRight * clampedOffsetRight;
computedArea.z = computedAreaUncut.z - areaOfSmallRightTriangle;
}
// Assuming a isoceles triangle of 1.5 texels height and 3 texels wide lying on 4 texels.

real4 dummy;
SampleShadow_GetTexelAreas_Tent_3x3(offset, computedWeight, dummy);
computedWeight *= 0.44444;//0.44 == 1/(the triangle area)
real4 dummy;
SampleShadow_GetTexelAreas_Tent_3x3(offset, computedWeight, dummy);
computedWeight *= 0.44444;//0.44 == 1/(the triangle area)
}
// Assuming a isoceles triangle of 2.5 texel height and 5 texels wide lying on 6 texels.

// 0 1 2 3 4 5 <-- computed area indices (in texelsWeights[])
void SampleShadow_GetTexelWeights_Tent_5x5(real offset, out real3 texelsWeightsA, out real3 texelsWeightsB)
{
// See _UnityInternalGetAreaPerTexel_3TexelTriangleFilter for details.
real4 computedArea_From3texelTriangle;
real4 computedAreaUncut_From3texelTriangle;
SampleShadow_GetTexelAreas_Tent_3x3(offset, computedArea_From3texelTriangle, computedAreaUncut_From3texelTriangle);
// See _UnityInternalGetAreaPerTexel_3TexelTriangleFilter for details.
real4 computedArea_From3texelTriangle;
real4 computedAreaUncut_From3texelTriangle;
SampleShadow_GetTexelAreas_Tent_3x3(offset, computedArea_From3texelTriangle, computedAreaUncut_From3texelTriangle);
// Triangle slope is 45 degree thus we can almost reuse the result of the 3 texel wide computation.
// the 5 texel wide triangle can be seen as the 3 texel wide one but shifted up by one unit/texel.
// 0.16 is 1/(the triangle area)
texelsWeightsA.x = 0.16 * (computedArea_From3texelTriangle.x);
texelsWeightsA.y = 0.16 * (computedAreaUncut_From3texelTriangle.y);
texelsWeightsA.z = 0.16 * (computedArea_From3texelTriangle.y + 1);
texelsWeightsB.x = 0.16 * (computedArea_From3texelTriangle.z + 1);
texelsWeightsB.y = 0.16 * (computedAreaUncut_From3texelTriangle.z);
texelsWeightsB.z = 0.16 * (computedArea_From3texelTriangle.w);
// Triangle slope is 45 degree thus we can almost reuse the result of the 3 texel wide computation.
// the 5 texel wide triangle can be seen as the 3 texel wide one but shifted up by one unit/texel.
// 0.16 is 1/(the triangle area)
texelsWeightsA.x = 0.16 * (computedArea_From3texelTriangle.x);
texelsWeightsA.y = 0.16 * (computedAreaUncut_From3texelTriangle.y);
texelsWeightsA.z = 0.16 * (computedArea_From3texelTriangle.y + 1);
texelsWeightsB.x = 0.16 * (computedArea_From3texelTriangle.z + 1);
texelsWeightsB.y = 0.16 * (computedAreaUncut_From3texelTriangle.z);
texelsWeightsB.z = 0.16 * (computedArea_From3texelTriangle.w);
}
// Assuming a isoceles triangle of 3.5 texel height and 7 texels wide lying on 8 texels.

// 0 1 2 3 4 5 6 7 <-- computed area indices (in texelsWeights[])
void SampleShadow_GetTexelWeights_Tent_7x7(real offset, out real4 texelsWeightsA, out real4 texelsWeightsB)
{
// See _UnityInternalGetAreaPerTexel_3TexelTriangleFilter for details.
real4 computedArea_From3texelTriangle;
real4 computedAreaUncut_From3texelTriangle;
SampleShadow_GetTexelAreas_Tent_3x3(offset, computedArea_From3texelTriangle, computedAreaUncut_From3texelTriangle);
// See _UnityInternalGetAreaPerTexel_3TexelTriangleFilter for details.
real4 computedArea_From3texelTriangle;
real4 computedAreaUncut_From3texelTriangle;
SampleShadow_GetTexelAreas_Tent_3x3(offset, computedArea_From3texelTriangle, computedAreaUncut_From3texelTriangle);
// Triangle slope is 45 degree thus we can almost reuse the result of the 3 texel wide computation.
// the 7 texel wide triangle can be seen as the 3 texel wide one but shifted up by two unit/texel.
// 0.081632 is 1/(the triangle area)
texelsWeightsA.x = 0.081632 * (computedArea_From3texelTriangle.x);
texelsWeightsA.y = 0.081632 * (computedAreaUncut_From3texelTriangle.y);
texelsWeightsA.z = 0.081632 * (computedAreaUncut_From3texelTriangle.y + 1);
texelsWeightsA.w = 0.081632 * (computedArea_From3texelTriangle.y + 2);
texelsWeightsB.x = 0.081632 * (computedArea_From3texelTriangle.z + 2);
texelsWeightsB.y = 0.081632 * (computedAreaUncut_From3texelTriangle.z + 1);
texelsWeightsB.z = 0.081632 * (computedAreaUncut_From3texelTriangle.z);
texelsWeightsB.w = 0.081632 * (computedArea_From3texelTriangle.w);
// Triangle slope is 45 degree thus we can almost reuse the result of the 3 texel wide computation.
// the 7 texel wide triangle can be seen as the 3 texel wide one but shifted up by two unit/texel.
// 0.081632 is 1/(the triangle area)
texelsWeightsA.x = 0.081632 * (computedArea_From3texelTriangle.x);
texelsWeightsA.y = 0.081632 * (computedAreaUncut_From3texelTriangle.y);
texelsWeightsA.z = 0.081632 * (computedAreaUncut_From3texelTriangle.y + 1);
texelsWeightsA.w = 0.081632 * (computedArea_From3texelTriangle.y + 2);
texelsWeightsB.x = 0.081632 * (computedArea_From3texelTriangle.z + 2);
texelsWeightsB.y = 0.081632 * (computedAreaUncut_From3texelTriangle.z + 1);
texelsWeightsB.z = 0.081632 * (computedAreaUncut_From3texelTriangle.z);
texelsWeightsB.w = 0.081632 * (computedArea_From3texelTriangle.w);
// tent base is 3x3 base thus covering from 9 to 12 texels, thus we need 4 bilinear PCF fetches
real2 tentCenterInTexelSpace = coord.xy * shadowMapTexture_TexelSize.zw;
real2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5);
real2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace;
// tent base is 3x3 base thus covering from 9 to 12 texels, thus we need 4 bilinear PCF fetches
real2 tentCenterInTexelSpace = coord.xy * shadowMapTexture_TexelSize.zw;
real2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5);
real2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace;
// find the weight of each texel based
real4 texelsWeightsU, texelsWeightsV;
SampleShadow_GetTexelWeights_Tent_3x3(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsU);
SampleShadow_GetTexelWeights_Tent_3x3(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsV);
// find the weight of each texel based
real4 texelsWeightsU, texelsWeightsV;
SampleShadow_GetTexelWeights_Tent_3x3(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsU);
SampleShadow_GetTexelWeights_Tent_3x3(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsV);
// each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels
real2 fetchesWeightsU = texelsWeightsU.xz + texelsWeightsU.yw;
real2 fetchesWeightsV = texelsWeightsV.xz + texelsWeightsV.yw;
// each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels
real2 fetchesWeightsU = texelsWeightsU.xz + texelsWeightsU.yw;
real2 fetchesWeightsV = texelsWeightsV.xz + texelsWeightsV.yw;
// move the PCF bilinear fetches to respect texels weights
real2 fetchesOffsetsU = texelsWeightsU.yw / fetchesWeightsU.xy + real2(-1.5,0.5);
real2 fetchesOffsetsV = texelsWeightsV.yw / fetchesWeightsV.xy + real2(-1.5,0.5);
fetchesOffsetsU *= shadowMapTexture_TexelSize.xx;
fetchesOffsetsV *= shadowMapTexture_TexelSize.yy;
// move the PCF bilinear fetches to respect texels weights
real2 fetchesOffsetsU = texelsWeightsU.yw / fetchesWeightsU.xy + real2(-1.5,0.5);
real2 fetchesOffsetsV = texelsWeightsV.yw / fetchesWeightsV.xy + real2(-1.5,0.5);
fetchesOffsetsU *= shadowMapTexture_TexelSize.xx;
fetchesOffsetsV *= shadowMapTexture_TexelSize.yy;
real2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTexture_TexelSize.xy;
fetchesUV[0] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.x);
fetchesUV[1] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.x);
fetchesUV[2] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.y);
fetchesUV[3] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.y);
real2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTexture_TexelSize.xy;
fetchesUV[0] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.x);
fetchesUV[1] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.x);
fetchesUV[2] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.y);
fetchesUV[3] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.y);
fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x;
fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x;
fetchesWeights[2] = fetchesWeightsU.x * fetchesWeightsV.y;
fetchesWeights[3] = fetchesWeightsU.y * fetchesWeightsV.y;
fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x;
fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x;
fetchesWeights[2] = fetchesWeightsU.x * fetchesWeightsV.y;
fetchesWeights[3] = fetchesWeightsU.y * fetchesWeightsV.y;
// tent base is 5x5 base thus covering from 25 to 36 texels, thus we need 9 bilinear PCF fetches
real2 tentCenterInTexelSpace = coord.xy * shadowMapTexture_TexelSize.zw;
real2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5);
real2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace;
// tent base is 5x5 base thus covering from 25 to 36 texels, thus we need 9 bilinear PCF fetches
real2 tentCenterInTexelSpace = coord.xy * shadowMapTexture_TexelSize.zw;
real2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5);
real2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace;
// find the weight of each texel based on the area of a 45 degree slop tent above each of them.
real3 texelsWeightsU_A, texelsWeightsU_B;
real3 texelsWeightsV_A, texelsWeightsV_B;
SampleShadow_GetTexelWeights_Tent_5x5(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsU_A, texelsWeightsU_B);
SampleShadow_GetTexelWeights_Tent_5x5(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsV_A, texelsWeightsV_B);
// find the weight of each texel based on the area of a 45 degree slop tent above each of them.
real3 texelsWeightsU_A, texelsWeightsU_B;
real3 texelsWeightsV_A, texelsWeightsV_B;
SampleShadow_GetTexelWeights_Tent_5x5(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsU_A, texelsWeightsU_B);
SampleShadow_GetTexelWeights_Tent_5x5(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsV_A, texelsWeightsV_B);
// each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels
real3 fetchesWeightsU = real3(texelsWeightsU_A.xz, texelsWeightsU_B.y) + real3(texelsWeightsU_A.y, texelsWeightsU_B.xz);
real3 fetchesWeightsV = real3(texelsWeightsV_A.xz, texelsWeightsV_B.y) + real3(texelsWeightsV_A.y, texelsWeightsV_B.xz);
// each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels
real3 fetchesWeightsU = real3(texelsWeightsU_A.xz, texelsWeightsU_B.y) + real3(texelsWeightsU_A.y, texelsWeightsU_B.xz);
real3 fetchesWeightsV = real3(texelsWeightsV_A.xz, texelsWeightsV_B.y) + real3(texelsWeightsV_A.y, texelsWeightsV_B.xz);
// move the PCF bilinear fetches to respect texels weights
real3 fetchesOffsetsU = real3(texelsWeightsU_A.y, texelsWeightsU_B.xz) / fetchesWeightsU.xyz + real3(-2.5,-0.5,1.5);
real3 fetchesOffsetsV = real3(texelsWeightsV_A.y, texelsWeightsV_B.xz) / fetchesWeightsV.xyz + real3(-2.5,-0.5,1.5);
fetchesOffsetsU *= shadowMapTexture_TexelSize.xxx;
fetchesOffsetsV *= shadowMapTexture_TexelSize.yyy;
// move the PCF bilinear fetches to respect texels weights
real3 fetchesOffsetsU = real3(texelsWeightsU_A.y, texelsWeightsU_B.xz) / fetchesWeightsU.xyz + real3(-2.5,-0.5,1.5);
real3 fetchesOffsetsV = real3(texelsWeightsV_A.y, texelsWeightsV_B.xz) / fetchesWeightsV.xyz + real3(-2.5,-0.5,1.5);
fetchesOffsetsU *= shadowMapTexture_TexelSize.xxx;
fetchesOffsetsV *= shadowMapTexture_TexelSize.yyy;
real2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTexture_TexelSize.xy;
fetchesUV[0] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.x);
fetchesUV[1] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.x);
fetchesUV[2] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.x);
fetchesUV[3] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.y);
fetchesUV[4] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.y);
fetchesUV[5] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.y);
fetchesUV[6] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.z);
fetchesUV[7] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.z);
fetchesUV[8] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.z);
real2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTexture_TexelSize.xy;
fetchesUV[0] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.x);
fetchesUV[1] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.x);
fetchesUV[2] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.x);
fetchesUV[3] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.y);
fetchesUV[4] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.y);
fetchesUV[5] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.y);
fetchesUV[6] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.z);
fetchesUV[7] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.z);
fetchesUV[8] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.z);
fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x;
fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x;
fetchesWeights[2] = fetchesWeightsU.z * fetchesWeightsV.x;
fetchesWeights[3] = fetchesWeightsU.x * fetchesWeightsV.y;
fetchesWeights[4] = fetchesWeightsU.y * fetchesWeightsV.y;
fetchesWeights[5] = fetchesWeightsU.z * fetchesWeightsV.y;
fetchesWeights[6] = fetchesWeightsU.x * fetchesWeightsV.z;
fetchesWeights[7] = fetchesWeightsU.y * fetchesWeightsV.z;
fetchesWeights[8] = fetchesWeightsU.z * fetchesWeightsV.z;
fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x;
fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x;
fetchesWeights[2] = fetchesWeightsU.z * fetchesWeightsV.x;
fetchesWeights[3] = fetchesWeightsU.x * fetchesWeightsV.y;
fetchesWeights[4] = fetchesWeightsU.y * fetchesWeightsV.y;
fetchesWeights[5] = fetchesWeightsU.z * fetchesWeightsV.y;
fetchesWeights[6] = fetchesWeightsU.x * fetchesWeightsV.z;
fetchesWeights[7] = fetchesWeightsU.y * fetchesWeightsV.z;
fetchesWeights[8] = fetchesWeightsU.z * fetchesWeightsV.z;
// tent base is 7x7 base thus covering from 49 to 64 texels, thus we need 16 bilinear PCF fetches
real2 tentCenterInTexelSpace = coord.xy * shadowMapTexture_TexelSize.zw;
real2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5);
real2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace;
// tent base is 7x7 base thus covering from 49 to 64 texels, thus we need 16 bilinear PCF fetches
real2 tentCenterInTexelSpace = coord.xy * shadowMapTexture_TexelSize.zw;
real2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5);
real2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace;
// find the weight of each texel based on the area of a 45 degree slop tent above each of them.
real4 texelsWeightsU_A, texelsWeightsU_B;
real4 texelsWeightsV_A, texelsWeightsV_B;
SampleShadow_GetTexelWeights_Tent_7x7(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsU_A, texelsWeightsU_B);
SampleShadow_GetTexelWeights_Tent_7x7(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsV_A, texelsWeightsV_B);
// find the weight of each texel based on the area of a 45 degree slop tent above each of them.
real4 texelsWeightsU_A, texelsWeightsU_B;
real4 texelsWeightsV_A, texelsWeightsV_B;
SampleShadow_GetTexelWeights_Tent_7x7(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsU_A, texelsWeightsU_B);
SampleShadow_GetTexelWeights_Tent_7x7(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsV_A, texelsWeightsV_B);
// each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels
real4 fetchesWeightsU = real4(texelsWeightsU_A.xz, texelsWeightsU_B.xz) + real4(texelsWeightsU_A.yw, texelsWeightsU_B.yw);
real4 fetchesWeightsV = real4(texelsWeightsV_A.xz, texelsWeightsV_B.xz) + real4(texelsWeightsV_A.yw, texelsWeightsV_B.yw);
// each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels
real4 fetchesWeightsU = real4(texelsWeightsU_A.xz, texelsWeightsU_B.xz) + real4(texelsWeightsU_A.yw, texelsWeightsU_B.yw);
real4 fetchesWeightsV = real4(texelsWeightsV_A.xz, texelsWeightsV_B.xz) + real4(texelsWeightsV_A.yw, texelsWeightsV_B.yw);
// move the PCF bilinear fetches to respect texels weights
real4 fetchesOffsetsU = real4(texelsWeightsU_A.yw, texelsWeightsU_B.yw) / fetchesWeightsU.xyzw + real4(-3.5,-1.5,0.5,2.5);
real4 fetchesOffsetsV = real4(texelsWeightsV_A.yw, texelsWeightsV_B.yw) / fetchesWeightsV.xyzw + real4(-3.5,-1.5,0.5,2.5);
fetchesOffsetsU *= shadowMapTexture_TexelSize.xxxx;
fetchesOffsetsV *= shadowMapTexture_TexelSize.yyyy;
// move the PCF bilinear fetches to respect texels weights
real4 fetchesOffsetsU = real4(texelsWeightsU_A.yw, texelsWeightsU_B.yw) / fetchesWeightsU.xyzw + real4(-3.5,-1.5,0.5,2.5);
real4 fetchesOffsetsV = real4(texelsWeightsV_A.yw, texelsWeightsV_B.yw) / fetchesWeightsV.xyzw + real4(-3.5,-1.5,0.5,2.5);
fetchesOffsetsU *= shadowMapTexture_TexelSize.xxxx;
fetchesOffsetsV *= shadowMapTexture_TexelSize.yyyy;
real2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTexture_TexelSize.xy;
fetchesUV[0] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.x);
fetchesUV[1] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.x);
fetchesUV[2] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.x);
fetchesUV[3] = bilinearFetchOrigin + real2(fetchesOffsetsU.w, fetchesOffsetsV.x);
fetchesUV[4] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.y);
fetchesUV[5] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.y);
fetchesUV[6] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.y);
fetchesUV[7] = bilinearFetchOrigin + real2(fetchesOffsetsU.w, fetchesOffsetsV.y);
fetchesUV[8] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.z);
fetchesUV[9] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.z);
fetchesUV[10] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.z);
fetchesUV[11] = bilinearFetchOrigin + real2(fetchesOffsetsU.w, fetchesOffsetsV.z);
fetchesUV[12] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.w);
fetchesUV[13] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.w);
fetchesUV[14] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.w);
fetchesUV[15] = bilinearFetchOrigin + real2(fetchesOffsetsU.w, fetchesOffsetsV.w);
real2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTexture_TexelSize.xy;
fetchesUV[0] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.x);
fetchesUV[1] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.x);
fetchesUV[2] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.x);
fetchesUV[3] = bilinearFetchOrigin + real2(fetchesOffsetsU.w, fetchesOffsetsV.x);
fetchesUV[4] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.y);
fetchesUV[5] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.y);
fetchesUV[6] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.y);
fetchesUV[7] = bilinearFetchOrigin + real2(fetchesOffsetsU.w, fetchesOffsetsV.y);
fetchesUV[8] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.z);
fetchesUV[9] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.z);
fetchesUV[10] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.z);
fetchesUV[11] = bilinearFetchOrigin + real2(fetchesOffsetsU.w, fetchesOffsetsV.z);
fetchesUV[12] = bilinearFetchOrigin + real2(fetchesOffsetsU.x, fetchesOffsetsV.w);
fetchesUV[13] = bilinearFetchOrigin + real2(fetchesOffsetsU.y, fetchesOffsetsV.w);
fetchesUV[14] = bilinearFetchOrigin + real2(fetchesOffsetsU.z, fetchesOffsetsV.w);
fetchesUV[15] = bilinearFetchOrigin + real2(fetchesOffsetsU.w, fetchesOffsetsV.w);
fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x;
fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x;
fetchesWeights[2] = fetchesWeightsU.z * fetchesWeightsV.x;
fetchesWeights[3] = fetchesWeightsU.w * fetchesWeightsV.x;
fetchesWeights[4] = fetchesWeightsU.x * fetchesWeightsV.y;
fetchesWeights[5] = fetchesWeightsU.y * fetchesWeightsV.y;
fetchesWeights[6] = fetchesWeightsU.z * fetchesWeightsV.y;
fetchesWeights[7] = fetchesWeightsU.w * fetchesWeightsV.y;
fetchesWeights[8] = fetchesWeightsU.x * fetchesWeightsV.z;
fetchesWeights[9] = fetchesWeightsU.y * fetchesWeightsV.z;
fetchesWeights[10] = fetchesWeightsU.z * fetchesWeightsV.z;
fetchesWeights[11] = fetchesWeightsU.w * fetchesWeightsV.z;
fetchesWeights[12] = fetchesWeightsU.x * fetchesWeightsV.w;
fetchesWeights[13] = fetchesWeightsU.y * fetchesWeightsV.w;
fetchesWeights[14] = fetchesWeightsU.z * fetchesWeightsV.w;
fetchesWeights[15] = fetchesWeightsU.w * fetchesWeightsV.w;
fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x;
fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x;
fetchesWeights[2] = fetchesWeightsU.z * fetchesWeightsV.x;
fetchesWeights[3] = fetchesWeightsU.w * fetchesWeightsV.x;
fetchesWeights[4] = fetchesWeightsU.x * fetchesWeightsV.y;
fetchesWeights[5] = fetchesWeightsU.y * fetchesWeightsV.y;
fetchesWeights[6] = fetchesWeightsU.z * fetchesWeightsV.y;
fetchesWeights[7] = fetchesWeightsU.w * fetchesWeightsV.y;
fetchesWeights[8] = fetchesWeightsU.x * fetchesWeightsV.z;
fetchesWeights[9] = fetchesWeightsU.y * fetchesWeightsV.z;
fetchesWeights[10] = fetchesWeightsU.z * fetchesWeightsV.z;
fetchesWeights[11] = fetchesWeightsU.w * fetchesWeightsV.z;
fetchesWeights[12] = fetchesWeightsU.x * fetchesWeightsV.w;
fetchesWeights[13] = fetchesWeightsU.y * fetchesWeightsV.w;
fetchesWeights[14] = fetchesWeightsU.z * fetchesWeightsV.w;
fetchesWeights[15] = fetchesWeightsU.w * fetchesWeightsV.w;
}

208
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowTexFetch.hlsl


#if SHADOW_SUPPORTS_DYNAMIC_INDEXING != 0
// Shader model >= 5.1
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_COMP( _Tex2DArraySlots , _SamplerCompSlots ) real4 SampleCompShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real slice ) { return SAMPLE_TEXTURE2D_ARRAY_SHADOW( ctxt.tex2DArray[texIdx], ctxt.compSamplers[sampIdx], tcs, slice ); }
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_SAMP( _Tex2DArraySlots , _SamplerSlots ) real4 SampleShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real2 tcs, real slice, real lod = 0.0 ) { return SAMPLE_TEXTURE2D_ARRAY_LOD( ctxt.tex2DArray[texIdx], ctxt.samplers[sampIdx], tcs, slice, lod ); }
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_LOAD( _Tex2DArraySlots ) real4 LoadShadow_T2DA( ShadowContext ctxt, uint texIdx, uint2 tcs, uint slice, uint lod = 0 ) { return LOAD_TEXTURE2D_ARRAY_LOD( ctxt.tex2DArray[texIdx], tcs, slice, lod ).x; }
# define SHADOW_DEFINE_SAMPLING_FUNC_TCA_COMP( _TexCubeArraySlots, _SamplerCompSlots ) real4 SampleCompShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real4 tcs, real cubeIdx ) { return SAMPLE_TEXTURECUBE_ARRAY_SHADOW( ctxt.texCubeArray[texIdx], ctxt.compSamplers[sampIdx], tcs, cubeIdx );}
# define SHADOW_DEFINE_SAMPLING_FUNC_TCA_SAMP( _TexCubeArraySlots, _SamplerSlots ) real4 SampleShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real cubeIdx, real lod = 0.0 ) { return SAMPLE_TEXTURECUBE_ARRAY_LOD( ctxt.texCubeArray[texIdx], ctxt.samplers[sampIdx], tcs, cubeIdx, lod ); }
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_COMP( _Tex2DArraySlots , _SamplerCompSlots ) real4 SampleCompShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real slice ) { return SAMPLE_TEXTURE2D_ARRAY_SHADOW( ctxt.tex2DArray[texIdx], ctxt.compSamplers[sampIdx], tcs, slice ); }
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_SAMP( _Tex2DArraySlots , _SamplerSlots ) real4 SampleShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real2 tcs, real slice, real lod = 0.0 ) { return SAMPLE_TEXTURE2D_ARRAY_LOD( ctxt.tex2DArray[texIdx], ctxt.samplers[sampIdx], tcs, slice, lod ); }
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_LOAD( _Tex2DArraySlots ) real4 LoadShadow_T2DA( ShadowContext ctxt, uint texIdx, uint2 tcs, uint slice, uint lod = 0 ) { return LOAD_TEXTURE2D_ARRAY_LOD( ctxt.tex2DArray[texIdx], tcs, slice, lod ).x; }
# define SHADOW_DEFINE_SAMPLING_FUNC_TCA_COMP( _TexCubeArraySlots, _SamplerCompSlots ) real4 SampleCompShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real4 tcs, real cubeIdx ) { return SAMPLE_TEXTURECUBE_ARRAY_SHADOW( ctxt.texCubeArray[texIdx], ctxt.compSamplers[sampIdx], tcs, cubeIdx );}
# define SHADOW_DEFINE_SAMPLING_FUNC_TCA_SAMP( _TexCubeArraySlots, _SamplerSlots ) real4 SampleShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real cubeIdx, real lod = 0.0 ) { return SAMPLE_TEXTURECUBE_ARRAY_LOD( ctxt.texCubeArray[texIdx], ctxt.samplers[sampIdx], tcs, cubeIdx, lod ); }
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_COMP( _Tex2DArraySlots, _SamplerCompSlots ) \
real4 SampleCompShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real slice ) \
{ \
real4 res = 1.0.xxxx; \
UNITY_UNROLL for( uint i = 0; i < _Tex2DArraySlots; i++ ) \
{ \
UNITY_UNROLL for( uint j = 0; j < _SamplerCompSlots; j++ ) \
{ \
UNITY_BRANCH if( i == texIdx && j == sampIdx ) \
{ \
res = SAMPLE_TEXTURE2D_ARRAY_SHADOW( ctxt.tex2DArray[i], ctxt.compSamplers[j], tcs, slice ); \
break; \
} \
} \
} \
return res; \
}
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_COMP( _Tex2DArraySlots, _SamplerCompSlots ) \
real4 SampleCompShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real slice ) \
{ \
real4 res = 1.0.xxxx; \
UNITY_UNROLL for( uint i = 0; i < _Tex2DArraySlots; i++ ) \
{ \
UNITY_UNROLL for( uint j = 0; j < _SamplerCompSlots; j++ ) \
{ \
UNITY_BRANCH if( i == texIdx && j == sampIdx ) \
{ \
res = SAMPLE_TEXTURE2D_ARRAY_SHADOW( ctxt.tex2DArray[i], ctxt.compSamplers[j], tcs, slice ); \
break; \
} \
} \
} \
return res; \
}
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_SAMP( _Tex2DArraySlots, _SamplerSlots ) \
real4 SampleShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real2 tcs, real slice, real lod = 0.0 ) \
{ \
real4 res = 1.0.xxxx; \
UNITY_UNROLL for( uint i = 0; i < _Tex2DArraySlots; i++ ) \
{ \
UNITY_UNROLL for( uint j = 0; j < _SamplerSlots; j++ ) \
{ \
UNITY_BRANCH if( i == texIdx && j == sampIdx ) \
{ \
res = SAMPLE_TEXTURE2D_ARRAY_LOD( ctxt.tex2DArray[i], ctxt.samplers[j], tcs, slice, lod ); \
break; \
} \
} \
} \
return res; \
}
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_SAMP( _Tex2DArraySlots, _SamplerSlots ) \
real4 SampleShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real2 tcs, real slice, real lod = 0.0 ) \
{ \
real4 res = 1.0.xxxx; \
UNITY_UNROLL for( uint i = 0; i < _Tex2DArraySlots; i++ ) \
{ \
UNITY_UNROLL for( uint j = 0; j < _SamplerSlots; j++ ) \
{ \
UNITY_BRANCH if( i == texIdx && j == sampIdx ) \
{ \
res = SAMPLE_TEXTURE2D_ARRAY_LOD( ctxt.tex2DArray[i], ctxt.samplers[j], tcs, slice, lod ); \
break; \
} \
} \
} \
return res; \
}
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_LOAD( _Tex2DArraySlots ) \
real LoadShadow_T2DA( ShadowContext ctxt, uint texIdx, uint2 tcs, uint slice, uint lod = 0 ) \
{ \
real res = 1.0; \
UNITY_UNROLL for( uint i = 0; i < _Tex2DArraySlots; i++ ) \
{ \
UNITY_BRANCH if( i == texIdx ) \
{ \
res = LOAD_TEXTURE2D_ARRAY_LOD( ctxt.tex2DArray[i], tcs, slice, lod ).x; \
break; \
} \
} \
return res; \
}
# define SHADOW_DEFINE_SAMPLING_FUNC_T2DA_LOAD( _Tex2DArraySlots ) \
real LoadShadow_T2DA( ShadowContext ctxt, uint texIdx, uint2 tcs, uint slice, uint lod = 0 ) \
{ \
real res = 1.0; \
UNITY_UNROLL for( uint i = 0; i < _Tex2DArraySlots; i++ ) \
{ \
UNITY_BRANCH if( i == texIdx ) \
{ \
res = LOAD_TEXTURE2D_ARRAY_LOD( ctxt.tex2DArray[i], tcs, slice, lod ).x; \
break; \
} \
} \
return res; \
}
# define SHADOW_DEFINE_SAMPLING_FUNC_TCA_COMP( _TexCubeArraySlots, _SamplerCompSlots ) \
real4 SampleCompShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real4 tcs, real cubeIdx ) \
{ \
real4 res = 1.0.xxxx; \
UNITY_UNROLL for( uint i = 0; i < _TexCubeArraySlots; i++ ) \
{ \
UNITY_UNROLL for( uint j = 0; j < _SamplerCompSlots; j++ ) \
{ \
UNITY_BRANCH if( i == texIdx && j == sampIdx ) \
{ \
res = SAMPLE_TEXTURECUBE_ARRAY_SHADOW( ctxt.texCubeArray[i], ctxt.compSamplers[j], tcs, cubeIdx ); \
break; \
} \
} \
} \
return res; \
}
# define SHADOW_DEFINE_SAMPLING_FUNC_TCA_COMP( _TexCubeArraySlots, _SamplerCompSlots ) \
real4 SampleCompShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real4 tcs, real cubeIdx ) \
{ \
real4 res = 1.0.xxxx; \
UNITY_UNROLL for( uint i = 0; i < _TexCubeArraySlots; i++ ) \
{ \
UNITY_UNROLL for( uint j = 0; j < _SamplerCompSlots; j++ ) \
{ \
UNITY_BRANCH if( i == texIdx && j == sampIdx ) \
{ \
res = SAMPLE_TEXTURECUBE_ARRAY_SHADOW( ctxt.texCubeArray[i], ctxt.compSamplers[j], tcs, cubeIdx ); \
break; \
} \
} \
} \
return res; \
}
# define SHADOW_DEFINE_SAMPLING_FUNC_TCA_SAMP( _TexCubeArraySlots, _SamplerSlots ) \
real4 SampleShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real cubeIdx, real lod = 0.0 ) \
{ \
real4 res = 1.0.xxxx; \
UNITY_UNROLL for( uint i = 0; i < _TexCubeArraySlots; i++ ) \
{ \
UNITY_UNROLL for( uint j = 0; j < _SamplerSlots; j++ ) \
{ \
UNITY_BRANCH if( i == texIdx && j == sampIdx ) \
{ \
res = SAMPLE_TEXTURECUBE_ARRAY_LOD( ctxt.texCubeArray[i], ctxt.samplers[j], tcs, cubeIdx, lod ); \
break; \
} \
} \
} \
return res; \
}
# define SHADOW_DEFINE_SAMPLING_FUNC_TCA_SAMP( _TexCubeArraySlots, _SamplerSlots ) \
real4 SampleShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real cubeIdx, real lod = 0.0 ) \
{ \
real4 res = 1.0.xxxx; \
UNITY_UNROLL for( uint i = 0; i < _TexCubeArraySlots; i++ ) \
{ \
UNITY_UNROLL for( uint j = 0; j < _SamplerSlots; j++ ) \
{ \
UNITY_BRANCH if( i == texIdx && j == sampIdx ) \
{ \
res = SAMPLE_TEXTURECUBE_ARRAY_LOD( ctxt.texCubeArray[i], ctxt.samplers[j], tcs, cubeIdx, lod ); \
break; \
} \
} \
} \
return res; \
}
#define SHADOW_DECLARE_SAMPLING_FUNC_T2DA_COMP( _Tex2DArraySlots , _SamplerCompSlots ) real4 SampleCompShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real slice );
#define SHADOW_DECLARE_SAMPLING_FUNC_T2DA_SAMP( _Tex2DArraySlots , _SamplerSlots ) real4 SampleShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real2 tcs, real slice, real lod = 0.0 );
#define SHADOW_DECLARE_SAMPLING_FUNC_T2DA_LOAD( _Tex2DArraySlots ) real4 LoadShadow_T2DA( ShadowContext ctxt, uint texIdx, uint2 tcs, uint slice, uint lod = 0 );
#define SHADOW_DECLARE_SAMPLING_FUNC_TCA_COMP( _TexCubeArraySlots, _SamplerCompSlots ) real4 SampleCompShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real4 tcs, real cubeIdx );
#define SHADOW_DECLARE_SAMPLING_FUNC_TCA_SAMP( _TexCubeArraySlots, _SamplerSlots ) real4 SampleShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real cubeIdx, real lod = 0.0 );
#define SHADOW_DECLARE_SAMPLING_FUNC_T2DA_COMP( _Tex2DArraySlots , _SamplerCompSlots ) real4 SampleCompShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real slice );
#define SHADOW_DECLARE_SAMPLING_FUNC_T2DA_SAMP( _Tex2DArraySlots , _SamplerSlots ) real4 SampleShadow_T2DA( ShadowContext ctxt, uint texIdx, uint sampIdx, real2 tcs, real slice, real lod = 0.0 );
#define SHADOW_DECLARE_SAMPLING_FUNC_T2DA_LOAD( _Tex2DArraySlots ) real4 LoadShadow_T2DA( ShadowContext ctxt, uint texIdx, uint2 tcs, uint slice, uint lod = 0 );
#define SHADOW_DECLARE_SAMPLING_FUNC_TCA_COMP( _TexCubeArraySlots, _SamplerCompSlots ) real4 SampleCompShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real4 tcs, real cubeIdx );
#define SHADOW_DECLARE_SAMPLING_FUNC_TCA_SAMP( _TexCubeArraySlots, _SamplerSlots ) real4 SampleShadow_TCA( ShadowContext ctxt, uint texIdx, uint sampIdx, real3 tcs, real cubeIdx, real lod = 0.0 );
#define SHADOW_CHECK_0( _macro )
#define SHADOW_CHECK_0( _macro )
#define SHADOW_CHECK_1( _macro ) _macro
#define SHADOW_CHECK_2( _macro ) _macro
#define SHADOW_CHECK_3( _macro ) _macro

#define SHADOW_CHECK_ALT( _cnt, _macro, _alt ) SHADOW_CAT( SHADOW_CHECK_ALT_ , _cnt ) ( _macro, _alt )
// helper macro to declare texture members for the shadow context.
#define SHADOWCONTEXT_DECLARE_TEXTURES( _Tex2DArraySlots, _TexCubeArraySlots, _SamplerCompSlots, _SamplerSlots ) \
SHADOW_CHECK( _Tex2DArraySlots , Texture2DArray tex2DArray[_Tex2DArraySlots]; ) \
SHADOW_CHECK( _TexCubeArraySlots, TextureCubeArray texCubeArray[_TexCubeArraySlots]; ) \
SHADOW_CHECK( _SamplerCompSlots , SamplerComparisonState compSamplers[_Tex2DArraySlots]; ) \
SHADOW_CHECK( _SamplerSlots , SamplerState samplers[_Tex2DArraySlots]; )
#define SHADOWCONTEXT_DECLARE_TEXTURES( _Tex2DArraySlots, _TexCubeArraySlots, _SamplerCompSlots, _SamplerSlots ) \
SHADOW_CHECK( _Tex2DArraySlots , Texture2DArray tex2DArray[_Tex2DArraySlots]; ) \
SHADOW_CHECK( _TexCubeArraySlots, TextureCubeArray texCubeArray[_TexCubeArraySlots]; ) \
SHADOW_CHECK( _SamplerCompSlots , SamplerComparisonState compSamplers[_Tex2DArraySlots]; ) \
SHADOW_CHECK( _SamplerSlots , SamplerState samplers[_Tex2DArraySlots]; )
#define SHADOW_DEFINE_SAMPLING_FUNCS( _Tex2DArraySlots, _TexCubeArraySlots, _SamplerCompSlots, _SamplerSlots ) \
SHADOW_CHECK( _Tex2DArraySlots , SHADOW_CHECK_ALT( _SamplerCompSlots, SHADOW_DEFINE_SAMPLING_FUNC_T2DA_COMP( _Tex2DArraySlots, _SamplerCompSlots ), SHADOW_DECLARE_SAMPLING_FUNC_T2DA_COMP( _Tex2DArraySlots, _SamplerCompSlots ) ) ) \
SHADOW_CHECK( _Tex2DArraySlots , SHADOW_CHECK_ALT( _SamplerSlots , SHADOW_DEFINE_SAMPLING_FUNC_T2DA_SAMP( _Tex2DArraySlots, _SamplerSlots ), SHADOW_DECLARE_SAMPLING_FUNC_T2DA_SAMP( _Tex2DArraySlots, _SamplerSlots ) ) ) \
SHADOW_CHECK_ALT( _Tex2DArraySlots , SHADOW_DEFINE_SAMPLING_FUNC_T2DA_LOAD( _Tex2DArraySlots ), SHADOW_DECLARE_SAMPLING_FUNC_T2DA_LOAD( _Tex2DArraySlots ) ) \
SHADOW_CHECK( _TexCubeArraySlots, SHADOW_CHECK_ALT( _SamplerCompSlots, SHADOW_DEFINE_SAMPLING_FUNC_TCA_COMP(_TexCubeArraySlots, _SamplerCompSlots ), SHADOW_DECLARE_SAMPLING_FUNC_TCA_COMP(_TexCubeArraySlots, _SamplerCompSlots ) ) ) \
SHADOW_CHECK( _TexCubeArraySlots, SHADOW_CHECK_ALT( _SamplerSlots , SHADOW_DEFINE_SAMPLING_FUNC_TCA_SAMP(_TexCubeArraySlots, _SamplerSlots ), SHADOW_DECLARE_SAMPLING_FUNC_TCA_SAMP(_TexCubeArraySlots, _SamplerSlots ) ) )
#define SHADOW_DEFINE_SAMPLING_FUNCS( _Tex2DArraySlots, _TexCubeArraySlots, _SamplerCompSlots, _SamplerSlots ) \
SHADOW_CHECK( _Tex2DArraySlots , SHADOW_CHECK_ALT( _SamplerCompSlots, SHADOW_DEFINE_SAMPLING_FUNC_T2DA_COMP( _Tex2DArraySlots, _SamplerCompSlots ), SHADOW_DECLARE_SAMPLING_FUNC_T2DA_COMP( _Tex2DArraySlots, _SamplerCompSlots ) ) ) \
SHADOW_CHECK( _Tex2DArraySlots , SHADOW_CHECK_ALT( _SamplerSlots , SHADOW_DEFINE_SAMPLING_FUNC_T2DA_SAMP( _Tex2DArraySlots, _SamplerSlots ), SHADOW_DECLARE_SAMPLING_FUNC_T2DA_SAMP( _Tex2DArraySlots, _SamplerSlots ) ) ) \
SHADOW_CHECK_ALT( _Tex2DArraySlots , SHADOW_DEFINE_SAMPLING_FUNC_T2DA_LOAD( _Tex2DArraySlots ), SHADOW_DECLARE_SAMPLING_FUNC_T2DA_LOAD( _Tex2DArraySlots ) ) \
SHADOW_CHECK( _TexCubeArraySlots, SHADOW_CHECK_ALT( _SamplerCompSlots, SHADOW_DEFINE_SAMPLING_FUNC_TCA_COMP(_TexCubeArraySlots, _SamplerCompSlots ), SHADOW_DECLARE_SAMPLING_FUNC_TCA_COMP(_TexCubeArraySlots, _SamplerCompSlots ) ) ) \
SHADOW_CHECK( _TexCubeArraySlots, SHADOW_CHECK_ALT( _SamplerSlots , SHADOW_DEFINE_SAMPLING_FUNC_TCA_SAMP(_TexCubeArraySlots, _SamplerSlots ), SHADOW_DECLARE_SAMPLING_FUNC_TCA_SAMP(_TexCubeArraySlots, _SamplerSlots ) ) )

2
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Wind.hlsl


}
}

49
com.unity.render-pipelines.core/CoreRP/Shadow/AdditionalShadowData.cs


shadowDatas[idx].format = format;
shadowDatas[idx].data = data != null ? data : new int[0];
}
// Load a specific shadow data. Returns null if requested data is not present.
public int[] GetShadowData(int shadowDataFormat)
{

int idx = FindShadowData(shadowDataFormat);
return idx >= 0 ? shadowDatas[idx].data : null;
}
// Returns the currently set shadow data and format. Can return null.
public int[] GetShadowData(out int shadowDataFormat)
{

#if UNITY_EDITOR
public void CompactShadowData()
{

#endif
private int FindShadowData(int shadowDataFormat)
{

UnityEditor.SerializedProperty m_ShadowCascadeRatios;
UnityEditor.SerializedProperty m_ShadowCascadeBorders;
public static void SetRegistry( ShadowRegistry registry ) { m_ShadowRegistry = registry; }
public static void SetRegistry(ShadowRegistry registry) { m_ShadowRegistry = registry; }
m_ShadowAlgorithm = serializedObject.FindProperty( "shadowAlgorithm" );
m_ShadowVariant = serializedObject.FindProperty( "shadowVariant" );
m_ShadowData = serializedObject.FindProperty( "shadowData" );
m_ShadowDatas = serializedObject.FindProperty( "shadowDatas" );
m_ShadowCascadeCount = serializedObject.FindProperty( "shadowCascadeCount" );
m_ShadowCascadeRatios = serializedObject.FindProperty( "shadowCascadeRatios" );
m_ShadowCascadeBorders = serializedObject.FindProperty( "shadowCascadeBorders" );
m_ShadowAlgorithm = serializedObject.FindProperty("shadowAlgorithm");
m_ShadowVariant = serializedObject.FindProperty("shadowVariant");
m_ShadowData = serializedObject.FindProperty("shadowData");
m_ShadowDatas = serializedObject.FindProperty("shadowDatas");
m_ShadowCascadeCount = serializedObject.FindProperty("shadowCascadeCount");
m_ShadowCascadeRatios = serializedObject.FindProperty("shadowCascadeRatios");
m_ShadowCascadeBorders = serializedObject.FindProperty("shadowCascadeBorders");
if( m_ShadowRegistry == null )
if (m_ShadowRegistry == null)
AdditionalShadowData asd = (AdditionalShadowData) target;
if( asd == null )
AdditionalShadowData asd = (AdditionalShadowData)target;
if (asd == null)
m_ShadowRegistry.Draw( asd.gameObject.GetComponent<Light>() );
m_ShadowRegistry.Draw(asd.gameObject.GetComponent<Light>());
if( asd.gameObject.GetComponent<Light>().type == LightType.Directional )
if (asd.gameObject.GetComponent<Light>().type == LightType.Directional)
UnityEditor.EditorGUILayout.PropertyField( m_ShadowCascadeCount );
if( UnityEditor.EditorGUI.EndChangeCheck() )
UnityEditor.EditorGUILayout.PropertyField(m_ShadowCascadeCount);
if (UnityEditor.EditorGUI.EndChangeCheck())
const int kMaxCascades = (int) ShadowAtlas.k_MaxCascadesInShader; // depending on where you look this is either 32 or 4, so we're limiting it to 4 for now
const int kMaxCascades = (int)ShadowAtlas.k_MaxCascadesInShader; // depending on where you look this is either 32 or 4, so we're limiting it to 4 for now
m_ShadowCascadeRatios.arraySize = newcnt-1;
m_ShadowCascadeRatios.arraySize = newcnt - 1;
for( int i = 0; i < m_ShadowCascadeRatios.arraySize; i++ )
for (int i = 0; i < m_ShadowCascadeRatios.arraySize; i++)
UnityEditor.EditorGUILayout.Slider( m_ShadowCascadeRatios.GetArrayElementAtIndex( i ), 0.0f, 1.0f, new GUIContent( "Cascade " + i ) );
UnityEditor.EditorGUILayout.Slider(m_ShadowCascadeRatios.GetArrayElementAtIndex(i), 0.0f, 1.0f, new GUIContent("Cascade " + i));
UnityEditor.EditorGUILayout.Slider( m_ShadowCascadeBorders.GetArrayElementAtIndex( i ), 0.0f, 1.0f, new GUIContent( "Transition " + i ) );
UnityEditor.EditorGUILayout.Slider(m_ShadowCascadeBorders.GetArrayElementAtIndex(i), 0.0f, 1.0f, new GUIContent("Transition " + i));
if( UnityEditor.EditorGUI.EndChangeCheck() )
if (UnityEditor.EditorGUI.EndChangeCheck())
UnityEditor.EditorUtility.SetDirty( asd );
UnityEditor.EditorUtility.SetDirty(asd);
UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty();
UnityEditor.SceneView.RepaintAll();
}

797
com.unity.render-pipelines.core/CoreRP/Shadow/Shadow.cs
文件差异内容过多而无法显示
查看文件

340
com.unity.render-pipelines.core/CoreRP/Shadow/ShadowBase.cs


using UnityEngine.Rendering;
using UnityEngine.Rendering;
using System;
using System.Collections.Generic;

public struct Masks
{
public const int k_ShadowAlgorithm = (1 << Bits.k_ShadowAlgorithm ) - 1;
public const int k_ShadowVariant = (1 << Bits.k_ShadowVariant ) - 1;
public const int k_ShadowPrecision = (1 << Bits.k_ShadowPrecision ) - 1;
public const int k_GPUShadowAlgorithm = (1 << Bits.k_GPUShadowAlgorithm ) - 1;
public const int k_GPUShadowType = (1 << Bits.k_GPUShadowType ) - 1;
public const int k_ShadowAlgorithm = (1 << Bits.k_ShadowAlgorithm) - 1;
public const int k_ShadowVariant = (1 << Bits.k_ShadowVariant) - 1;
public const int k_ShadowPrecision = (1 << Bits.k_ShadowPrecision) - 1;
public const int k_GPUShadowAlgorithm = (1 << Bits.k_GPUShadowAlgorithm) - 1;
public const int k_GPUShadowType = (1 << Bits.k_GPUShadowType) - 1;
}
}

public delegate void VariantDelegate( Light l, ShadowAlgorithm dataAlgorithm, ShadowVariant dataVariant, ShadowPrecision dataPrecision, ref int[] dataContainer );
public delegate void VariantDelegate(Light l, ShadowAlgorithm dataAlgorithm, ShadowVariant dataVariant, ShadowPrecision dataPrecision, ref int[] dataContainer);
public delegate GPUShadowType ShadowLightTypeDelegate(Light l);

case LightType.Point:
shadowType = GPUShadowType.Point;
break;
// area lights by themselves can't be mapped to any GPU type
// area lights by themselves can't be mapped to any GPU type
}
return shadowType;

ShadowLightTypeDelegate m_shadowLightType;
Dictionary<ShadowAlgorithm, Entry>[] m_Entries = new Dictionary<ShadowAlgorithm, Entry>[ShadowConstants.Counts.k_GPUShadowType]
{ new Dictionary<ShadowAlgorithm, Entry>(),
new Dictionary<ShadowAlgorithm, Entry>(),
new Dictionary<ShadowAlgorithm, Entry>() };
{
new Dictionary<ShadowAlgorithm, Entry>(),
new Dictionary<ShadowAlgorithm, Entry>(),
new Dictionary<ShadowAlgorithm, Entry>()
};
// Init default delegate
public ShadowRegistry() { m_shadowLightType = ShadowLightType; }

foreach( var d in m_Entries )
foreach (var d in m_Entries)
d.Clear();
}

m_shadowLightType = del;
}
public void Register( GPUShadowType type, ShadowPrecision precision, ShadowAlgorithm algorithm, string algorithmDescriptor, ShadowVariant[] variants, string[] variantDescriptors, VariantDelegate[] variantDelegates )
public void Register(GPUShadowType type, ShadowPrecision precision, ShadowAlgorithm algorithm, string algorithmDescriptor, ShadowVariant[] variants, string[] variantDescriptors, VariantDelegate[] variantDelegates)
if( Validate( algorithmDescriptor, variants, variantDescriptors, variantDelegates ) )
Register( m_Entries[(int)type], precision, algorithm, algorithmDescriptor, variants, variantDescriptors, variantDelegates );
if (Validate(algorithmDescriptor, variants, variantDescriptors, variantDelegates))
Register(m_Entries[(int)type], precision, algorithm, algorithmDescriptor, variants, variantDescriptors, variantDelegates);
private bool Validate( string algorithmDescriptor, ShadowVariant[] variants, string[] variantDescriptors, VariantDelegate[] variantDelegates )
private bool Validate(string algorithmDescriptor, ShadowVariant[] variants, string[] variantDescriptors, VariantDelegate[] variantDelegates)
if( string.IsNullOrEmpty( algorithmDescriptor ) )
if (string.IsNullOrEmpty(algorithmDescriptor))
Debug.LogError( "Tried to register a shadow algorithm but the algorithm descriptor is empty." );
Debug.LogError("Tried to register a shadow algorithm but the algorithm descriptor is empty.");
if( variantDescriptors == null || variantDescriptors.Length == 0 )
if (variantDescriptors == null || variantDescriptors.Length == 0)
Debug.LogError( "Tried to register a shadow algorithm (" + algorithmDescriptor + ") but the variant descriptors are empty. At least one variant descriptor is required for registration." );
Debug.LogError("Tried to register a shadow algorithm (" + algorithmDescriptor + ") but the variant descriptors are empty. At least one variant descriptor is required for registration.");
if( variantDescriptors.Length > ShadowConstants.Counts.k_ShadowVariant )
if (variantDescriptors.Length > ShadowConstants.Counts.k_ShadowVariant)
Debug.LogError( "Tried to register a shadow algorithm (" + algorithmDescriptor + ") with more than the valid amount of variants. Variant count: " + variantDescriptors.Length + ", valid count: " + ShadowConstants.Counts.k_ShadowVariant + "." );
Debug.LogError("Tried to register a shadow algorithm (" + algorithmDescriptor + ") with more than the valid amount of variants. Variant count: " + variantDescriptors.Length + ", valid count: " + ShadowConstants.Counts.k_ShadowVariant + ".");
if( variantDescriptors.Length != variants.Length )
if (variantDescriptors.Length != variants.Length)
Debug.LogError( "Tried to register a shadow algorithm (" + algorithmDescriptor + ") but the length of variant descriptors (" + variantDescriptors.Length + ") does not match the length of variants (" + variants.Length + ")." );
Debug.LogError("Tried to register a shadow algorithm (" + algorithmDescriptor + ") but the length of variant descriptors (" + variantDescriptors.Length + ") does not match the length of variants (" + variants.Length + ").");
if( variantDelegates.Length != variants.Length )
if (variantDelegates.Length != variants.Length)
Debug.LogError( "Tried to register a shadow algorithm (" + algorithmDescriptor + ") but the length of variant delegates (" + variantDelegates.Length + ") does not match the length of variants (" + variants.Length + ")." );
Debug.LogError("Tried to register a shadow algorithm (" + algorithmDescriptor + ") but the length of variant delegates (" + variantDelegates.Length + ") does not match the length of variants (" + variants.Length + ").");
private void Register( Dictionary<ShadowAlgorithm, Entry> dict, ShadowPrecision precision, ShadowAlgorithm algorithm, string algorithmDescriptor, ShadowVariant[] variants, string[] variantDescriptors, VariantDelegate[] variantDelegates )
private void Register(Dictionary<ShadowAlgorithm, Entry> dict, ShadowPrecision precision, ShadowAlgorithm algorithm, string algorithmDescriptor, ShadowVariant[] variants, string[] variantDescriptors, VariantDelegate[] variantDelegates)
if( !dict.ContainsKey( algorithm ) )
if (!dict.ContainsKey(algorithm))
{
Entry e;
e.algorithmDesc = algorithmDescriptor;

for( uint i = 0, cnt = (uint) variants.Length; i < cnt; ++i )
for (uint i = 0, cnt = (uint)variants.Length; i < cnt; ++i)
e.variantDescs[(uint) variants[i]] = variantDescriptors[i];
if( precision == ShadowPrecision.Low )
e.variantDels[(uint) variants[i]].low = variantDelegates[i];
e.variantDescs[(uint)variants[i]] = variantDescriptors[i];
if (precision == ShadowPrecision.Low)
e.variantDels[(uint)variants[i]].low = variantDelegates[i];
e.variantDels[(uint) variants[i]].high = variantDelegates[i];
e.variantDels[(uint)variants[i]].high = variantDelegates[i];
dict.Add( algorithm, e );
dict.Add(algorithm, e);
for( uint i = 0, cnt = (uint) variants.Length; i < cnt; ++i )
for (uint i = 0, cnt = (uint)variants.Length; i < cnt; ++i)
if( string.IsNullOrEmpty( entry.variantDescs[(uint) variants[i]] ) )
if (string.IsNullOrEmpty(entry.variantDescs[(uint)variants[i]]))
entry.variantDescs[(uint) variants[i]] = variantDescriptors[i];
entry.variantDels[(uint) variants[i]].low = precision == ShadowPrecision.Low ? variantDelegates[i] : null;
entry.variantDels[(uint) variants[i]].high = precision == ShadowPrecision.High ? variantDelegates[i] : null;
entry.variantDescs[(uint)variants[i]] = variantDescriptors[i];
entry.variantDels[(uint)variants[i]].low = precision == ShadowPrecision.Low ? variantDelegates[i] : null;
entry.variantDels[(uint)variants[i]].high = precision == ShadowPrecision.High ? variantDelegates[i] : null;
else if( precision == ShadowPrecision.Low && entry.variantDels[(uint)variants[i]].low == null )
else if (precision == ShadowPrecision.Low && entry.variantDels[(uint)variants[i]].low == null)
else if( precision == ShadowPrecision.High && entry.variantDels[(uint)variants[i]].high == null )
else if (precision == ShadowPrecision.High && entry.variantDels[(uint)variants[i]].high == null)
Debug.Log( "Tried to register variant " + variants[i] + " for algorithm " + algorithm + " with precision " + precision + ", but this variant is already registered. Skipping registration." );
Debug.Log("Tried to register variant " + variants[i] + " for algorithm " + algorithm + " with precision " + precision + ", but this variant is already registered. Skipping registration.");
public void Draw( Light l )
public void Draw(Light l)
{
AdditionalShadowData asd = l.GetComponent<AdditionalShadowData>();
Debug.Assert(asd != null, "Light has no valid AdditionalShadowData component attached.");

// check if this has supported shadows
if( (int) shadowType >= ShadowConstants.Counts.k_GPUShadowType )
if ((int)shadowType >= ShadowConstants.Counts.k_GPUShadowType)
return;
int shadowAlgorithm;

if( globalOverride )
if (globalOverride)
shadowAlgorithm = (int) m_GlobalOverrides[(int)shadowType].algorithm;
shadowVariant = (int) m_GlobalOverrides[(int)shadowType].variant;
shadowPrecision = (int) m_GlobalOverrides[(int)shadowType].precision;
shadowAlgorithm = (int)m_GlobalOverrides[(int)shadowType].algorithm;
shadowVariant = (int)m_GlobalOverrides[(int)shadowType].variant;
shadowPrecision = (int)m_GlobalOverrides[(int)shadowType].precision;
asd.GetShadowAlgorithm( out shadowAlgorithm, out shadowVariant, out shadowPrecision );
asd.GetShadowAlgorithm(out shadowAlgorithm, out shadowVariant, out shadowPrecision);
DrawWidgets( l, shadowType, (ShadowAlgorithm) shadowAlgorithm, (ShadowVariant) shadowVariant, (ShadowPrecision) shadowPrecision, globalOverride );
DrawWidgets(l, shadowType, (ShadowAlgorithm)shadowAlgorithm, (ShadowVariant)shadowVariant, (ShadowPrecision)shadowPrecision, globalOverride);
void DrawWidgets( Light l, GPUShadowType shadowType, ShadowAlgorithm shadowAlgorithm, ShadowVariant shadowVariant, ShadowPrecision shadowPrecision, bool globalOverride )
void DrawWidgets(Light l, GPUShadowType shadowType, ShadowAlgorithm shadowAlgorithm, ShadowVariant shadowVariant, ShadowPrecision shadowPrecision, bool globalOverride)
{
#if UNITY_EDITOR
var dict = m_Entries[(int)shadowType];

foreach( var entry in dict )
foreach (var entry in dict)
algoOptions[idx] = (int) entry.Key;
algoDescs[idx] = new GUIContent( entry.Value.algorithmDesc );
algoOptions[idx] = (int)entry.Key;
algoDescs[idx] = new GUIContent(entry.Value.algorithmDesc);
idx++;
}

shadowAlgorithm = (ShadowAlgorithm) UnityEditor.EditorGUILayout.IntPopup( new GUIContent( "Shadow Algorithm" ), (int) shadowAlgorithm, algoDescs, algoOptions );
if( UnityEditor.EditorGUI.EndChangeCheck() )
shadowAlgorithm = (ShadowAlgorithm)UnityEditor.EditorGUILayout.IntPopup(new GUIContent("Shadow Algorithm"), (int)shadowAlgorithm, algoDescs, algoOptions);
if (UnityEditor.EditorGUI.EndChangeCheck())
shadowVariant = 0;
}

GUIContent[] varDescs = new GUIContent[varsAvailable];
idx = 0;
for( int writeIdx = 0; writeIdx < varsAvailable; idx++ )
for (int writeIdx = 0; writeIdx < varsAvailable; idx++)
if( e.variantDels[idx].low != null || e.variantDels[idx].high != null )
if (e.variantDels[idx].low != null || e.variantDels[idx].high != null)
varDescs[writeIdx] = new GUIContent( e.variantDescs[idx] );
varDescs[writeIdx] = new GUIContent(e.variantDescs[idx]);
writeIdx++;
}
}

using( new UnityEditor.EditorGUI.DisabledGroupScope( globalOverride ) )
using (new UnityEditor.EditorGUI.DisabledGroupScope(globalOverride))
shadowVariant = (ShadowVariant) UnityEditor.EditorGUILayout.IntPopup( new GUIContent( "Variant + Precision" ), (int) shadowVariant, varDescs, varOptions );
shadowVariant = (ShadowVariant)UnityEditor.EditorGUILayout.IntPopup(new GUIContent("Variant + Precision"), (int)shadowVariant, varDescs, varOptions);
if( e.variantDels[(int)shadowVariant].low != null && e.variantDels[(int)shadowVariant].high != null )
if (e.variantDels[(int)shadowVariant].low != null && e.variantDels[(int)shadowVariant].high != null)
GUIContent[] precDescs = new GUIContent[] { new GUIContent( "High" ), new GUIContent( "Low" ) };
GUIContent[] precDescs = new GUIContent[] { new GUIContent("High"), new GUIContent("Low") };
using( new UnityEditor.EditorGUI.DisabledScope() )
using (new UnityEditor.EditorGUI.DisabledScope())
GUIContent[] precDescs = new GUIContent[] { new GUIContent( e.variantDels[(int)shadowVariant].low == null ? "High" : "Low" ) };
GUIContent[] precDescs = new GUIContent[] { new GUIContent(e.variantDels[(int)shadowVariant].low == null ? "High" : "Low") };
shadowPrecision = (ShadowPrecision) precOptions[0];
shadowPrecision = (ShadowPrecision)precOptions[0];
GPUShadowAlgorithm packedAlgo = ShadowUtils.Pack( shadowAlgorithm, shadowVariant, shadowPrecision );
GPUShadowAlgorithm packedAlgo = ShadowUtils.Pack(shadowAlgorithm, shadowVariant, shadowPrecision);
if( !GUILayout.Button( "Reset", GUILayout.MaxWidth( 80.0f ) ) )
shadowData = asd.GetShadowData( (int) packedAlgo );
if (!GUILayout.Button("Reset", GUILayout.MaxWidth(80.0f)))
shadowData = asd.GetShadowData((int)packedAlgo);
if( shadowPrecision == ShadowPrecision.Low )
e.variantDels[(int) shadowVariant].low( l, shadowAlgorithm, shadowVariant, shadowPrecision, ref shadowData );
if (shadowPrecision == ShadowPrecision.Low)
e.variantDels[(int)shadowVariant].low(l, shadowAlgorithm, shadowVariant, shadowPrecision, ref shadowData);
e.variantDels[(int) shadowVariant].high( l, shadowAlgorithm, shadowVariant, shadowPrecision, ref shadowData );
asd.SetShadowAlgorithm( (int) shadowAlgorithm, (int) shadowVariant, (int) shadowPrecision, (int) packedAlgo, shadowData );
e.variantDels[(int)shadowVariant].high(l, shadowAlgorithm, shadowVariant, shadowPrecision, ref shadowData);
asd.SetShadowAlgorithm((int)shadowAlgorithm, (int)shadowVariant, (int)shadowPrecision, (int)packedAlgo, shadowData);
public void SetGlobalShadowOverride( GPUShadowType shadowType, ShadowAlgorithm shadowAlgorithm, ShadowVariant shadowVariant, ShadowPrecision shadowPrecision, bool enable )
public void SetGlobalShadowOverride(GPUShadowType shadowType, ShadowAlgorithm shadowAlgorithm, ShadowVariant shadowVariant, ShadowPrecision shadowPrecision, bool enable)
{
m_GlobalOverrides[(int)shadowType].enabled = enable;
m_GlobalOverrides[(int)shadowType].algorithm = shadowAlgorithm;

void SetGlobalOverrideEnabled( GPUShadowType shadowType, bool enabled )
void SetGlobalOverrideEnabled(GPUShadowType shadowType, bool enabled)
public bool GetGlobalShadowOverride( GPUShadowType shadowType, ref GPUShadowAlgorithm algo )
public bool GetGlobalShadowOverride(GPUShadowType shadowType, ref GPUShadowAlgorithm algo)
if( m_GlobalOverrides[(int)shadowType].enabled )
algo = ShadowUtils.Pack( m_GlobalOverrides[(int)shadowType].algorithm, m_GlobalOverrides[(int)shadowType].variant, m_GlobalOverrides[(int)shadowType].precision );
if (m_GlobalOverrides[(int)shadowType].enabled)
algo = ShadowUtils.Pack(m_GlobalOverrides[(int)shadowType].algorithm, m_GlobalOverrides[(int)shadowType].variant, m_GlobalOverrides[(int)shadowType].precision);
return m_GlobalOverrides[(int)shadowType].enabled;
}
}

public Vector3 _pad; // 16 byte padding
public Matrix4x4 shadowToWorld; // from light space matrix
public void PackShadowmapId( uint texIdx, uint sampIdx )
public void PackShadowmapId(uint texIdx, uint sampIdx)
Debug.Assert( texIdx <= 0xff );
Debug.Assert( sampIdx <= 0xff );
Debug.Assert(texIdx <= 0xff);
Debug.Assert(sampIdx <= 0xff);
public void UnpackShadowmapId( out uint texIdx, out uint sampIdx )
public void UnpackShadowmapId(out uint texIdx, out uint sampIdx)
public void PackShadowType( GPUShadowType type, GPUShadowAlgorithm algorithm )
public void PackShadowType(GPUShadowType type, GPUShadowAlgorithm algorithm)
shadowType = (uint)type << ShadowConstants.Bits.k_GPUShadowAlgorithm | (uint) algorithm;
shadowType = (uint)type << ShadowConstants.Bits.k_GPUShadowAlgorithm | (uint)algorithm;
}
};

uint anisotropy;
#pragma warning restore 414
public static SamplerState Default()
public static SamplerState Default()
{
SamplerState defaultState;
defaultState.filterMode = FilterMode.Bilinear;

}
public static bool operator ==( SamplerState lhs, SamplerState rhs )
public static bool operator==(SamplerState lhs, SamplerState rhs)
public static bool operator !=( SamplerState lhs, SamplerState rhs ) { return !(lhs == rhs); }
public override bool Equals( object obj ) { return (obj is SamplerState) && (SamplerState) obj == this; }
public static bool operator!=(SamplerState lhs, SamplerState rhs) { return !(lhs == rhs); }
public override bool Equals(object obj) { return (obj is SamplerState) && (SamplerState)obj == this; }
public override int GetHashCode() { /* TODO: implement this at some point */ throw new NotImplementedException(); }
}

uint anisotropy;
#pragma warning restore 414
public static ComparisonSamplerState Default()
public static ComparisonSamplerState Default()
{
ComparisonSamplerState defaultState;
defaultState.filterMode = FilterMode.Bilinear;

}
// TODO: this should either contain the description for a comparison sampler, or be replaced by a struct that does
public static bool operator ==(ComparisonSamplerState lhs, ComparisonSamplerState rhs)
public static bool operator==(ComparisonSamplerState lhs, ComparisonSamplerState rhs)
public static bool operator !=(ComparisonSamplerState lhs, ComparisonSamplerState rhs) { return !(lhs == rhs); }
public override bool Equals( object obj ) { return (obj is ComparisonSamplerState) && (ComparisonSamplerState) obj == this; }
public static bool operator!=(ComparisonSamplerState lhs, ComparisonSamplerState rhs) { return !(lhs == rhs); }
public override bool Equals(object obj) { return (obj is ComparisonSamplerState) && (ComparisonSamplerState)obj == this; }
public override int GetHashCode() { /* TODO: implement this at some point */ throw new NotImplementedException(); }
}
// -------------- End temporary structs that need to be replaced at some point ---------------

public int p2;
public int p3;
public void Set( float v0, float v1, float v2, float v3 )
public void Set(float v0, float v1, float v2, float v3)
p0 = ShadowUtils.Asint( v0 );
p1 = ShadowUtils.Asint( v1 );
p2 = ShadowUtils.Asint( v2 );
p3 = ShadowUtils.Asint( v3 );
p0 = ShadowUtils.Asint(v0);
p1 = ShadowUtils.Asint(v1);
p2 = ShadowUtils.Asint(v2);
p3 = ShadowUtils.Asint(v3);
public void Set( int v0, int v1, int v2, int v3 )
public void Set(int v0, int v1, int v2, int v3)
{
p0 = v0;
p1 = v1;

public void Set( Vector4 v ) { Set( v.x, v.y, v.z, v.w ); }
public void Set(Vector4 v) { Set(v.x, v.y, v.z, v.w); }
}
// Class holding resource information that needs to be synchronized with shaders.

public uint maxComparisonSamplerSlots;
public uint maxSamplerSlots;
}
protected ShadowContextStorage( ref Init initializer )
protected ShadowContextStorage(ref Init initializer)
m_ShadowDatas.Reserve( initializer.maxShadowDataSlots );
m_Payloads.Reserve( initializer.maxPayloadSlots );
m_Tex2DArray.Reserve( initializer.maxTex2DArraySlots );
m_TexCubeArray.Reserve( initializer.maxTexCubeArraySlots );
m_CompSamplers.Reserve( initializer.maxComparisonSamplerSlots );
m_Samplers.Reserve( initializer.maxSamplerSlots );
m_ShadowDatas.Reserve(initializer.maxShadowDataSlots);
m_Payloads.Reserve(initializer.maxPayloadSlots);
m_Tex2DArray.Reserve(initializer.maxTex2DArraySlots);
m_TexCubeArray.Reserve(initializer.maxTexCubeArraySlots);
m_CompSamplers.Reserve(initializer.maxComparisonSamplerSlots);
m_Samplers.Reserve(initializer.maxSamplerSlots);
public uint RequestTex2DArraySlot() { return m_Tex2DArray.Add( new RenderTargetIdentifier() ); }
public uint RequestTexCubeArraySlot() { return m_TexCubeArray.Add( new RenderTargetIdentifier() ); }
public uint RequestSamplerSlot( SamplerState ss )
public uint RequestTex2DArraySlot() { return m_Tex2DArray.Add(new RenderTargetIdentifier()); }
public uint RequestTexCubeArraySlot() { return m_TexCubeArray.Add(new RenderTargetIdentifier()); }
public uint RequestSamplerSlot(SamplerState ss)
if( m_Samplers.FindFirst( out idx, ref ss ) )
if (m_Samplers.FindFirst(out idx, ref ss))
m_Samplers.Add( ss );
m_Samplers.Add(ss);
public uint RequestSamplerSlot( ComparisonSamplerState css )
public uint RequestSamplerSlot(ComparisonSamplerState css)
if( m_CompSamplers.FindFirst( out idx, ref css ) )
if (m_CompSamplers.FindFirst(out idx, ref css))
m_CompSamplers.Add( css );
m_CompSamplers.Add(css);
public void SetTex2DArraySlot( uint slot, RenderTargetIdentifier val ) { m_Tex2DArray[slot] = val; }
public void SetTexCubeArraySlot( uint slot, RenderTargetIdentifier val ) { m_TexCubeArray[slot] = val; }
public void SetTex2DArraySlot(uint slot, RenderTargetIdentifier val) { m_Tex2DArray[slot] = val; }
public void SetTexCubeArraySlot(uint slot, RenderTargetIdentifier val) { m_TexCubeArray[slot] = val; }
protected VectorArray<ShadowData> m_ShadowDatas = new VectorArray<ShadowData>( 0, false );
protected VectorArray<ShadowPayload> m_Payloads = new VectorArray<ShadowPayload>( 0, false );
protected VectorArray<RenderTargetIdentifier> m_Tex2DArray = new VectorArray<RenderTargetIdentifier>( 0, true );
protected VectorArray<RenderTargetIdentifier> m_TexCubeArray = new VectorArray<RenderTargetIdentifier>( 0, true );
protected VectorArray<ComparisonSamplerState> m_CompSamplers = new VectorArray<ComparisonSamplerState>( 0, true );
protected VectorArray<SamplerState> m_Samplers = new VectorArray<SamplerState>( 0, true );
protected VectorArray<ShadowData> m_ShadowDatas = new VectorArray<ShadowData>(0, false);
protected VectorArray<ShadowPayload> m_Payloads = new VectorArray<ShadowPayload>(0, false);
protected VectorArray<RenderTargetIdentifier> m_Tex2DArray = new VectorArray<RenderTargetIdentifier>(0, true);
protected VectorArray<RenderTargetIdentifier> m_TexCubeArray = new VectorArray<RenderTargetIdentifier>(0, true);
protected VectorArray<ComparisonSamplerState> m_CompSamplers = new VectorArray<ComparisonSamplerState>(0, true);
protected VectorArray<SamplerState> m_Samplers = new VectorArray<SamplerState>(0, true);
public delegate void SyncDel( ShadowContext sc );
public delegate void BindDel( ShadowContext sc, CommandBuffer cb, ComputeShader computeShader, int computeKernel);
public delegate void SyncDel(ShadowContext sc);
public delegate void BindDel(ShadowContext sc, CommandBuffer cb, ComputeShader computeShader, int computeKernel);
public struct CtxtInit
{
public Init storage;

public ShadowContext( ref CtxtInit initializer ) : base( ref initializer.storage )
public ShadowContext(ref CtxtInit initializer) : base(ref initializer.storage)
Debug.Assert( initializer.dataSyncer != null && initializer.resourceBinder != null );
Debug.Assert(initializer.dataSyncer != null && initializer.resourceBinder != null);
public void SyncData() { m_DataSyncerDel( this ); }
public void SyncData() { m_DataSyncerDel(this); }
public void BindResources( CommandBuffer cb, ComputeShader computeShader, int computeKernel) { m_ResourceBinderDel( this, cb, computeShader, computeKernel); }
public void BindResources(CommandBuffer cb, ComputeShader computeShader, int computeKernel) { m_ResourceBinderDel(this, cb, computeShader, computeKernel); }
public void GetShadowDatas( out ShadowData[] shadowDatas, out uint offset, out uint count ) { shadowDatas = m_ShadowDatas.AsArray( out offset, out count ); }
public void GetPayloads( out ShadowPayload[] payloads, out uint offset, out uint count ) { payloads = m_Payloads.AsArray( out offset, out count ); }
public void GetTex2DArrays( out RenderTargetIdentifier[] tex2DArrays, out uint offset, out uint count ) { tex2DArrays = m_Tex2DArray.AsArray( out offset, out count ); }
public void GetTexCubeArrays( out RenderTargetIdentifier[] texCubeArrays, out uint offset, out uint count ) { texCubeArrays = m_TexCubeArray.AsArray( out offset, out count ); }
public void GetComparisonSamplerArrays( out ComparisonSamplerState[] compSamplers, out uint offset, out uint count ) { compSamplers = m_CompSamplers.AsArray( out offset, out count ); }
public void GetSamplerArrays( out SamplerState[] samplerArrays, out uint offset, out uint count ) { samplerArrays = m_Samplers.AsArray( out offset, out count ); }
public void GetShadowDatas(out ShadowData[] shadowDatas, out uint offset, out uint count) { shadowDatas = m_ShadowDatas.AsArray(out offset, out count); }
public void GetPayloads(out ShadowPayload[] payloads, out uint offset, out uint count) { payloads = m_Payloads.AsArray(out offset, out count); }
public void GetTex2DArrays(out RenderTargetIdentifier[] tex2DArrays, out uint offset, out uint count) { tex2DArrays = m_Tex2DArray.AsArray(out offset, out count); }
public void GetTexCubeArrays(out RenderTargetIdentifier[] texCubeArrays, out uint offset, out uint count) { texCubeArrays = m_TexCubeArray.AsArray(out offset, out count); }
public void GetComparisonSamplerArrays(out ComparisonSamplerState[] compSamplers, out uint offset, out uint count) { compSamplers = m_CompSamplers.AsArray(out offset, out count); }
public void GetSamplerArrays(out SamplerState[] samplerArrays, out uint offset, out uint count) { samplerArrays = m_Samplers.AsArray(out offset, out count); }
private SyncDel m_DataSyncerDel;
private BindDel m_ResourceBinderDel;

// shadow type of this light
public GPUShadowType shadowType
{
get { return (GPUShadowType) (m_ShadowTypeAndAlgorithm >> ShadowConstants.Bits.k_GPUShadowAlgorithm); }
get { return (GPUShadowType)(m_ShadowTypeAndAlgorithm >> ShadowConstants.Bits.k_GPUShadowAlgorithm); }
get { return (GPUShadowAlgorithm) (m_ShadowTypeAndAlgorithm & ShadowConstants.Masks.k_GPUShadowAlgorithm); }
get { return (GPUShadowAlgorithm)(m_ShadowTypeAndAlgorithm & ShadowConstants.Masks.k_GPUShadowAlgorithm); }
set { m_ShadowTypeAndAlgorithm = (m_ShadowTypeAndAlgorithm & ~(ShadowConstants.Masks.k_GPUShadowAlgorithm)) | (int)value; }
}
// index into the visible lights array

public ShadowSupport shadowSupport; // bitmask of all shadow types that this shadowmap supports
};
protected ShadowmapBase( ref BaseInit initializer )
protected ShadowmapBase(ref BaseInit initializer)
{
m_Width = initializer.width;
m_Height = initializer.height;

return m_ShadowmapFormat == RenderTextureFormat.Shadowmap || m_ShadowmapFormat == RenderTextureFormat.Depth;
}
public void Register( ShadowRegistry registry )
public void Register(ShadowRegistry registry)
for( GPUShadowType i = GPUShadowType.Point; i < GPUShadowType.MAX; ++i, bit <<= 1 )
for (GPUShadowType i = GPUShadowType.Point; i < GPUShadowType.MAX; ++i, bit <<= 1)
if( ((int)m_ShadowSupport & bit) != 0 )
Register( i, registry );
if (((int)m_ShadowSupport & bit) != 0)
Register(i, registry);
public ShadowSupport QueryShadowSupport() { return m_ShadowSupport; }
public uint GetMaxPayload() { return m_MaxPayloadCount; }
public void Assign( CullResults cullResults ) { m_CullResults = cullResults; } // TODO: Remove when m_CullResults is removed again
abstract public bool Reserve( FrameId frameId, Camera camera, bool cameraRelativeRendering, ref ShadowData shadowData, ShadowRequest sr, uint width, uint height, ref VectorArray<ShadowData> entries, ref VectorArray<ShadowPayload> payloads, List<VisibleLight> lights);
abstract public bool Reserve( FrameId frameId, Camera camera, bool cameraRelativeRendering, ref ShadowData shadowData, ShadowRequest sr, uint[] widths, uint[] heights, ref VectorArray<ShadowData> entries, ref VectorArray<ShadowPayload> payloads, List<VisibleLight> lights);
abstract public bool ReserveFinalize( FrameId frameId, ref VectorArray<ShadowData> entries, ref VectorArray<ShadowPayload> payloads );
abstract public void Update( FrameId frameId, ScriptableRenderContext renderContext, CommandBuffer cmd, CullResults cullResults, List<VisibleLight> lights);
abstract public void ReserveSlots( ShadowContextStorage sc );
abstract public void Fill( ShadowContextStorage cs );
public ShadowSupport QueryShadowSupport() { return m_ShadowSupport; }
public uint GetMaxPayload() { return m_MaxPayloadCount; }
public void Assign(CullResults cullResults) { m_CullResults = cullResults; } // TODO: Remove when m_CullResults is removed again
abstract public bool Reserve(FrameId frameId, Camera camera, bool cameraRelativeRendering, ref ShadowData shadowData, ShadowRequest sr, uint width, uint height, ref VectorArray<ShadowData> entries, ref VectorArray<ShadowPayload> payloads, List<VisibleLight> lights);
abstract public bool Reserve(FrameId frameId, Camera camera, bool cameraRelativeRendering, ref ShadowData shadowData, ShadowRequest sr, uint[] widths, uint[] heights, ref VectorArray<ShadowData> entries, ref VectorArray<ShadowPayload> payloads, List<VisibleLight> lights);
abstract public bool ReserveFinalize(FrameId frameId, ref VectorArray<ShadowData> entries, ref VectorArray<ShadowPayload> payloads);
abstract public void Update(FrameId frameId, ScriptableRenderContext renderContext, CommandBuffer cmd, CullResults cullResults, List<VisibleLight> lights);
abstract public void ReserveSlots(ShadowContextStorage sc);
abstract public void Fill(ShadowContextStorage cs);
abstract protected void Register( GPUShadowType type, ShadowRegistry registry );
abstract protected void Register(GPUShadowType type, ShadowRegistry registry);
abstract public void DisplayShadowMap(CommandBuffer cmd, Material debugMaterial, Vector4 scaleBias, uint slice, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY);
}

// shadowPayloads contains implementation specific data that is accessed from the shader by indexing into an Buffer<int> using ShadowData.ShadowmapData.payloadOffset.
// This is the equivalent of a void pointer in the shader and there needs to be loader code that knows how to interpret the data.
// If there are no valid shadow casters all output arrays will be null, otherwise they will contain valid data that can be passed to shaders.
void ProcessShadowRequests( FrameId frameId, CullResults cullResults, Camera camera, bool cameraRelativeRendering, List<VisibleLight> lights, ref uint shadowRequestsCount, int[] shadowRequests, out int[] shadowDataIndices );
void ProcessShadowRequests(FrameId frameId, CullResults cullResults, Camera camera, bool cameraRelativeRendering, List<VisibleLight> lights, ref uint shadowRequestsCount, int[] shadowRequests, out int[] shadowDataIndices);
void RenderShadows( FrameId frameId, ScriptableRenderContext renderContext, CommandBuffer cmd, CullResults cullResults, List<VisibleLight> lights);
void RenderShadows(FrameId frameId, ScriptableRenderContext renderContext, CommandBuffer cmd, CullResults cullResults, List<VisibleLight> lights);
// Debug function to display a shadow at the screen coordinate
void DisplayShadow(CommandBuffer cmd, Material debugMaterial, int shadowIndex, uint faceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY);
void DisplayShadowMap(CommandBuffer cmd, Material debugMaterial, uint shadowMapIndex, uint sliceIndex, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, bool flipY);

void BindResources( CommandBuffer cmd, ComputeShader computeShader, int computeKernel);
void BindResources(CommandBuffer cmd, ComputeShader computeShader, int computeKernel);
void UpdateCullingParameters( ref ScriptableCullingParameters cullingParams );
void UpdateCullingParameters(ref ScriptableCullingParameters cullingParams);
uint GetShadowMapCount();
uint GetShadowMapSliceCount(uint shadowMapIndex);

abstract public class ShadowManagerBase : ShadowRegistry, IShadowManager
{
public abstract void ProcessShadowRequests( FrameId frameId, CullResults cullResults, Camera camera, bool cameraRelativeRendering, List<VisibleLight> lights, ref uint shadowRequestsCount, int[] shadowRequests, out int[] shadowDataIndices );
public abstract void RenderShadows( FrameId frameId, ScriptableRenderContext renderContext, CommandBuffer cmd, CullResults cullResults, List<VisibleLight> lights);
public abstract void ProcessShadowRequests(FrameId frameId, CullResults cullResults, Camera camera, bool cameraRelativeRendering, List<VisibleLight> lights, ref uint shadowRequestsCount, int[] shadowRequests, out int[] shadowDataIndices);
public abstract void RenderShadows(FrameId frameId, ScriptableRenderContext renderContext, CommandBuffer cmd, CullResults cullResults, List<VisibleLight> lights);
public abstract void BindResources( CommandBuffer cmd, ComputeShader computeShader, int computeKernel);
public abstract void UpdateCullingParameters( ref ScriptableCullingParameters cullingParams );
public abstract void BindResources(CommandBuffer cmd, ComputeShader computeShader, int computeKernel);
public abstract void UpdateCullingParameters(ref ScriptableCullingParameters cullingParams);
protected abstract void PrioritizeShadowCasters( Camera camera, List<VisibleLight> lights, uint shadowRequestsCount, int[] shadowRequests );
protected abstract void PrioritizeShadowCasters(Camera camera, List<VisibleLight> lights, uint shadowRequestsCount, int[] shadowRequests);
protected abstract void PruneShadowCasters( Camera camera, List<VisibleLight> lights, ref VectorArray<int> shadowRequests, ref VectorArray<ShadowmapBase.ShadowRequest> requestsGranted, out uint totalRequestCount );
protected abstract void PruneShadowCasters(Camera camera, List<VisibleLight> lights, ref VectorArray<int> shadowRequests, ref VectorArray<ShadowmapBase.ShadowRequest> requestsGranted, out uint totalRequestCount);
protected abstract bool AllocateShadows( FrameId frameId, Camera camera, bool cameraRelativeRendering, List<VisibleLight> lights, uint totalGranted, ref VectorArray<ShadowmapBase.ShadowRequest> grantedRequests, ref VectorArray<int> shadowIndices, ref VectorArray<ShadowData> shadowmapDatas, ref VectorArray<ShadowPayload> shadowmapPayload );
protected abstract bool AllocateShadows(FrameId frameId, Camera camera, bool cameraRelativeRendering, List<VisibleLight> lights, uint totalGranted, ref VectorArray<ShadowmapBase.ShadowRequest> grantedRequests, ref VectorArray<int> shadowIndices, ref VectorArray<ShadowData> shadowmapDatas, ref VectorArray<ShadowPayload> shadowmapPayload);
public abstract uint GetShadowMapCount();
public abstract uint GetShadowMapSliceCount(uint shadowMapIndex);

}
} // end of namespace UnityEngine.Experimental.ScriptableRenderLoop

34
com.unity.render-pipelines.core/CoreRP/Shadow/ShadowBase.cs.hlsl


//
float4 GetProj(ShadowData value)
{
return value.proj;
return value.proj;
return value.pos;
return value.pos;
return value.rot0;
return value.rot0;
return value.rot1;
return value.rot1;
return value.rot2;
return value.rot2;
return value.scaleOffset;
return value.scaleOffset;
return value.textureSize;
return value.textureSize;
return value.texelSizeRcp;
return value.texelSizeRcp;
return value.id;
return value.id;
return value.shadowType;
return value.shadowType;
return value.payloadOffset;
return value.payloadOffset;
return value.slice;
return value.slice;
return value.viewBias;
return value.viewBias;
return value.normalBias;
return value.normalBias;
return value.edgeTolerance;
return value.edgeTolerance;
return value._pad;
return value._pad;
return value.shadowToWorld;
return value.shadowToWorld;
}

428
com.unity.render-pipelines.core/CoreRP/Shadow/ShadowBlurMoments.compute


#define VSM 0
#define EVSM_2 1
#define EVSM_4 2
#define MSM 3
#define THREADS 16
#define MAX_BLUR_SIZE (THREADS+1)
#define VSM 0
#define EVSM_2 1
#define EVSM_4 2
#define MSM 3
#define THREADS 16
#define MAX_BLUR_SIZE (THREADS+1)
#pragma kernel main_VSM_3 KERNEL_MAIN=main_VSM_3 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=3
#pragma kernel main_VSM_5 KERNEL_MAIN=main_VSM_5 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=5
#pragma kernel main_VSM_7 KERNEL_MAIN=main_VSM_7 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=7
#pragma kernel main_VSM_9 KERNEL_MAIN=main_VSM_9 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=9
#pragma kernel main_VSM_11 KERNEL_MAIN=main_VSM_11 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=11
#pragma kernel main_VSM_13 KERNEL_MAIN=main_VSM_13 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=13
#pragma kernel main_VSM_15 KERNEL_MAIN=main_VSM_15 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=15
#pragma kernel main_VSM_17 KERNEL_MAIN=main_VSM_17 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=17
#pragma kernel main_VSM_3 KERNEL_MAIN=main_VSM_3 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=3
#pragma kernel main_VSM_5 KERNEL_MAIN=main_VSM_5 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=5
#pragma kernel main_VSM_7 KERNEL_MAIN=main_VSM_7 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=7
#pragma kernel main_VSM_9 KERNEL_MAIN=main_VSM_9 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=9
#pragma kernel main_VSM_11 KERNEL_MAIN=main_VSM_11 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=11
#pragma kernel main_VSM_13 KERNEL_MAIN=main_VSM_13 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=13
#pragma kernel main_VSM_15 KERNEL_MAIN=main_VSM_15 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=15
#pragma kernel main_VSM_17 KERNEL_MAIN=main_VSM_17 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=17
#pragma kernel main_EVSM_2_3 KERNEL_MAIN=main_EVSM_2_3 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=3
#pragma kernel main_EVSM_2_5 KERNEL_MAIN=main_EVSM_2_5 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=5
#pragma kernel main_EVSM_2_7 KERNEL_MAIN=main_EVSM_2_7 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=7
#pragma kernel main_EVSM_2_9 KERNEL_MAIN=main_EVSM_2_9 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=9
#pragma kernel main_EVSM_2_11 KERNEL_MAIN=main_EVSM_2_11 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=11
#pragma kernel main_EVSM_2_13 KERNEL_MAIN=main_EVSM_2_13 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=13
#pragma kernel main_EVSM_2_15 KERNEL_MAIN=main_EVSM_2_15 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=15
#pragma kernel main_EVSM_2_17 KERNEL_MAIN=main_EVSM_2_17 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=17
#pragma kernel main_EVSM_2_3 KERNEL_MAIN=main_EVSM_2_3 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=3
#pragma kernel main_EVSM_2_5 KERNEL_MAIN=main_EVSM_2_5 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=5
#pragma kernel main_EVSM_2_7 KERNEL_MAIN=main_EVSM_2_7 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=7
#pragma kernel main_EVSM_2_9 KERNEL_MAIN=main_EVSM_2_9 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=9
#pragma kernel main_EVSM_2_11 KERNEL_MAIN=main_EVSM_2_11 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=11
#pragma kernel main_EVSM_2_13 KERNEL_MAIN=main_EVSM_2_13 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=13
#pragma kernel main_EVSM_2_15 KERNEL_MAIN=main_EVSM_2_15 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=15
#pragma kernel main_EVSM_2_17 KERNEL_MAIN=main_EVSM_2_17 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=1 BLUR_SIZE=17
#pragma kernel main_EVSM_4_3 KERNEL_MAIN=main_EVSM_4_3 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=3
#pragma kernel main_EVSM_4_5 KERNEL_MAIN=main_EVSM_4_5 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=5
#pragma kernel main_EVSM_4_7 KERNEL_MAIN=main_EVSM_4_7 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=7
#pragma kernel main_EVSM_4_9 KERNEL_MAIN=main_EVSM_4_9 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=9
#pragma kernel main_EVSM_4_11 KERNEL_MAIN=main_EVSM_4_11 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=11
#pragma kernel main_EVSM_4_13 KERNEL_MAIN=main_EVSM_4_13 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=13
#pragma kernel main_EVSM_4_15 KERNEL_MAIN=main_EVSM_4_15 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=15
#pragma kernel main_EVSM_4_17 KERNEL_MAIN=main_EVSM_4_17 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=17
#pragma kernel main_EVSM_4_3 KERNEL_MAIN=main_EVSM_4_3 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=3
#pragma kernel main_EVSM_4_5 KERNEL_MAIN=main_EVSM_4_5 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=5
#pragma kernel main_EVSM_4_7 KERNEL_MAIN=main_EVSM_4_7 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=7
#pragma kernel main_EVSM_4_9 KERNEL_MAIN=main_EVSM_4_9 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=9
#pragma kernel main_EVSM_4_11 KERNEL_MAIN=main_EVSM_4_11 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=11
#pragma kernel main_EVSM_4_13 KERNEL_MAIN=main_EVSM_4_13 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=13
#pragma kernel main_EVSM_4_15 KERNEL_MAIN=main_EVSM_4_15 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=15
#pragma kernel main_EVSM_4_17 KERNEL_MAIN=main_EVSM_4_17 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=1 BLUR_SIZE=17
#pragma kernel main_MSM_3 KERNEL_MAIN=main_MSM_3 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=3
#pragma kernel main_MSM_5 KERNEL_MAIN=main_MSM_5 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=5
#pragma kernel main_MSM_7 KERNEL_MAIN=main_MSM_7 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=7
#pragma kernel main_MSM_9 KERNEL_MAIN=main_MSM_9 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=9
#pragma kernel main_MSM_11 KERNEL_MAIN=main_MSM_11 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=11
#pragma kernel main_MSM_13 KERNEL_MAIN=main_MSM_13 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=13
#pragma kernel main_MSM_15 KERNEL_MAIN=main_MSM_15 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=15
#pragma kernel main_MSM_17 KERNEL_MAIN=main_MSM_17 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=17
#pragma kernel main_MSM_3 KERNEL_MAIN=main_MSM_3 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=3
#pragma kernel main_MSM_5 KERNEL_MAIN=main_MSM_5 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=5
#pragma kernel main_MSM_7 KERNEL_MAIN=main_MSM_7 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=7
#pragma kernel main_MSM_9 KERNEL_MAIN=main_MSM_9 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=9
#pragma kernel main_MSM_11 KERNEL_MAIN=main_MSM_11 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=11
#pragma kernel main_MSM_13 KERNEL_MAIN=main_MSM_13 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=13
#pragma kernel main_MSM_15 KERNEL_MAIN=main_MSM_15 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=15
#pragma kernel main_MSM_17 KERNEL_MAIN=main_MSM_17 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=17
#pragma kernel main_MSAA_VSM_3 KERNEL_MAIN=main_MSAA_VSM_3 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_VSM_5 KERNEL_MAIN=main_MSAA_VSM_5 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_VSM_7 KERNEL_MAIN=main_MSAA_VSM_7 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_VSM_9 KERNEL_MAIN=main_MSAA_VSM_9 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_VSM_11 KERNEL_MAIN=main_MSAA_VSM_11 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_VSM_13 KERNEL_MAIN=main_MSAA_VSM_13 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_VSM_15 KERNEL_MAIN=main_MSAA_VSM_15 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_VSM_17 KERNEL_MAIN=main_MSAA_VSM_17 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=17
#pragma kernel main_MSAA_VSM_3 KERNEL_MAIN=main_MSAA_VSM_3 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_VSM_5 KERNEL_MAIN=main_MSAA_VSM_5 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_VSM_7 KERNEL_MAIN=main_MSAA_VSM_7 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_VSM_9 KERNEL_MAIN=main_MSAA_VSM_9 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_VSM_11 KERNEL_MAIN=main_MSAA_VSM_11 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_VSM_13 KERNEL_MAIN=main_MSAA_VSM_13 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_VSM_15 KERNEL_MAIN=main_MSAA_VSM_15 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_VSM_17 KERNEL_MAIN=main_MSAA_VSM_17 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=17
#pragma kernel main_MSAA_EVSM_2_3 KERNEL_MAIN=main_MSAA_EVSM_2_3 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_EVSM_2_5 KERNEL_MAIN=main_MSAA_EVSM_2_5 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_EVSM_2_7 KERNEL_MAIN=main_MSAA_EVSM_2_7 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_EVSM_2_9 KERNEL_MAIN=main_MSAA_EVSM_2_9 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_EVSM_2_11 KERNEL_MAIN=main_MSAA_EVSM_2_11 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_EVSM_2_13 KERNEL_MAIN=main_MSAA_EVSM_2_13 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_EVSM_2_15 KERNEL_MAIN=main_MSAA_EVSM_2_15 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_EVSM_2_17 KERNEL_MAIN=main_MSAA_EVSM_2_17 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=17
#pragma kernel main_MSAA_EVSM_2_3 KERNEL_MAIN=main_MSAA_EVSM_2_3 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_EVSM_2_5 KERNEL_MAIN=main_MSAA_EVSM_2_5 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_EVSM_2_7 KERNEL_MAIN=main_MSAA_EVSM_2_7 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_EVSM_2_9 KERNEL_MAIN=main_MSAA_EVSM_2_9 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_EVSM_2_11 KERNEL_MAIN=main_MSAA_EVSM_2_11 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_EVSM_2_13 KERNEL_MAIN=main_MSAA_EVSM_2_13 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_EVSM_2_15 KERNEL_MAIN=main_MSAA_EVSM_2_15 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_EVSM_2_17 KERNEL_MAIN=main_MSAA_EVSM_2_17 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=17
#pragma kernel main_MSAA_EVSM_4_3 KERNEL_MAIN=main_MSAA_EVSM_4_3 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_EVSM_4_5 KERNEL_MAIN=main_MSAA_EVSM_4_5 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_EVSM_4_7 KERNEL_MAIN=main_MSAA_EVSM_4_7 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_EVSM_4_9 KERNEL_MAIN=main_MSAA_EVSM_4_9 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_EVSM_4_11 KERNEL_MAIN=main_MSAA_EVSM_4_11 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_EVSM_4_13 KERNEL_MAIN=main_MSAA_EVSM_4_13 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_EVSM_4_15 KERNEL_MAIN=main_MSAA_EVSM_4_15 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_EVSM_4_17 KERNEL_MAIN=main_MSAA_EVSM_4_17 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=17
#pragma kernel main_MSAA_EVSM_4_3 KERNEL_MAIN=main_MSAA_EVSM_4_3 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_EVSM_4_5 KERNEL_MAIN=main_MSAA_EVSM_4_5 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_EVSM_4_7 KERNEL_MAIN=main_MSAA_EVSM_4_7 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_EVSM_4_9 KERNEL_MAIN=main_MSAA_EVSM_4_9 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_EVSM_4_11 KERNEL_MAIN=main_MSAA_EVSM_4_11 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_EVSM_4_13 KERNEL_MAIN=main_MSAA_EVSM_4_13 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_EVSM_4_15 KERNEL_MAIN=main_MSAA_EVSM_4_15 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_EVSM_4_17 KERNEL_MAIN=main_MSAA_EVSM_4_17 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=17
#pragma kernel main_MSAA_MSM_3 KERNEL_MAIN=main_MSAA_MSM_3 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_MSM_5 KERNEL_MAIN=main_MSAA_MSM_5 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_MSM_7 KERNEL_MAIN=main_MSAA_MSM_7 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_MSM_9 KERNEL_MAIN=main_MSAA_MSM_9 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_MSM_11 KERNEL_MAIN=main_MSAA_MSM_11 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_MSM_13 KERNEL_MAIN=main_MSAA_MSM_13 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_MSM_15 KERNEL_MAIN=main_MSAA_MSM_15 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_MSM_17 KERNEL_MAIN=main_MSAA_MSM_17 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=17
#pragma kernel main_MSAA_MSM_3 KERNEL_MAIN=main_MSAA_MSM_3 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_MSM_5 KERNEL_MAIN=main_MSAA_MSM_5 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_MSM_7 KERNEL_MAIN=main_MSAA_MSM_7 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_MSM_9 KERNEL_MAIN=main_MSAA_MSM_9 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_MSM_11 KERNEL_MAIN=main_MSAA_MSM_11 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_MSM_13 KERNEL_MAIN=main_MSAA_MSM_13 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_MSM_15 KERNEL_MAIN=main_MSAA_MSM_15 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_MSM_17 KERNEL_MAIN=main_MSAA_MSM_17 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=17
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/Shadow/ShadowMoments.hlsl"

Texture2D<float> depthTex;
#endif
uniform uint4 srcRect; // .xy = offset, .zw = width/height
uniform uint4 dstRect; // .xy = offset, .z = array slice , .w = Flags: 1 := 16bpp, 2 := 2 channels pp, 4:= reversed z
uniform uint4 srcRect; // .xy = offset, .zw = width/height
uniform uint4 dstRect; // .xy = offset, .z = array slice , .w = Flags: 1 := 16bpp, 2 := 2 channels pp, 4:= reversed z
static const int kBits_16 = 1; // 16 bits per channel
static const int kBits_16 = 1; // 16 bits per channel
# define SHADOW_MOMENTS 2
# define SHADOW_MOMENTS 2
float2 DepthToMoments( float depth )
{
return float2( depth, depth * depth );
}
float2 DepthToMoments( float depth )
{
return float2( depth, depth * depth );
}
# define SHADOW_MOMENTS 2
# define SHADOW_MOMENTS 2
uniform float evsmExponent;
uniform float evsmExponent;
float2 DepthToMoments( float depth )
{
float2 moments = ShadowMoments_WarpDepth( depth, evsmExponent.xx );
return float2( moments.x, moments.x * moments.x );
}
float2 DepthToMoments( float depth )
{
float2 moments = ShadowMoments_WarpDepth( depth, evsmExponent.xx );
return float2( moments.x, moments.x * moments.x );
}
# define SHADOW_MOMENTS 4
# define SHADOW_MOMENTS 4
uniform float2 evsmExponents;
uniform float2 evsmExponents;
float4 DepthToMoments( float depth )
{
float2 moments = ShadowMoments_WarpDepth( depth, evsmExponents );
return float4( moments.xy, moments.xy * moments.xy );
}
float4 DepthToMoments( float depth )
{
float2 moments = ShadowMoments_WarpDepth( depth, evsmExponents );
return float4( moments.xy, moments.xy * moments.xy );
}
# define SHADOW_MOMENTS 4
# define SHADOW_MOMENTS 4
float4 DepthToMoments( float depth )
{
if( (dstRect.w & kBits_16) != 0 )
return ShadowMoments_Encode16MSM( depth );
else
{
float dsq = depth * depth;
return float4( depth, dsq, depth * dsq, dsq * dsq );
}
}
float4 DepthToMoments( float depth )
{
if( (dstRect.w & kBits_16) != 0 )
return ShadowMoments_Encode16MSM( depth );
else
{
float dsq = depth * depth;
return float4( depth, dsq, depth * dsq, dsq * dsq );
}
}
# error "No valid shadow moment algorithm has been set to the define SHADOW_MOMENT_ALGORITHM."
# error "No valid shadow moment algorithm has been set to the define SHADOW_MOMENT_ALGORITHM."
#endif

#define moment_t MERGE_NAME( float, SHADOW_MOMENTS )
RWTexture2DArray<moment_t> outputTex;
RWTexture2DArray<moment_t> outputTex;
groupshared float moments1[THREADS * LDS_STRIDE]; // contains the blurred first moment
groupshared float moments2[THREADS * LDS_STRIDE]; // contains the blurred second moment

int getLDSIdx( int2 pos, int stride )
{
// interleave two consecutive rows to avoid bank conflicts
return (pos.y >> 1) * (stride << 1) + (pos.x << 1) + (pos.y & 1);
// interleave two consecutive rows to avoid bank conflicts
return (pos.y >> 1) * (stride << 1) + (pos.x << 1) + (pos.y & 1);
int idx = getLDSIdx( pos, stride );
moments1[idx] = val.x;
moments2[idx] = val.y;
int idx = getLDSIdx( pos, stride );
moments1[idx] = val.x;
moments2[idx] = val.y;
moments3[idx] = val.z;
moments4[idx] = val.w;
moments3[idx] = val.z;
moments4[idx] = val.w;
int idx = getLDSIdx( pos, stride );
moment_t res;
res.x = moments1[idx];
res.y = moments2[idx];
int idx = getLDSIdx( pos, stride );
moment_t res;
res.x = moments1[idx];
res.y = moments2[idx];
res.z = moments3[idx];
res.w = moments4[idx];
res.z = moments3[idx];
res.w = moments4[idx];
return res;
return res;
}
[numthreads( THREADS, THREADS, 1 )]

uint width, height, sampleCnt;
depthTex.GetDimensions( width, height, sampleCnt );
sampleCnt = clamp( sampleCnt, 2, MAX_MSAA );
float sampleCntRcp = 1.0 / sampleCnt;
uint width, height, sampleCnt;
depthTex.GetDimensions( width, height, sampleCnt );
sampleCnt = clamp( sampleCnt, 2, MAX_MSAA );
float sampleCntRcp = 1.0 / sampleCnt;
// calculate weights based on sample positions
if( groupThreadId.x < sampleCnt )
{
float2 spos = depthTex.GetSamplePosition( groupThreadId.x );
sampleWeights[groupThreadId.x] = sampleCntRcp;
}
if( groupThreadId.x == 0 )
{
float sum = 0.0;
for( uint i = 0; i < sampleCnt; i++ )
sum += sampleWeights[i];
sumWeights = 1.0 / sum;
}
// calculate weights based on sample positions
if( groupThreadId.x < sampleCnt )
{
float2 spos = depthTex.GetSamplePosition( groupThreadId.x );
sampleWeights[groupThreadId.x] = sampleCntRcp;
}
if( groupThreadId.x == 0 )
{
float sum = 0.0;
for( uint i = 0; i < sampleCnt; i++ )
sum += sampleWeights[i];
sumWeights = 1.0 / sum;
}
// load moments into LDS
// each workgroup works on THREADS * THREADS tiles, but the blur filter requires
// us to fetch enough data around the border of the current tile.
// We assume that the blur filter's support does not exceed THREADS, so we fetch
// the data in 4 blocks.
const bool reverse_z = (dstRect.w & kReversed_z) != 0;
const int blurBorder = BLUR_BORDER;
const int2 validSrc = (int2) (srcRect.xy + srcRect.zw - 1);
// load moments into LDS
// each workgroup works on THREADS * THREADS tiles, but the blur filter requires
// us to fetch enough data around the border of the current tile.
// We assume that the blur filter's support does not exceed THREADS, so we fetch
// the data in 4 blocks.
const bool reverse_z = (dstRect.w & kReversed_z) != 0;
const int blurBorder = BLUR_BORDER;
const int2 validSrc = (int2) (srcRect.xy + srcRect.zw - 1);
int2 srcIdx = ((int2) dispatchId.xy) - blurBorder.xx + (int2) srcRect.xy;
int2 ldsIdx = (int2) groupThreadId.xy;
moment_t hblurredMoments[2];
int2 srcIdx = ((int2) dispatchId.xy) - blurBorder.xx + (int2) srcRect.xy;
int2 ldsIdx = (int2) groupThreadId.xy;
moment_t hblurredMoments[2];
UNITY_UNROLL
for( int ih = 0; ih < 2; ih++ )
{
UNITY_UNROLL
for( int iw = 0; iw < 2; iw++ )
{
if( ldsIdx.x < LDS_STRIDE )
{
UNITY_UNROLL
for( int ih = 0; ih < 2; ih++ )
{
UNITY_UNROLL
for( int iw = 0; iw < 2; iw++ )
{
if( ldsIdx.x < LDS_STRIDE )
{
moment_t avgMoments = 0.0;
UNITY_LOOP
for( uint is = 0; is < sampleCnt; is++ )
{
float depth = depthTex.Load( min( srcIdx, validSrc ), is ).x;
depth = reverse_z ? (1.0 - depth) : depth;
moment_t avgMoments = 0.0;
UNITY_LOOP
for( uint is = 0; is < sampleCnt; is++ )
{
float depth = depthTex.Load( min( srcIdx, validSrc ), is ).x;
depth = reverse_z ? (1.0 - depth) : depth;
// We're pancaking triangles to znear in the depth pass so depth and subsequently all moments can end up being zero.
// The solver ShadowMoments_SolveMSM then ends up calculating infinities and nands, which produces different results
// on different vendors' GPUs. So we're adding a small safety margin here.
depth = clamp( depth, 0.001, 0.999 );
// We're pancaking triangles to znear in the depth pass so depth and subsequently all moments can end up being zero.
// The solver ShadowMoments_SolveMSM then ends up calculating infinities and nands, which produces different results
// on different vendors' GPUs. So we're adding a small safety margin here.
depth = clamp( depth, 0.001, 0.999 );
avgMoments += sampleWeights[is] * DepthToMoments( depth );
}
avgMoments *= sumWeights;
avgMoments += sampleWeights[is] * DepthToMoments( depth );
}
avgMoments *= sumWeights;
writeToShared( avgMoments, int2( ldsIdx.x, groupThreadId.y ), LDS_STRIDE );
writeToShared( avgMoments, int2( ldsIdx.x, groupThreadId.y ), LDS_STRIDE );
float depth = depthTex.Load( int3( min( srcIdx, validSrc ), 0 ) ).x;
depth = reverse_z ? (1.0 - depth) : depth;
float depth = depthTex.Load( int3( min( srcIdx, validSrc ), 0 ) ).x;
depth = reverse_z ? (1.0 - depth) : depth;
// We're pancaking triangles to znear in the depth pass so depth and subsequently all moments can end up being zero.
// The solver ShadowMoments_SolveMSM then ends up calculating infinities and nands, which produces different results
// on different vendors' GPUs. So we're adding a small safety margin here.
depth = clamp( depth, 0.001, 0.999 );
// We're pancaking triangles to znear in the depth pass so depth and subsequently all moments can end up being zero.
// The solver ShadowMoments_SolveMSM then ends up calculating infinities and nands, which produces different results
// on different vendors' GPUs. So we're adding a small safety margin here.
depth = clamp( depth, 0.001, 0.999 );
writeToShared( DepthToMoments( depth ), int2( ldsIdx.x, groupThreadId.y ), LDS_STRIDE );
writeToShared( DepthToMoments( depth ), int2( ldsIdx.x, groupThreadId.y ), LDS_STRIDE );
ldsIdx.x += THREADS;
srcIdx.x += THREADS;
}
}
ldsIdx.x += THREADS;
srcIdx.x += THREADS;
}
}
GroupMemoryBarrierWithGroupSync();
GroupMemoryBarrierWithGroupSync();
hblurredMoments[ih] = 0;
int2 idx = { groupThreadId.x + blurBorder, groupThreadId.y };
UNITY_LOOP
for( int blurOffset = -blurBorder; blurOffset <= blurBorder; blurOffset++ )
{
hblurredMoments[ih] += readFromShared( int2( idx.x + blurOffset, idx.y ), LDS_STRIDE ) * blurWeights[abs( blurOffset )];
}
hblurredMoments[ih] = 0;
int2 idx = { groupThreadId.x + blurBorder, groupThreadId.y };
UNITY_LOOP
for( int blurOffset = -blurBorder; blurOffset <= blurBorder; blurOffset++ )
{
hblurredMoments[ih] += readFromShared( int2( idx.x + blurOffset, idx.y ), LDS_STRIDE ) * blurWeights[abs( blurOffset )];
}
GroupMemoryBarrierWithGroupSync();
GroupMemoryBarrierWithGroupSync();
ldsIdx.x = groupThreadId.x;
srcIdx.x = (int) dispatchId.x - blurBorder + srcRect.x;
srcIdx.y += THREADS;
}
ldsIdx.x = groupThreadId.x;
srcIdx.x = (int) dispatchId.x - blurBorder + srcRect.x;
srcIdx.y += THREADS;
}
// update LDS with horizontally blurred values
writeToShared( hblurredMoments[0], (int2) groupThreadId.xy, THREADS );
if( (groupThreadId.y + THREADS) < LDS_STRIDE )
writeToShared( hblurredMoments[1], int2( groupThreadId.x, groupThreadId.y + THREADS ), THREADS );
// update LDS with horizontally blurred values
writeToShared( hblurredMoments[0], (int2) groupThreadId.xy, THREADS );
if( (groupThreadId.y + THREADS) < LDS_STRIDE )
writeToShared( hblurredMoments[1], int2( groupThreadId.x, groupThreadId.y + THREADS ), THREADS );
// sync threads
GroupMemoryBarrierWithGroupSync();
// sync threads
GroupMemoryBarrierWithGroupSync();
// second pass blurs vertically
ldsIdx = (int2) groupThreadId.xy + int2( 0, blurBorder );
moment_t vblurredMoment = 0.0;
// second pass blurs vertically
ldsIdx = (int2) groupThreadId.xy + int2( 0, blurBorder );
moment_t vblurredMoment = 0.0;
UNITY_UNROLL
for( int blurOffset = -blurBorder; blurOffset <= blurBorder; blurOffset++ )
{
vblurredMoment += readFromShared( int2( ldsIdx.x, ldsIdx.y + blurOffset ), THREADS ) * blurWeights[abs(blurOffset)];
}
UNITY_UNROLL
for( int blurOffset = -blurBorder; blurOffset <= blurBorder; blurOffset++ )
{
vblurredMoment += readFromShared( int2( ldsIdx.x, ldsIdx.y + blurOffset ), THREADS ) * blurWeights[abs(blurOffset)];
}
// and write out the result
if( all( dispatchId.xy < srcRect.zw ) )
{
dispatchId.xy += dstRect.xy;
dispatchId.z = dstRect.z;
outputTex[dispatchId] = vblurredMoment;
}
// and write out the result
if( all( dispatchId.xy < srcRect.zw ) )
{
dispatchId.xy += dstRect.xy;
dispatchId.z = dstRect.z;
outputTex[dispatchId] = vblurredMoment;
}
}

181
com.unity.render-pipelines.core/CoreRP/Shadow/ShadowUtilities.cs


namespace UnityEngine.Experimental.Rendering
{
public class ShadowUtilsConstants

kCubeEdge_Count
};
public static readonly CubemapEdge[,] kCubemapEdgesPerFace = new CubemapEdge[6,4]
public static readonly CubemapEdge[,] kCubemapEdgesPerFace = new CubemapEdge[6, 4]
{
{ CubemapEdge.kCubeEdgePX_PY, CubemapEdge.kCubeEdgePX_NY, CubemapEdge.kCubeEdgePX_PZ, CubemapEdge.kCubeEdgePX_NZ }, // PX
{ CubemapEdge.kCubeEdgeNX_PY, CubemapEdge.kCubeEdgeNX_NY, CubemapEdge.kCubeEdgeNX_PZ, CubemapEdge.kCubeEdgeNX_NZ }, // NX

const float oneOverSqr2 = 0.70710678118654752440084436210485f;
public static readonly Vector3[] kCubemapEdgeDirections = new Vector3[(int)CubemapEdge.kCubeEdge_Count]
{
new Vector3( oneOverSqr2, oneOverSqr2, 0 ),
new Vector3( oneOverSqr2, -oneOverSqr2, 0 ),
new Vector3( oneOverSqr2, 0, oneOverSqr2 ),
new Vector3( oneOverSqr2, 0, -oneOverSqr2 ),
new Vector3(oneOverSqr2, oneOverSqr2, 0),
new Vector3(oneOverSqr2, -oneOverSqr2, 0),
new Vector3(oneOverSqr2, 0, oneOverSqr2),
new Vector3(oneOverSqr2, 0, -oneOverSqr2),
new Vector3( -oneOverSqr2, oneOverSqr2, 0 ),
new Vector3( -oneOverSqr2, -oneOverSqr2, 0 ),
new Vector3( -oneOverSqr2, 0, oneOverSqr2 ),
new Vector3( -oneOverSqr2, 0, -oneOverSqr2 ),
new Vector3(-oneOverSqr2, oneOverSqr2, 0),
new Vector3(-oneOverSqr2, -oneOverSqr2, 0),
new Vector3(-oneOverSqr2, 0, oneOverSqr2),
new Vector3(-oneOverSqr2, 0, -oneOverSqr2),
new Vector3( 0, oneOverSqr2, oneOverSqr2 ),
new Vector3( 0, oneOverSqr2, -oneOverSqr2 ),
new Vector3( 0, -oneOverSqr2, oneOverSqr2 ),
new Vector3( 0, -oneOverSqr2, -oneOverSqr2 )
new Vector3(0, oneOverSqr2, oneOverSqr2),
new Vector3(0, oneOverSqr2, -oneOverSqr2),
new Vector3(0, -oneOverSqr2, oneOverSqr2),
new Vector3(0, -oneOverSqr2, -oneOverSqr2)
};
// Cubemap faces with flipped z coordinate.

public static readonly Matrix4x4[] kCubemapFaces = new Matrix4x4[]
{
new Matrix4x4( // pos X
new Vector4( 0.0f, 0.0f, -1.0f, 0.0f ),
new Vector4( 0.0f, 1.0f, 0.0f, 0.0f ),
new Vector4( -1.0f, 0.0f, 0.0f, 0.0f ),
new Vector4( 0.0f, 0.0f, 0.0f, 1.0f ) ),
new Vector4(0.0f, 0.0f, -1.0f, 0.0f),
new Vector4(0.0f, 1.0f, 0.0f, 0.0f),
new Vector4(-1.0f, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, 0.0f, 1.0f)),
new Vector4( 0.0f, 0.0f, 1.0f, 0.0f ),
new Vector4( 0.0f, 1.0f, 0.0f, 0.0f ),
new Vector4( 1.0f, 0.0f, 0.0f, 0.0f ),
new Vector4( 0.0f, 0.0f, 0.0f, 1.0f ) ),
new Vector4(0.0f, 0.0f, 1.0f, 0.0f),
new Vector4(0.0f, 1.0f, 0.0f, 0.0f),
new Vector4(1.0f, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, 0.0f, 1.0f)),
new Vector4( 1.0f, 0.0f, 0.0f, 0.0f ),
new Vector4( 0.0f, 0.0f, -1.0f, 0.0f ),
new Vector4( 0.0f, -1.0f, 0.0f, 0.0f ),
new Vector4( 0.0f, 0.0f, 0.0f, 1.0f ) ),
new Vector4(1.0f, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, -1.0f, 0.0f),
new Vector4(0.0f, -1.0f, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, 0.0f, 1.0f)),
new Vector4( 1.0f, 0.0f, 0.0f, 0.0f ),
new Vector4( 0.0f, 0.0f, 1.0f, 0.0f ),
new Vector4( 0.0f, 1.0f, 0.0f, 0.0f ),
new Vector4( 0.0f, 0.0f, 0.0f, 1.0f ) ),
new Vector4(1.0f, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, 1.0f, 0.0f),
new Vector4(0.0f, 1.0f, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, 0.0f, 1.0f)),
new Vector4( 1.0f, 0.0f, 0.0f, 0.0f ),
new Vector4( 0.0f, 1.0f, 0.0f, 0.0f ),
new Vector4( 0.0f, 0.0f, -1.0f, 0.0f ),
new Vector4( 0.0f, 0.0f, 0.0f, 1.0f ) ),
new Vector4(1.0f, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, 1.0f, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, -1.0f, 0.0f),
new Vector4(0.0f, 0.0f, 0.0f, 1.0f)),
new Vector4( -1.0f, 0.0f, 0.0f, 0.0f ),
new Vector4( 0.0f, 1.0f, 0.0f, 0.0f ),
new Vector4( 0.0f, 0.0f, 1.0f, 0.0f ),
new Vector4( 0.0f, 0.0f, 0.0f, 1.0f ) )
new Vector4(-1.0f, 0.0f, 0.0f, 0.0f),
new Vector4(0.0f, 1.0f, 0.0f, 0.0f),
new Vector4(0.0f, 0.0f, 1.0f, 0.0f),
new Vector4(0.0f, 0.0f, 0.0f, 1.0f))
public static void InvertView( ref Matrix4x4 view, out Matrix4x4 invview )
public static void InvertView(ref Matrix4x4 view, out Matrix4x4 invview)
{
invview = Matrix4x4.zero;
invview.m00 = view.m00; invview.m01 = view.m10; invview.m02 = view.m20;

invview.m23 = -(invview.m20 * view.m03 + invview.m21 * view.m13 + invview.m22 * view.m23);
}
public static void InvertOrthographic( ref Matrix4x4 proj, ref Matrix4x4 view, out Matrix4x4 vpinv )
public static void InvertOrthographic(ref Matrix4x4 proj, ref Matrix4x4 view, out Matrix4x4 vpinv)
InvertView( ref view, out invview );
InvertView(ref view, out invview);
Matrix4x4 invproj = Matrix4x4.zero;
invproj.m00 = 1.0f / proj.m00;

invproj.m03 = proj.m03 * invproj.m00;
invproj.m13 = proj.m13 * invproj.m11;
invproj.m23 = - proj.m23 * invproj.m22;
invproj.m23 = -proj.m23 * invproj.m22;
public static void InvertPerspective( ref Matrix4x4 proj, ref Matrix4x4 view, out Matrix4x4 vpinv )
public static void InvertPerspective(ref Matrix4x4 proj, ref Matrix4x4 view, out Matrix4x4 vpinv)
{
Matrix4x4 invview;
InvertView(ref view, out invview);

vpinv = invview * invproj;
}
public static Matrix4x4 ExtractSpotLightMatrix( VisibleLight vl, float guardAngle, out Matrix4x4 view, out Matrix4x4 proj, out Matrix4x4 deviceProj, out Matrix4x4 vpinverse, out Vector4 lightDir, out ShadowSplitData splitData )
public static Matrix4x4 ExtractSpotLightMatrix(VisibleLight vl, float guardAngle, out Matrix4x4 view, out Matrix4x4 proj, out Matrix4x4 deviceProj, out Matrix4x4 vpinverse, out Vector4 lightDir, out ShadowSplitData splitData)
splitData.cullingSphere.Set( 0.0f, 0.0f, 0.0f, float.NegativeInfinity );
splitData.cullingSphere.Set(0.0f, 0.0f, 0.0f, float.NegativeInfinity);
splitData.cullingPlaneCount = 0;
// get lightDir
lightDir = vl.light.transform.forward;

float fov = vl.spotAngle + guardAngle;
proj = Matrix4x4.Perspective(fov, 1.0f, znear, zfar);
// and the compound (deviceProj will potentially inverse-Z)
deviceProj = GL.GetGPUProjectionMatrix( proj, false );
InvertPerspective( ref deviceProj, ref view, out vpinverse );
deviceProj = GL.GetGPUProjectionMatrix(proj, false);
InvertPerspective(ref deviceProj, ref view, out vpinverse);
public static Matrix4x4 ExtractPointLightMatrix( VisibleLight vl, uint faceIdx, float guardAngle, out Matrix4x4 view, out Matrix4x4 proj, out Matrix4x4 deviceProj, out Matrix4x4 vpinverse, out Vector4 lightDir, out ShadowSplitData splitData )
public static Matrix4x4 ExtractPointLightMatrix(VisibleLight vl, uint faceIdx, float guardAngle, out Matrix4x4 view, out Matrix4x4 proj, out Matrix4x4 deviceProj, out Matrix4x4 vpinverse, out Vector4 lightDir, out ShadowSplitData splitData)
if( faceIdx > (uint) CubemapFace.NegativeZ )
Debug.LogError( "Tried to extract cubemap face " + faceIdx + "." );
if (faceIdx > (uint)CubemapFace.NegativeZ)
Debug.LogError("Tried to extract cubemap face " + faceIdx + ".");
splitData.cullingSphere.Set( 0.0f, 0.0f, 0.0f, float.NegativeInfinity );
splitData.cullingSphere.Set(0.0f, 0.0f, 0.0f, float.NegativeInfinity);
splitData.cullingPlaneCount = 4;
// get lightDir
lightDir = vl.light.transform.forward;

Vector3 inverted_viewpos = ShadowUtilsConstants.kCubemapFaces[faceIdx].MultiplyPoint( -lpos );
view.SetColumn( 3, new Vector4( inverted_viewpos.x, inverted_viewpos.y, inverted_viewpos.z, 1.0f ) );
Vector3 inverted_viewpos = ShadowUtilsConstants.kCubemapFaces[faceIdx].MultiplyPoint(-lpos);
view.SetColumn(3, new Vector4(inverted_viewpos.x, inverted_viewpos.y, inverted_viewpos.z, 1.0f));
for( int i = 0; i < 4; ++i )
for (int i = 0; i < 4; ++i)
ShadowUtilsConstants.CubemapEdge cubemapEdge = ShadowUtilsConstants.kCubemapEdgesPerFace[faceIdx,i];
ShadowUtilsConstants.CubemapEdge cubemapEdge = ShadowUtilsConstants.kCubemapEdgesPerFace[faceIdx, i];
splitData.SetCullingPlane( i, new Plane( cullingPlaneDirection, lpos ) );
splitData.SetCullingPlane(i, new Plane(cullingPlaneDirection, lpos));
}
// following code is from SharedLightData::GetNearPlaneMinBound
float percentageBound = 0.01f * vl.light.range;

float farPlane = vl.range;
float nearPlane = vl.light.shadowNearPlane >= nearmin ? vl.light.shadowNearPlane : nearmin;
proj = Matrix4x4.Perspective( 90.0f + guardAngle, 1.0f, nearPlane, farPlane );
proj = Matrix4x4.Perspective(90.0f + guardAngle, 1.0f, nearPlane, farPlane);
deviceProj = GL.GetGPUProjectionMatrix( proj, false );
InvertPerspective( ref deviceProj, ref view, out vpinverse );
deviceProj = GL.GetGPUProjectionMatrix(proj, false);
InvertPerspective(ref deviceProj, ref view, out vpinverse);
public static Matrix4x4 ExtractDirectionalLightMatrix( VisibleLight vl, uint cascadeIdx, int cascadeCount, float[] splitRatio, float nearPlaneOffset, uint width, uint height, out Matrix4x4 view, out Matrix4x4 proj, out Matrix4x4 deviceProj, out Matrix4x4 vpinverse, out Vector4 lightDir, out ShadowSplitData splitData, CullResults cullResults, int lightIndex )
public static Matrix4x4 ExtractDirectionalLightMatrix(VisibleLight vl, uint cascadeIdx, int cascadeCount, float[] splitRatio, float nearPlaneOffset, uint width, uint height, out Matrix4x4 view, out Matrix4x4 proj, out Matrix4x4 deviceProj, out Matrix4x4 vpinverse, out Vector4 lightDir, out ShadowSplitData splitData, CullResults cullResults, int lightIndex)
Debug.Assert( width == height, "Currently the cascaded shadow mapping code requires square cascades." );
Debug.Assert(width == height, "Currently the cascaded shadow mapping code requires square cascades.");
splitData = new ShadowSplitData();
splitData.cullingSphere.Set(0.0f, 0.0f, 0.0f, float.NegativeInfinity);
splitData.cullingPlaneCount = 0;

// For directional lights shadow data is extracted from the cullResults, so that needs to be somehow provided here.
// Check ScriptableShadowsUtility.cpp ComputeDirectionalShadowMatricesAndCullingPrimitives(...) for details.
Vector3 ratios = new Vector3();
for( int i = 0, cnt = splitRatio.Length < 3 ? splitRatio.Length : 3; i < cnt; i++ )
for (int i = 0, cnt = splitRatio.Length < 3 ? splitRatio.Length : 3; i < cnt; i++)
cullResults.ComputeDirectionalShadowMatricesAndCullingPrimitives( lightIndex, (int) cascadeIdx, cascadeCount, ratios, (int) width, nearPlaneOffset, out view, out proj, out splitData );
cullResults.ComputeDirectionalShadowMatricesAndCullingPrimitives(lightIndex, (int)cascadeIdx, cascadeCount, ratios, (int)width, nearPlaneOffset, out view, out proj, out splitData);
deviceProj = GL.GetGPUProjectionMatrix( proj, false );
InvertOrthographic( ref deviceProj, ref view, out vpinverse );
deviceProj = GL.GetGPUProjectionMatrix(proj, false);
InvertOrthographic(ref deviceProj, ref view, out vpinverse);
public static float CalcGuardAnglePerspective( float angleInDeg, float resolution, float filterWidth, float normalBiasMax, float guardAngleMaxInDeg )
public static float CalcGuardAnglePerspective(float angleInDeg, float resolution, float filterWidth, float normalBiasMax, float guardAngleMaxInDeg)
float texelSize = Mathf.Cos( angleInRad ) * res;
float texelSize = Mathf.Cos(angleInRad) * res;
float guardAngle = Mathf.Atan( beta );
texelSize = Mathf.Tan( angleInRad + guardAngle ) * res;
guardAngle = Mathf.Atan( (resolution + Mathf.Ceil( filterWidth )) * texelSize * 0.5f ) * 2.0f * Mathf.Rad2Deg - angleInDeg;
guardAngle *= 2.0f;
float guardAngle = Mathf.Atan(beta);
texelSize = Mathf.Tan(angleInRad + guardAngle) * res;
guardAngle = Mathf.Atan((resolution + Mathf.Ceil(filterWidth)) * texelSize * 0.5f) * 2.0f * Mathf.Rad2Deg - angleInDeg;
guardAngle *= 2.0f;
public static GPUShadowAlgorithm Pack( ShadowAlgorithm algo, ShadowVariant vari, ShadowPrecision prec )
public static GPUShadowAlgorithm Pack(ShadowAlgorithm algo, ShadowVariant vari, ShadowPrecision prec)
return (GPUShadowAlgorithm) ( (int) prec << precshift | ((int) algo << algoshift) | (int)vari);
return (GPUShadowAlgorithm)((int)prec << precshift | ((int)algo << algoshift) | (int)vari);
public static ShadowAlgorithm ExtractAlgorithm( GPUShadowAlgorithm gpuAlgo ) { return (ShadowAlgorithm) ( ShadowConstants.Masks.k_ShadowAlgorithm & ((int)gpuAlgo >> ShadowConstants.Bits.k_ShadowVariant) ); }
public static ShadowVariant ExtractVariant( GPUShadowAlgorithm gpuAlgo ) { return (ShadowVariant ) ( ShadowConstants.Masks.k_ShadowVariant & (int)gpuAlgo ); }
public static ShadowPrecision ExtractPrecision( GPUShadowAlgorithm gpuAlgo ) { return (ShadowPrecision) ( ShadowConstants.Masks.k_ShadowPrecision & ((int)gpuAlgo >> (ShadowConstants.Bits.k_ShadowVariant + ShadowConstants.Bits.k_ShadowAlgorithm)) ); }
public static void Unpack( GPUShadowAlgorithm gpuAlgo, out ShadowAlgorithm algo, out ShadowVariant vari, out ShadowPrecision prec )
public static ShadowAlgorithm ExtractAlgorithm(GPUShadowAlgorithm gpuAlgo) { return (ShadowAlgorithm)(ShadowConstants.Masks.k_ShadowAlgorithm & ((int)gpuAlgo >> ShadowConstants.Bits.k_ShadowVariant)); }
public static ShadowVariant ExtractVariant(GPUShadowAlgorithm gpuAlgo) { return (ShadowVariant)(ShadowConstants.Masks.k_ShadowVariant & (int)gpuAlgo); }
public static ShadowPrecision ExtractPrecision(GPUShadowAlgorithm gpuAlgo) { return (ShadowPrecision)(ShadowConstants.Masks.k_ShadowPrecision & ((int)gpuAlgo >> (ShadowConstants.Bits.k_ShadowVariant + ShadowConstants.Bits.k_ShadowAlgorithm))); }
public static void Unpack(GPUShadowAlgorithm gpuAlgo, out ShadowAlgorithm algo, out ShadowVariant vari, out ShadowPrecision prec)
algo = ExtractAlgorithm( gpuAlgo );
vari = ExtractVariant( gpuAlgo );
prec = ExtractPrecision( gpuAlgo );
algo = ExtractAlgorithm(gpuAlgo);
vari = ExtractVariant(gpuAlgo);
prec = ExtractPrecision(gpuAlgo);
public static GPUShadowAlgorithm ClearPrecision( GPUShadowAlgorithm gpuAlgo )
public static GPUShadowAlgorithm ClearPrecision(GPUShadowAlgorithm gpuAlgo)
var algo = ExtractAlgorithm( gpuAlgo );
var vari = ExtractVariant( gpuAlgo );
return Pack( algo, vari, ShadowPrecision.Low );
var algo = ExtractAlgorithm(gpuAlgo);
var vari = ExtractVariant(gpuAlgo);
return Pack(algo, vari, ShadowPrecision.Low);
public static float Asfloat( uint val ) { unsafe { return *((float*)&val); } }
public static float Asfloat( int val ) { unsafe { return *((float*)&val); } }
public static int Asint( float val ) { unsafe { return *((int*)&val); } }
public static uint Asuint( float val ) { unsafe { return *((uint*)&val); } }
public static float Asfloat(uint val) { unsafe { return *((float*)&val); } }
public static float Asfloat(int val) { unsafe { return *((float*)&val); } }
public static int Asint(float val) { unsafe { return *((int*)&val); } }
public static uint Asuint(float val) { unsafe { return *((uint*)&val); } }
}
} // end of namespace UnityEngine.Experimental.ScriptableRenderLoop

53
com.unity.render-pipelines.core/CoreRP/Shadow/VectorArray.cs


}
// Add obj and reallocate if necessary. Returns the index where the object was added.
public uint Add( T obj )
public uint Add(T obj)
{
Reserve(1);
uint idx = m_count;

}
// Adds the object if it does not exist in the container, yet
public uint AddUnique( T obj )
public uint AddUnique(T obj)
Reserve( 1 );
return AddUniqueUnchecked( obj );
Reserve(1);
return AddUniqueUnchecked(obj);
public uint AddUnique( T[] objs, uint count )
public uint AddUnique(T[] objs, uint count)
Reserve( count );
return AddUniqueUnchecked( objs, count );
Reserve(count);
return AddUniqueUnchecked(objs, count);
public uint AddUnique( ref VectorArray<T> vec )
public uint AddUnique(ref VectorArray<T> vec)
Reserve( vec.Count() );
return AddUniqueUnchecked( ref vec );
Reserve(vec.Count());
return AddUniqueUnchecked(ref vec);
public uint AddUnchecked( T obj )
public uint AddUnchecked(T obj)
{
uint idx = m_count;
this[idx] = obj;

}
// Adds the object if it does not exist in the container, yet
public uint AddUniqueUnchecked( T obj )
public uint AddUniqueUnchecked(T obj)
if( !Contains( obj ) )
return Add( obj );
if (!Contains(obj))
return Add(obj);
public uint AddUniqueUnchecked( T[] objs, uint count )
public uint AddUniqueUnchecked(T[] objs, uint count)
for( uint i = 0; i < count; ++i )
for (uint i = 0; i < count; ++i)
uint tmp = AddUniqueUnchecked( objs[i] );
uint tmp = AddUniqueUnchecked(objs[i]);
public uint AddUniqueUnchecked( ref VectorArray<T> vec )
public uint AddUniqueUnchecked(ref VectorArray<T> vec)
for( uint i = 0, cnt = vec.Count(); i < cnt; ++i )
for (uint i = 0, cnt = vec.Count(); i < cnt; ++i)
uint tmp = AddUniqueUnchecked( vec[i] );
uint tmp = AddUniqueUnchecked(vec[i]);
// Purge count number of elements from the end of the array.
public void Purge(uint count)

// Sort according to some comparer
public void Sort(System.Collections.Generic.IComparer<T> comparer)
{
Debug.Assert(m_count <= int.MaxValue && m_offset <= int.MaxValue);
Array.Sort(m_array, (int)m_offset, (int)m_count, comparer);
}

idx = k_InvalidIdx;
return false;
}
public bool Contains( T designator )
public bool Contains(T designator)
return FindFirst( out idx, ref designator );
return FindFirst(out idx, ref designator);
public bool Contains<U>( U designator, Comparator<U> compareDelegate )
public bool Contains<U>(U designator, Comparator<U> compareDelegate)
return FindFirst( out idx, ref designator, compareDelegate );
return FindFirst(out idx, ref designator, compareDelegate);
// Returns a vector representing a subrange. Contents are shared, not duplicated.
public VectorArray<T> Subrange(uint offset, uint count)
{

22
com.unity.render-pipelines.core/CoreRP/Textures/BufferedRTHandleSystem.cs


using System;
using System;
using System.Collections.Generic;
using UnityEngine.Assertions;
using UnityEngine.Rendering;

/// enum BufferType
/// {
/// Color,
/// Depth
/// Depth
///
///
///
///
/// GetCameraWidth(camera), GetCameraHeight(camera),
/// GetCameraWidth(camera), GetCameraHeight(camera),
///
///
/// var currentColor = buffer.GetFrameRT((int)BufferType.Color, 0);
/// if (currentColor == null) // Buffer was not allocated
/// {

/// );
/// currentColor = buffer.GetFrameRT((int)BufferType.Color, 0);
/// }
///
///
///
///
/// // Use previousColor and write into currentColor
/// }
/// </code>

/// <param name="allocator">The functor to use for allocation.</param>
/// <param name="bufferCount">The number of RT handles for this buffer.</param>
public void AllocBuffer(
int bufferId,
int bufferId,
)
)
{
var buffer = new RTHandleSystem.RTHandle[bufferCount];
m_RTHandles.Add(bufferId, buffer);

/// <summary>
/// Swap the buffers.
///
///
/// Take care that if the new current frame needs resizing, it will occurs during the this call.
/// </summary>
public void Swap()

2
com.unity.render-pipelines.core/CoreRP/Textures/DepthBits.cs


using System.Collections.Generic;
using System.Collections.Generic;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering

12
com.unity.render-pipelines.core/CoreRP/Textures/EncodeBC6H.cs


using UnityEngine.Assertions;
using UnityEngine.Assertions;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering

// Only use mode11 of BC6H encoding
/// <summary>
/// Encode a Cubemap in BC6H.
///
///
///
///
/// It uses only mode 11 of BC6H.
/// </summary>
/// <param name="cmb">Command buffer for execution</param>

/// <param name="fromMip">Starting mip to encode</param>
/// <param name="toMip">Last mip to encode</param>
/// <param name="targetArrayIndex">The index of the cubemap to store the compressed texture.
///
///
/// Only relevant when target is a CubemapArray</param>
public void EncodeFastCubemap(CommandBuffer cmb, RenderTargetIdentifier source, int sourceSize, RenderTargetIdentifier target, int fromMip, int toMip, int targetArrayIndex = 0)
{

useMipMap = false,
};
cmb.SetComputeTextureParam(m_Shader, m_KEncodeFastCubemapMip, _Source, source);
cmb.SetComputeTextureParam(m_Shader, m_KEncodeFastCubemapMip, _Source, source);
for (var mip = actualFromMip; mip <= actualToMip; ++mip)
{

EncodeBC6H.DefaultInstance.EncodeFastCubemap(cmb, source, sourceSize, target, fromMip, toMip, targetArrayIndex);
}
}
}
}

部分文件因为文件数量过多而无法显示

正在加载...
取消
保存