浏览代码

Merge branch 'master' of https://github.com/Unity-Technologies/ScriptableRenderLoop into feature/realtimeCubemap

/Add-support-for-light-specular-color-tint
Julien Ignace 7 年前
当前提交
11c1d9a8
共有 701 个文件被更改,包括 3028 次插入1402 次删除
  1. 1
      .npmignore
  2. 32
      README.md
  3. 27
      SampleScenes/FPTL/FPTL.unity
  4. 20
      SampleScenes/FPTL/Materials/FwdMat.mat
  5. 10
      SampleScenes/HDTest/GraphicTest/Common/CustomTexture/DistortionMap.shader
  6. 9
      SampleScenes/HDTest/GraphicTest/SSS/Materials/SSSHead.mat
  7. 13
      SampleScenes/HDTest/GraphicTest/Two Sided/Material/GroundLeaf_DoubleSided.mat
  8. 11
      SampleScenes/HDTest/GraphicTest/Two Sided/Material/GroundLeaf_DoubleSidedFlipSSS.mat
  9. 11
      SampleScenes/HDTest/GraphicTest/Unlit/Material/TestUnlit Mask.mat
  10. 9
      SampleScenes/HDTest/GraphicTest/Unlit/Material/TestUnlit Transparent.mat
  11. 7
      SampleScenes/HDTest/GraphicTest/Unlit/Material/TestUnlit.mat
  12. 803
      SampleScenes/HDTest/LayeredLitTest.unity
  13. 24
      ScriptableRenderPipeline/Core/CoreUtils.cs
  14. 3
      ScriptableRenderPipeline/Core/ShaderLibrary/API/PSSL.hlsl
  15. 26
      ScriptableRenderPipeline/Core/ShaderLibrary/Common.hlsl
  16. 6
      ScriptableRenderPipeline/Core/ShaderLibrary/CommonLighting.hlsl
  17. 27
      ScriptableRenderPipeline/Core/ShaderLibrary/CommonMaterial.hlsl
  18. 22
      ScriptableRenderPipeline/Core/ShaderLibrary/EntityLighting.hlsl
  19. 6
      ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/Resources/ShadowBlurMoments.compute
  20. 7
      ScriptableRenderPipeline/Core/ShaderLibrary/VolumeRendering.hlsl
  21. 2
      ScriptableRenderPipeline/Core/Shadow/Resources/DebugDisplayShadowMap.shader
  22. 7
      ScriptableRenderPipeline/Core/Shadow/Shadow.cs
  23. 13
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs
  24. 22
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs.hlsl
  25. 2
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayLatlong.shader
  26. 2
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugFullScreen.shader
  27. 34
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewMaterialGBuffer.shader
  28. 2
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewTiles.shader
  29. 88
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs
  30. 209
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  31. 13
      ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs
  32. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDUtils.cs
  33. 25
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Deferred.shader
  34. 18
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs
  35. 37
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs.hlsl
  36. 119
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/Deferred.compute
  37. 502
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  38. 19
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs.hlsl
  39. 18
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.hlsl
  40. 151
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePassLoop.hlsl
  41. 21
      ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs
  42. 32
      ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs.hlsl
  43. 25
      ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.hlsl
  44. 51
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader
  45. 54
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader
  46. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs
  47. 40
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs
  48. 21
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs
  49. 678
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  50. 52
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader
  51. 17
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl
  52. 10
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataIndividualLayer.hlsl
  53. 6
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitProperties.hlsl
  54. 8
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitReference.hlsl
  55. 52
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader
  56. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CombineLighting.shader
  57. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CopyStencilBuffer.shader
  58. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/PreIntegratedFGD.shader
  59. 106
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.compute
  60. 16
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.shader
  61. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitSharePass.hlsl
  62. 100
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs
  63. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs.hlsl
  64. 125
      ScriptableRenderPipeline/HDRenderPipeline/Material/Material.hlsl
  65. 28
      ScriptableRenderPipeline/HDRenderPipeline/Material/MaterialUtilities.hlsl
  66. 28
      ScriptableRenderPipeline/HDRenderPipeline/Material/RenderPipelineMaterial.cs
  67. 27
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/BaseUnlitUI.cs
  68. 5
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/UnlitUI.cs
  69. 6
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/ShaderPass/UnlitSharePass.hlsl
  70. 16
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.shader
  71. 15
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/UnlitData.hlsl
  72. 8
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/UnlitProperties.hlsl
  73. 2
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader
  74. 4
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader
  75. 15
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassForward.hlsl
  76. 2
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassGBuffer.hlsl
  77. 24
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl
  78. 16
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariables.hlsl
  79. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/BlacksmithlSky/Resources/SkyBlacksmith.shader
  80. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/GGXConvolve.shader
  81. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Resources/SkyHDRI.shader
  82. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/OpaqueAtmosphericScattering.shader
  83. 2
      ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/Resources/ProceduralSky.shader
  84. 2
      TestbedPipelines/Fptl/FPTLRenderPipeline.asset
  85. 39
      TestbedPipelines/Fptl/FptlLighting.cs
  86. 8
      TestbedPipelines/Fptl/RegularForwardLightingUtils.hlsl
  87. 5
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes.meta
  88. 5
      package.json
  89. 17
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/BlackRGBA64x64.tga.meta
  90. 17
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/MidGreyRGBA64x64.tga.meta
  91. 17
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/WhiteRGBA64x64.tga.meta
  92. 17
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/Black-WhiteRGBA64x64.tga.meta
  93. 8
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/HDRI/KirbyCoveWhiteBalancedNoSun.exr.meta
  94. 14
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/uvGrid.tga.meta
  95. 20
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/HDRP_Test_Camera.prefab
  96. 20
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Materials/HDRP_Default_Material.mat
  97. 10
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials.meta
  98. 241
      SampleScenes/HDTest/LayeredLitTest/Material/Lit_UVChart_Planar_Detail.mat

1
.npmignore


/SampleScenes*
/TestbedPipelines*
/Tests*
/ScriptableRenderPipeline/HDRenderPipeline*
/.collabignore
/.gitignore
/.gitmodules

32
README.md


new modern built-in rendering pipeline with it. For now you can look around if you're _really_ curious, but like said above, this is
not useful for any public Unity version yet.
There's a more detailed overview document here: [ScriptableRenderLoop google doc](https://docs.google.com/document/d/1e2jkr_-v5iaZRuHdnMrSv978LuJKYZhsIYnrDkNAuvQ/edit?usp=sharing)
There's a more detailed overview document here: [ScriptableRenderPipeline google doc](https://docs.google.com/document/d/1e2jkr_-v5iaZRuHdnMrSv978LuJKYZhsIYnrDkNAuvQ/edit?usp=sharing)
Did we mention it's a very WIP, no promises, may or might not ship feature, anything and everything in it can change? It totally is.

Perform the following instructions to get a working copy of SRP:
```
> cd <Path to your Unity project>/Assets
> git clone https://github.com/Unity-Technologies/ScriptableRenderLoop
> cd ScriptableRenderLoop
> git clone https://github.com/Unity-Technologies/ScriptableRenderPipeline
> cd ScriptableRenderPipeline
## For Unity 2017.1 beta users
## For Unity above 2017.1 beta users
> git clone https://github.com/Unity-Technologies/ScriptableRenderLoop
> cd ScriptableRenderLoop
> git clone https://github.com/Unity-Technologies/ScriptableRenderPipeline
> cd ScriptableRenderPipeline
## For HDRenderPipeline:
1. Download Unity version compatible with Github release (https://github.com/Unity-Technologies/ScriptableRenderPipeline/releases)
2. Launch
3. Create a new Unity project
4. Set `Color Space` to `Linear` in Player settings, Set Antialiasing to disable in Quality settings for all configuration (Fantastic and High), Set Anisotropic Textures to "Per Textures"
5. Close Unity
6. Execute the following commands (or use GitHub interface (ask us)):
```
> cd <Path to your Unity project>/Assets
> git clone https://github.com/Unity-Technologies/ScriptableRenderPipeline
> cd ScriptableRenderPipeline
> git submodule update --init --recursive --remote (This is to get the PostProcessing folder)
```
7. Re-open the project
8. In Graphic Settings, for render pipeline, setup the HDRenderPipelineAsset
Advice: It is recommended to make a copy of HDRenderPipelineAsset outside of the ScriptableRenderPipeline, so settings are not lost when merging. And setup this new created HDRenderPipelineAsset in GraphicSettings
## For Unity 5.6 beta users

27
SampleScenes/FPTL/FPTL.unity


m_EnableBakedLightmaps: 0
m_EnableRealtimeLightmaps: 0
m_LightmapEditorSettings:
serializedVersion: 9
serializedVersion: 10
m_TextureWidth: 1024
m_TextureHeight: 1024
m_AtlasSize: 1024
m_AO: 0
m_AOMaxDistance: 1
m_CompAOExponent: 0

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1713034008}
m_Enabled: 1
m_ExtensionPropertyValues: []
--- !u!124 &1713034010
Behaviour:
m_ObjectHideFlags: 0

m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
m_StereoMirrorMode: 0
--- !u!4 &1713034013
Transform:
m_ObjectHideFlags: 0

m_Script: {fileID: 11500000, guid: 92bb16b4ee20841929b24d6bd771738d, type: 3}
m_Name:
m_EditorClassIdentifier:
m_RenderLoop: {fileID: 11400000, guid: 4dc14083116279a438e1b2de3830999f, type: 2}
--- !u!114 &1713034015
MonoBehaviour:
m_ObjectHideFlags: 0

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
- {fileID: 2100000, guid: cb6536d04ba24874981eb01dfd87479e, type: 2}
- {fileID: 2100000, guid: 24e6a15bf9d2c0944b380d860a738528, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
- {fileID: 2100000, guid: cb6536d04ba24874981eb01dfd87479e, type: 2}
- {fileID: 2100000, guid: 24e6a15bf9d2c0944b380d860a738528, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1

m_CastShadows: 1
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_RenderingLayerMask: 4294967295
- {fileID: 2100000, guid: cb6536d04ba24874981eb01dfd87479e, type: 2}
- {fileID: 2100000, guid: 24e6a15bf9d2c0944b380d860a738528, type: 2}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0

20
SampleScenes/FPTL/Materials/FwdMat.mat


m_PrefabInternal: {fileID: 0}
m_Name: FwdMat
m_Shader: {fileID: 4800000, guid: 8f28d6dbfdba66d4dbae80224aca5669, type: 3}
m_ShaderKeywords: _EMISSION
m_ShaderKeywords: _ALPHAPREMULTIPLY_ON _EMISSION
m_CustomRenderQueue: -1
stringTagMap: {}
m_DoubleSidedGI: 0
m_CustomRenderQueue: 3000
stringTagMap:
RenderType: Transparent
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3

- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _DstBlend: 10
- _Glossiness: 0.5
- _Glossiness: 0.806
- _Metallic: 0
- _Mode: 0
- _Metallic: 0.891
- _Mode: 3
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0

- _ZWrite: 1
- _ZWrite: 0
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _Color: {r: 1, g: 1, b: 1, a: 0.559}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}

10
SampleScenes/HDTest/GraphicTest/Common/CustomTexture/DistortionMap.shader


Shader "Hidden/HDRenderPipeline/Test/DistortionMap"{
Shader "Hidden/HDRenderPipeline/Test/DistortionMap"{
Properties
{
_Size("Size", Float) = 1

float2 distortion = s.xy * _DistortionAmplitude;
float blur = s.z;
return float4(distortion, blur, 1.0);
return float4(distortion * 0.5 + 0.5, blur, 1.0);
}
ENDCG
}

float blur = (min(t, 1-t) * 2);
return float4(distortion, blur, 1.0);
return float4(distortion * 0.5 + 0.5, blur, 1.0);
}
ENDCG
}

float blur = v;
return float4(distortion, blur, 1.0);
return float4(distortion * 0.5 + 0.5, blur, 1.0);
}
}

9
SampleScenes/HDTest/GraphicTest/SSS/Materials/SSSHead.mat


m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Texture: {fileID: 2800000, guid: 6e9f830fee2ef0c44af529384a948910, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MaskMap:

m_Offset: {x: 0, y: 0}
- _ThicknessMap:
m_Texture: {fileID: 2800000, guid: 13ef23776cd487941973bab55623a077, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TransmittanceColorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:

- _SrcBlend: 1
- _StencilRef: 1
- _Stiffness: 1
- _SubsurfaceProfile: 0
- _SubsurfaceProfile: 1
- _SubsurfaceRadius: 1
- _SurfaceType: 0
- _TexWorldScale: 1

- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _InvPrimScale: {r: 1, g: 1, b: 0, a: 0}
- _SpecularColor: {r: 1, g: 1, b: 1, a: 1}
- _ThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
- _TransmittanceColor: {r: 1, g: 1, b: 1, a: 1}
- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}

13
SampleScenes/HDTest/GraphicTest/Two Sided/Material/GroundLeaf_DoubleSided.mat


m_ShaderKeywords: _ALPHATEST_ON _DOUBLESIDED_ON
m_LightmapFlags: 1
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_DoubleSidedGI: 1
m_CustomRenderQueue: 2450
stringTagMap:
RenderType: TransparentCutout

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: 00447c5eeb984f54d92c80818840a36b, type: 3}
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MaskMap:

m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _UnlitColorMap:
m_Texture: {fileID: 2800000, guid: 00447c5eeb984f54d92c80818840a36b, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AlphaCutoff: 0.5
- _AlphaCutoffEnable: 1

- _ZWrite: 1
m_Colors:
- _BaseColor: {r: 1, g: 1, b: 1, a: 1}
- _Color: {r: 0.5882353, g: 0.5882353, b: 0.5882353, a: 1}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissiveColor: {r: 1, g: 1, b: 1, a: 1}
- _UnlitColor: {r: 1, g: 1, b: 1, a: 1}

11
SampleScenes/HDTest/GraphicTest/Two Sided/Material/GroundLeaf_DoubleSidedFlipSSS.mat


_MASKMAP _MATID_SSS _NORMALMAP _NORMALMAP_TANGENT_SPACE
m_LightmapFlags: 1
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_DoubleSidedGI: 1
m_CustomRenderQueue: 2450
stringTagMap:
RenderType: TransparentCutout

m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ThicknessMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TransmittanceColorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}

- _SrcBlend: 1
- _StencilRef: 1
- _Stiffness: 1
- _SubsurfaceProfile: 1
- _SubsurfaceProfile: 2
- _SubsurfaceRadius: 1
- _SurfaceType: 0
- _TessellationBackFaceCullEpsilon: -0.375

- _ZWrite: 1
m_Colors:
- _BaseColor: {r: 1, g: 1, b: 1, a: 1}
- _Color: {r: 0.5882353, g: 0.5882353, b: 0.5882353, a: 1}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _ThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
- _TransmittanceColor: {r: 1, g: 1, b: 1, a: 1}
- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}

11
SampleScenes/HDTest/GraphicTest/Unlit/Material/TestUnlit Mask.mat


m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _UnlitColorMap:
m_Texture: {fileID: 2800000, guid: 46531a9b9b2461347a4d5a0f75c33766, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AlphaCutoff: 0.4
- _AlphaCutoffEnable: 1

- _Cutoff: 0.5
- _Cutoff: 0.4
- _DetailNormalMapScale: 1
- _DistortionBlendMode: 0
- _DistortionBlurBlendMode: 0

- _ZTestMode: 8
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 0.559}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissiveColor: {r: 1, g: 1, b: 1, a: 1}
- _UnlitColor: {r: 1, g: 1, b: 1, a: 1}

9
SampleScenes/HDTest/GraphicTest/Unlit/Material/TestUnlit Transparent.mat


m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _UnlitColorMap:
m_Texture: {fileID: 2800000, guid: eb22c3aedea15d246959bf77d8f9e766, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AlphaCutoff: 0.5
- _AlphaCutoffEnable: 0

- _ZTestMode: 8
- _ZWrite: 0
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 0.341}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissiveColor: {r: 1, g: 1, b: 1, a: 1}
- _UnlitColor: {r: 1, g: 1, b: 1, a: 0.359}

7
SampleScenes/HDTest/GraphicTest/Unlit/Material/TestUnlit.mat


m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _UnlitColorMap:
m_Texture: {fileID: 2800000, guid: eb22c3aedea15d246959bf77d8f9e766, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AlphaCutoff: 0.5
- _AlphaCutoffEnable: 0

m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissiveColor: {r: 1, g: 1, b: 1, a: 1}
- _UnlitColor: {r: 1, g: 1, b: 1, a: 1}

803
SampleScenes/HDTest/LayeredLitTest.unity
文件差异内容过多而无法显示
查看文件

24
ScriptableRenderPipeline/Core/CoreUtils.cs


public static class CoreUtils
{
// Note: Color.Black have alpha channel set to 1. Most of the time we want alpha channel set to 0 as we use black to clear render target
public static Color clearColorAllBlack { get { return new Color(0f, 0f, 0f, 0f); } }
// Render Target Management.
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier buffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)
{

public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier buffer, ClearFlag clearFlag = ClearFlag.None, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)
{
SetRenderTarget(cmd, buffer, clearFlag, Color.black, miplevel, cubemapFace);
SetRenderTarget(cmd, buffer, clearFlag, clearColorAllBlack, miplevel, cubemapFace);
SetRenderTarget(cmd, colorBuffer, depthBuffer, ClearFlag.None, Color.black, miplevel, cubemapFace);
SetRenderTarget(cmd, colorBuffer, depthBuffer, ClearFlag.None, clearColorAllBlack, miplevel, cubemapFace);
SetRenderTarget(cmd, colorBuffer, depthBuffer, clearFlag, Color.black, miplevel, cubemapFace);
SetRenderTarget(cmd, colorBuffer, depthBuffer, clearFlag, clearColorAllBlack, miplevel, cubemapFace);
}
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)

public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthBuffer)
{
SetRenderTarget(cmd, colorBuffers, depthBuffer, ClearFlag.None, Color.black);
SetRenderTarget(cmd, colorBuffers, depthBuffer, ClearFlag.None, clearColorAllBlack);
SetRenderTarget(cmd, colorBuffers, depthBuffer, clearFlag, Color.black);
SetRenderTarget(cmd, colorBuffers, depthBuffer, clearFlag, clearColorAllBlack);
}
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier[] colorBuffers, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, Color clearColor)

public static void ClearCubemap(CommandBuffer cmd, RenderTargetIdentifier buffer, Color clearColor)
{
for(int i = 0; i < 6; ++i)
SetRenderTarget(cmd, buffer, ClearFlag.Color, Color.black, 0, (CubemapFace)i);
SetRenderTarget(cmd, buffer, ClearFlag.Color, clearColorAllBlack, 0, (CubemapFace)i);
}
// Draws a full screen triangle as a faster alternative to drawing a full screen quad.

return mat;
}
public static void SetKeyword(CommandBuffer cmd, string keyword, bool state)
{
if (state)
cmd.EnableShaderKeyword(keyword);
else
cmd.DisableShaderKeyword(keyword);
}
// Caution: such a call should not be use interlaced with command buffer command, as it is immediate
public static void SetKeyword(Material m, string keyword, bool state)
{
if (state)

3
ScriptableRenderPipeline/Core/ShaderLibrary/API/PSSL.hlsl


// This file assume SHADER_API_D3D11 is defined
#define INTRINSIC_BITFIELD_EXTRACT
#define INTRINSIC_WAVEREADFIRSTLANE
#define WaveReadFirstLane ReadFirstLane
#define INTRINSIC_MED3
#define INTRINSIC_MINMAX3
#define Min3 min3
#define Max3 max3

26
ScriptableRenderPipeline/Core/ShaderLibrary/Common.hlsl


#include "API/D3D11_1.hlsl"
#elif defined(SHADER_API_METAL)
#include "API/Metal.hlsl"
#elif defined(SHADER_API_VULKAN)
#include "API/Vulkan.hlsl"
#else
#error unsupported shader api
#endif

return BitFieldExtract(data, 1u, bitPos) != 0;
}
#ifndef INTRINSIC_CLAMP
// TODO: should we force all clamp to be intrinsic by default ?
// Some platform have one instruction clamp
#define Clamp clamp
#endif // INTRINSIC_CLAMP
#ifndef INTRINSIC_WAVEREADFIRSTLANE
// Warning: for correctness, the value you pass to the function must be constant across the wave!
uint WaveReadFirstLane(uint scalarValue)
{
return scalarValue;
}
#endif
#ifndef INTRINSIC_MUL24
int Mul24(int a, int b)

return a * b + c;
}
#endif // INTRINSIC_MAD24
#ifndef INTRINSIC_MED3
float Med3(float a, float b, float c)
{
return Clamp(a, b, c);
}
#endif // INTRINSIC_MED3
#ifndef INTRINSIC_MINMAX3
float Min3(float a, float b, float c)

#define HALF_PI 1.57079632679
#define INV_HALF_PI 0.636619772367
#define INFINITY asfloat(0x7F800000)
#define LOG2_E 1.44269504089
#define FLT_EPSILON 1.192092896e-07 // Smallest positive number, such that 1.0 + FLT_EPSILON != 1.0
#define FLT_MIN 1.175494351e-38 // Minimum representable positive floating-point number

#define SMALL_FLT_VALUE 0.0001
// General constant
float DegToRad(float deg)
{

6
ScriptableRenderPipeline/Core/ShaderLibrary/CommonLighting.hlsl


return float3x3(localX, localY, localZ);
}
// ior is a value between 1.0 and 2.5
float IORToFresnel0(float ior)
{
return Sqr((ior - 1.0) / (ior + 1.0));
}
#endif // UNITY_COMMON_LIGHTING_INCLUDED

27
ScriptableRenderPipeline/Core/ShaderLibrary/CommonMaterial.hlsl


// Helper function for anisotropy
//-----------------------------------------------------------------------------
// Ref: http://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf (in addenda)
// Convert anisotropic ratio (0->no isotropic; 1->full anisotropy in tangent direction) to roughness
void ConvertAnisotropyToRoughness(float roughness, float anisotropy, out float roughnessT, out float roughnessB)
{
// Use the parametrization of Sony Imageworks.

// Evaluate Int{0, inf}{2 * Pi * r * R(sqrt(r^2 + d^2))}, where R is the diffusion profile.
// Note: 'volumeAlbedo' should be premultiplied by 0.25.
// Ref: Approximate Reflectance Profiles for Efficient Subsurface Scattering by Pixar (BSSRDF only).
float3 ComputeTransmittance(float3 S, float3 volumeAlbedo, float thickness, float radiusScale)
float3 ComputeTransmittanceDisney(float3 S, float3 volumeAlbedo, float thickness, float radiusScale)
#if 0
#else
// Help the compiler.
float k = (-1.0 / 3.0) * LOG2_E;
float3 p = (k * thickness) * S;
float3 expOneThird = exp2(p);
#endif
// Premultiply & optimize: T = (1/4 * A) * (e^(-t * S) + 3 * e^(-1/3 * t * S))
return volumeAlbedo * (expOneThird * expOneThird * expOneThird + 3 * expOneThird);

float ComputeWrappedDiffuseLighting(float NdotL, float w)
{
return saturate((NdotL + w) / ((1 + w) * (1 + w)));
}
// In order to support subsurface scattering, we need to know which pixels have an SSS material.
// It can be accomplished by reading the stencil buffer.
// A faster solution (which avoids an extra texture fetch) is to simply make sure that
// all pixels which belong to an SSS material are not black (those that don't always are).
float3 TagLightingForSSS(float3 subsurfaceLighting)
{
subsurfaceLighting.r = max(subsurfaceLighting.r, HFLT_MIN);
return subsurfaceLighting;
}
// See TagLightingForSSS() for details.
bool TestLightingForSSS(float3 subsurfaceLighting)
{
return subsurfaceLighting.r > 0;
}
// MACRO from Legacy Untiy

22
ScriptableRenderPipeline/Core/ShaderLibrary/EntityLighting.hlsl


}
// This sample a 3D volume storing SH
// Volume is store as 3D texture with 4 R, G, B, X set of 4 coefficient store atlas in same 3D texture. X is use for occlusion.
// TODO: the packing here is inefficient as we will fetch values far away from each other and they may not fit into the cache - Suggest we pack only RGB continuously
// Volume is store as 3D texture with 4 R, G, B, Occ set of 4 coefficient store atlas in same 3D texture. Occ is use for occlusion.
// TODO: the packing here is inefficient as we will fetch values far away from each other and they may not fit into the cache - Suggest we pack RGB continuously
float3 SampleProbeVolumeSH4(TEXTURE3D_ARGS(SHVolumeTexture, SHVolumeSampler), float3 positionWS, float3 normalWS, float4x4 WorldToTexture,
float3 SampleProbeVolumeSH4(TEXTURE3D_ARGS(SHVolumeTexture, SHVolumeSampler), float3 positionWS, float3 normalWS, float4x4 WorldToTexture,
float transformToLocal, float texelSizeX, float3 probeVolumeMin, float3 probeVolumeSizeInv)
{
float3 position = (transformToLocal == 1.0f) ? mul(WorldToTexture, float4(positionWS, 1.0)).xyz : positionWS;

// but last one is not used.
// Clamp to edge of the "internal" texture, as R is from half texel to size of R texture minus half texel.
// This avoid leaking
texCoord.x = Clamp(texCoord.x * 0.25, 0.5 * texelSizeX, 0.25 - 0.5 * texelSizeX);
texCoord.x = clamp(texCoord.x * 0.25, 0.5 * texelSizeX, 0.25 - 0.5 * texelSizeX);
float4 shAr = SAMPLE_TEXTURE3D(SHVolumeTexture, SHVolumeSampler, texCoord);
texCoord.x += 0.25;

return SHEvalLinearL0L1(normalWS, shAr, shAg, shAb);
}
float4 SampleProbeOcclusion(TEXTURE3D_ARGS(SHVolumeTexture, SHVolumeSampler), float3 positionWS, float4x4 WorldToTexture,
float transformToLocal, float texelSizeX, float3 probeVolumeMin, float3 probeVolumeSizeInv)
{
float3 position = (transformToLocal == 1.0f) ? mul(WorldToTexture, float4(positionWS, 1.0)).xyz : positionWS;
float3 texCoord = (position - probeVolumeMin) * probeVolumeSizeInv.xyz;
// Sample fourth texture in the atlas
// We need to compute proper U coordinate to sample.
// Clamp the coordinate otherwize we'll have leaking between ShB coefficients and Probe Occlusion(Occ) info
texCoord.x = max(texCoord.x * 0.25 + 0.75, 0.75 + 0.5 * texelSizeX);
return SAMPLE_TEXTURE3D(SHVolumeTexture, SHVolumeSampler, texCoord);
}
// Following functions are to sample enlighten lightmaps (or lightmaps encoded the same way as our

6
ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/Resources/ShadowBlurMoments.compute


#if MAX_MSAA > 1
uint width, height, sampleCnt;
depthTex.GetDimensions( width, height, sampleCnt );
sampleCnt = Clamp( sampleCnt, 2, MAX_MSAA );
sampleCnt = clamp( sampleCnt, 2, MAX_MSAA );
float sampleCntRcp = 1.0 / sampleCnt;
// calculate weights based on sample positions

// 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 );
depth = clamp( depth, 0.001, 0.999 );
# endif
avgMoments += sampleWeights[is] * DepthToMoments( 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 );
depth = clamp( depth, 0.001, 0.999 );
# endif
writeToShared( DepthToMoments( depth ), int2( ldsIdx.x, groupThreadId.y ), LDS_STRIDE );
#endif

7
ScriptableRenderPipeline/Core/ShaderLibrary/VolumeRendering.hlsl


HenyeyGreensteinPhasePartVarying(asymmetry, LdotD);
}
// Absorption coefficient from Disney: http://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf
float3 TransmittanceColorAtDistanceToAbsorption(float3 transmittanceColor, float atDistance)
{
return -log(transmittanceColor + 0.00001) / max(atDistance, 0.000001);
}
#endif // UNITY_VOLUME_RENDERING_INCLUDED

2
ScriptableRenderPipeline/Core/Shadow/Resources/DebugDisplayShadowMap.shader


{
HLSLINCLUDE
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: unitl we go futher in dev
#include "../../../Core/ShaderLibrary/Common.hlsl"

7
ScriptableRenderPipeline/Core/Shadow/Shadow.cs


{
public const uint k_MaxCascadesInShader = 4;
protected readonly int m_TempDepthId;
protected readonly int m_ZClipId;
protected RenderTexture m_Shadowmap;
protected RenderTargetIdentifier m_ShadowmapId;
protected VectorArray<CachedEntry> m_EntryCache = new VectorArray<CachedEntry>( 0, true );

public Key key;
public Data current;
public Data previous;
public bool zclip;
public int CompareTo( CachedEntry other )
{

public ShadowAtlas( ref AtlasInit init ) : base( ref init.baseInit )
{
m_ZClipId = Shader.PropertyToID( "_ZClip" );
if( !IsNativeDepth() )
{
m_TempDepthId = Shader.PropertyToID( "Temporary Shadowmap Depth" );

// read
float texelSizeX = 1.0f, texelSizeY = 1.0f;
CachedEntry ce = m_EntryCache[ceIdx];
ce.zclip = sr.shadowType != GPUShadowType.Directional;
// modify
Matrix4x4 vp, invvp;
if( sr.shadowType == GPUShadowType.Point )

cmd.SetViewport( m_EntryCache[i].current.viewport );
cmd.SetViewProjectionMatrices( m_EntryCache[i].current.view, m_EntryCache[i].current.proj );
cmd.SetGlobalVector( "g_vLightDirWs", m_EntryCache[i].current.lightDir );
cmd.SetGlobalFloat( m_ZClipId, m_EntryCache[i].zclip ? 1.0f : 0.0f );
//cmd.EndSample(cbName);
dss.lightIndex = m_EntryCache[i].key.visibleIdx;

cmd.EndSample("Shadowmap.DisableShaderKeyword");
}
cmd.SetGlobalFloat( m_ZClipId, 1.0f ); // Re-enable zclip globally
m_ActiveEntriesCount = 0;
profilingSample.Dispose();

13
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs


IndirectDiffuseOcclusionFromSsao,
IndirectDiffuseGtaoFromSsao,
IndirectSpecularOcclusionFromSsao,
IndirectSpecularGtaoFromSsao
IndirectSpecularGtaoFromSsao
}
public class DebugDisplaySettings

VertexNormalWS,
VertexColor,
VertexColorAlpha,
// caution if you add something here, it must start below
Last,
};
// Number must be contiguous

None = 0,
Depth = DebugViewVarying.VertexColorAlpha + 1,
Depth = DebugViewVarying.Last + 1,
BakeShadowMask0,
BakeShadowMask1,
BakeShadowMask2,
BakeShadowMask3,
Last,
}
// Number must be contiguous

None = 0,
Tessellation = DebugViewGbuffer.BakeDiffuseLightingWithAlbedoPlusEmissive + 1,
Tessellation = DebugViewGbuffer.Last + 1,
PixelDisplacement,
VertexDisplacement,
TessellationDisplacement,

22
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs.hlsl


#define DEBUGVIEWVARYING_VERTEX_NORMAL_WS (7)
#define DEBUGVIEWVARYING_VERTEX_COLOR (8)
#define DEBUGVIEWVARYING_VERTEX_COLOR_ALPHA (9)
#define DEBUGVIEWVARYING_LAST (10)
#define DEBUGVIEWGBUFFER_DEPTH (10)
#define DEBUGVIEWGBUFFER_BAKE_DIFFUSE_LIGHTING_WITH_ALBEDO_PLUS_EMISSIVE (11)
#define DEBUGVIEWGBUFFER_DEPTH (11)
#define DEBUGVIEWGBUFFER_BAKE_DIFFUSE_LIGHTING_WITH_ALBEDO_PLUS_EMISSIVE (12)
#define DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK0 (13)
#define DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK1 (14)
#define DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK2 (15)
#define DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK3 (16)
#define DEBUGVIEWGBUFFER_LAST (17)
#define DEBUGVIEWPROPERTIES_TESSELLATION (12)
#define DEBUGVIEWPROPERTIES_PIXEL_DISPLACEMENT (13)
#define DEBUGVIEWPROPERTIES_VERTEX_DISPLACEMENT (14)
#define DEBUGVIEWPROPERTIES_TESSELLATION_DISPLACEMENT (15)
#define DEBUGVIEWPROPERTIES_DEPTH_OFFSET (16)
#define DEBUGVIEWPROPERTIES_LIGHTMAP (17)
#define DEBUGVIEWPROPERTIES_TESSELLATION (18)
#define DEBUGVIEWPROPERTIES_PIXEL_DISPLACEMENT (19)
#define DEBUGVIEWPROPERTIES_VERTEX_DISPLACEMENT (20)
#define DEBUGVIEWPROPERTIES_TESSELLATION_DISPLACEMENT (21)
#define DEBUGVIEWPROPERTIES_DEPTH_OFFSET (22)
#define DEBUGVIEWPROPERTIES_LIGHTMAP (23)
//
// UnityEngine.Experimental.Rendering.HDPipeline.FullScreenDebugMode: static fields

2
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplayLatlong.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: unitl we go futher in dev
#pragma vertex Vert
#pragma fragment Frag

2
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugFullScreen.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: unitl we go futher in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: unitl we go futher in dev
#pragma vertex Vert
#pragma fragment Frag

34
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewMaterialGBuffer.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma multi_compile _ SHADOWS_SHADOWMASK
#include "../../Core/ShaderLibrary/Common.hlsl"
#include "../../Core/ShaderLibrary/Color.hlsl"

#include "../Material/Material.hlsl"
DECLARE_GBUFFER_TEXTURE(_GBufferTexture);
#ifdef SHADOWS_SHADOWMASK
TEXTURE2D(_ShadowMaskTexture);
#endif
struct Attributes
{

FETCH_GBUFFER(gbuffer, _GBufferTexture, posInput.unPositionSS);
BSDFData bsdfData;
float3 bakeDiffuseLighting;
DECODE_FROM_GBUFFER(gbuffer, 0xFFFFFFFF, bsdfData, bakeDiffuseLighting);
BakeLightingData bakeLightingData;
DECODE_FROM_GBUFFER(gbuffer, 0xFFFFFFFF, bsdfData, bakeLightingData.bakeDiffuseLighting);
#ifdef SHADOWS_SHADOWMASK
DecodeShadowMask(LOAD_TEXTURE2D(_ShadowMaskTexture, posInput.unPositionSS), bakeLightingData.bakeShadowMask);
#endif
// Init to not expected value
float3 result = float3(-666.0, 0.0, 0.0);

{
// TODO: require a remap
// TODO: we should not gamma correct, but easier to debug for now without correct high range value
result = bakeDiffuseLighting; needLinearToSRGB = true;
result = bakeLightingData.bakeDiffuseLighting; needLinearToSRGB = true;
#ifdef SHADOWS_SHADOWMASK
else if (_DebugViewMaterial == DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK0)
{
result = bakeLightingData.bakeShadowMask.xxx;
}
else if (_DebugViewMaterial == DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK1)
{
result = bakeLightingData.bakeShadowMask.yyy;
}
else if (_DebugViewMaterial == DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK2)
{
result = bakeLightingData.bakeShadowMask.zzz;
}
else if (_DebugViewMaterial == DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK3)
{
result = bakeLightingData.bakeShadowMask.www;
}
#endif
GetBSDFDataDebug(_DebugViewMaterial, bsdfData, result, needLinearToSRGB);

2
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewTiles.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

88
ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs


using System.IO;
using System.IO;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;

}
}
static void CheckOutFile(bool VSCEnabled, Material mat)
{
if (VSCEnabled)
{
UnityEditor.VersionControl.Task task = UnityEditor.VersionControl.Provider.Checkout(mat, UnityEditor.VersionControl.CheckoutMode.Both);
if (!task.success)
{
Debug.Log(task.text + " " + task.resultCode);
}
}
}
[MenuItem("HDRenderPipeline/Update/Update SSS profile indices")]
static void UpdateSSSProfileIndices()
{
try
{
var matIds = AssetDatabase.FindAssets("t:Material");
for (int i = 0, length = matIds.Length; i < length; i++)
{
var path = AssetDatabase.GUIDToAssetPath(matIds[i]);
var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
EditorUtility.DisplayProgressBar(
"Setup materials Keywords...",
string.Format("{0} / {1} materials SSS updated.", i, length),
i / (float)(length - 1));
bool VSCEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);
if (mat.shader.name == "HDRenderPipeline/LitTessellation" ||
mat.shader.name == "HDRenderPipeline/Lit")
{
float fvalue = mat.GetFloat("_MaterialID");
if (fvalue == 0.0) // SSS
{
CheckOutFile(VSCEnabled, mat);
int ivalue = mat.GetInt("_SubsurfaceProfile");
if (ivalue == 15)
{
mat.SetInt("_SubsurfaceProfile", 0);
}
else
{
mat.SetInt("_SubsurfaceProfile", ivalue + 1);
}
EditorUtility.SetDirty(mat);
}
}
else if (mat.shader.name == "HDRenderPipeline/LayeredLit" ||
mat.shader.name == "HDRenderPipeline/LayeredLitTessellation")
{
float fvalue = mat.GetFloat("_MaterialID");
if (fvalue == 0.0) // SSS
{
CheckOutFile(VSCEnabled, mat);
int numLayer = (int)mat.GetFloat("_LayerCount");
for (int x = 0; x < numLayer; ++x)
{
int ivalue = mat.GetInt("_SubsurfaceProfile" + x);
if (ivalue == 15)
{
mat.SetInt("_SubsurfaceProfile" + x, 0);
}
else
{
mat.SetInt("_SubsurfaceProfile" + x, ivalue + 1);
}
}
EditorUtility.SetDirty(mat);
}
}
}
}
finally
{
EditorUtility.ClearProgressBar();
}
}
// Function used only to check performance of data with and without tessellation
[MenuItem("HDRenderPipeline/Test/Remove tessellation materials (not reversible)")]
static void RemoveTessellationMaterials()

static void MenuCreateSubsurfaceScatteringProfile()
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetSubsurfaceScatteringSettings>(), "New SSS Profile.asset", icon, null);
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<DoCreateNewAssetSubsurfaceScatteringSettings>(), "New SSS Settings.asset", icon, null);
}
[MenuItem("Assets/Create/HDRenderPipeline/HDRISky Settings", priority = 750)]

209
ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs


public int gbufferCount { get; set; }
int[] m_IDs = new int[k_MaxGbuffer];
RenderTextureFormat[] m_Formats = new RenderTextureFormat[k_MaxGbuffer];
RenderTextureReadWrite[] m_sRGBWrites = new RenderTextureReadWrite[k_MaxGbuffer];
public void SetBufferDescription(int index, string stringId, RenderTextureFormat inFormat, RenderTextureReadWrite inSRGBWrite)
public void InitGBuffers(int width, int height, RenderPipelineMaterial deferredMaterial, bool enableBakeShadowMask, CommandBuffer cmd)
m_IDs[index] = Shader.PropertyToID(stringId);
m_RTIDs[index] = new RenderTargetIdentifier(m_IDs[index]);
m_Formats[index] = inFormat;
m_sRGBWrites[index] = inSRGBWrite;
}
// Init Gbuffer description
gbufferCount = deferredMaterial.GetMaterialGBufferCount();
RenderTextureFormat[] rtFormat;
RenderTextureReadWrite[] rtReadWrite;
deferredMaterial.GetMaterialGBufferDescription(out rtFormat, out rtReadWrite);
for (int gbufferIndex = 0; gbufferIndex < gbufferCount; ++gbufferIndex)
{
cmd.GetTemporaryRT(HDShaderIDs._GBufferTexture[gbufferIndex], width, height, 0, FilterMode.Point, rtFormat[gbufferIndex], rtReadWrite[gbufferIndex]);
m_RTIDs[gbufferIndex] = new RenderTargetIdentifier(HDShaderIDs._GBufferTexture[gbufferIndex]);
}
if (enableBakeShadowMask)
{
cmd.GetTemporaryRT(HDShaderIDs._ShadowMaskTexture, width, height, 0, FilterMode.Point, Builtin.GetShadowMaskBufferFormat(), Builtin.GetShadowMaskBufferReadWrite());
m_RTIDs[gbufferCount++] = new RenderTargetIdentifier(HDShaderIDs._ShadowMaskTexture);
}
public void InitGBuffers(int width, int height, CommandBuffer cmd)
{
for (int index = 0; index < gbufferCount; index++)
if (ShaderConfig.s_VelocityInGbuffer == 1)
cmd.GetTemporaryRT(m_IDs[index], width, height, 0, FilterMode.Point, m_Formats[index], m_sRGBWrites[index]);
// If velocity is in GBuffer then it is in the last RT. Assign a different name to it.
cmd.GetTemporaryRT(HDShaderIDs._VelocityTexture, width, height, 0, FilterMode.Point, Builtin.GetVelocityBufferFormat(), Builtin.GetVelocityBufferReadWrite());
m_RTIDs[gbufferCount++] = new RenderTargetIdentifier(HDShaderIDs._VelocityTexture);
// TODO: check with THomas or Tim if wa can simply return m_ColorMRTs with null for extra RT
if (m_ColorMRTs == null || m_ColorMRTs.Length != gbufferCount)
m_ColorMRTs = new RenderTargetIdentifier[gbufferCount];

readonly GBufferManager m_GbufferManager = new GBufferManager();
// Renderer Bake configuration can vary depends on if shadow mask is enabled or no
RendererConfiguration m_currentRendererConfigurationBakedLighting = HDUtils.k_RendererConfigurationBakedLighting;
Material m_CopyStencilForSplitLighting;
Material m_CopyStencilForRegularLighting;
GPUCopy m_GPUCopy;

// Debug material
Material m_DebugViewMaterialGBuffer;
Material m_DebugViewMaterialGBufferShadowMask;
Material m_currentDebugViewMaterialGBuffer;
Material m_DebugDisplayLatlong;
Material m_DebugFullScreen;
Material m_ErrorMaterial;

// Old SSS Model >>>
readonly int m_CameraFilteringBuffer;
// <<< Old SSS Model
readonly int m_ShadowMaskBuffer;
readonly int m_VelocityBuffer;
readonly int m_DistortionBuffer;
readonly int m_GaussianPyramidColorBuffer;

RenderTargetIdentifier m_CameraStencilBufferCopyRT;
RenderTargetIdentifier m_HTileRT;
// The pass "SRPDefaultUnlit" is a fallback to legacy unlit rendering and is required to support unity 2d + unity UI that render in the scene.
// The pass "SRPDefaultUnlit" is a fall back to legacy unlit rendering and is required to support unity 2d + unity UI that render in the scene.
ShaderPassName[] m_ForwardAndForwardOnlyPassNames = { new ShaderPassName(), new ShaderPassName(), HDShaderPassNames.s_SRPDefaultUnlitName};
ShaderPassName[] m_ForwardOnlyPassNames = { new ShaderPassName(), HDShaderPassNames.s_SRPDefaultUnlitName};
ShaderPassName[] m_DepthOnlyAndDepthForwardOnlyPassNames = { HDShaderPassNames.s_DepthForwardOnlyName, HDShaderPassNames.s_DepthOnlyName };

InitializeDebugMaterials();
// Init Gbuffer description
m_GbufferManager.gbufferCount = m_DeferredMaterial.GetMaterialGBufferCount();
RenderTextureFormat[] rtFormat;
RenderTextureReadWrite[] rtReadWrite;
m_DeferredMaterial.GetMaterialGBufferDescription(out rtFormat, out rtReadWrite);
for (int gbufferIndex = 0; gbufferIndex < m_GbufferManager.gbufferCount; ++gbufferIndex)
{
m_GbufferManager.SetBufferDescription(gbufferIndex, "_GBufferTexture" + gbufferIndex, rtFormat[gbufferIndex], rtReadWrite[gbufferIndex]);
}
if (ShaderConfig.s_VelocityInGbuffer == 1)
{
// If velocity is in GBuffer then it is in the last RT. Assign a different name to it.
m_GbufferManager.SetBufferDescription(m_GbufferManager.gbufferCount, "_VelocityTexture", Builtin.GetVelocityBufferFormat(), Builtin.GetVelocityBufferReadWrite());
m_GbufferManager.gbufferCount++;
}
m_VelocityBufferRT = new RenderTargetIdentifier(m_VelocityBuffer);
m_DistortionBuffer = HDShaderIDs._DistortionTexture;

void InitializeDebugMaterials()
{
m_DebugViewMaterialGBuffer = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugViewMaterialGBufferShader);
m_DebugViewMaterialGBufferShadowMask = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugViewMaterialGBufferShader);
m_DebugViewMaterialGBufferShadowMask.EnableKeyword("SHADOWS_SHADOWMASK");
m_DebugDisplayLatlong = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugDisplayLatlongShader);
m_DebugFullScreen = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugFullScreenShader);
m_ErrorMaterial = CoreUtils.CreateEngineMaterial("Hidden/InternalErrorShader");

m_MaterialList.ForEach(material => material.Cleanup());
CoreUtils.Destroy(m_DebugViewMaterialGBuffer);
CoreUtils.Destroy(m_DebugViewMaterialGBufferShadowMask);
CoreUtils.Destroy(m_DebugDisplayLatlong);
CoreUtils.Destroy(m_DebugFullScreen);
CoreUtils.Destroy(m_ErrorMaterial);

#if UNITY_EDITOR
SupportedRenderingFeatures.active = SupportedRenderingFeatures.Default;
SupportedRenderingFeatures.active = new SupportedRenderingFeatures();
#endif
}

reflectionProbe = SupportedRenderingFeatures.ReflectionProbe.Rotation
reflectionProbeSupportFlags = SupportedRenderingFeatures.ReflectionProbeSupportFlags.Rotation
};
#endif

m_LightLoop.AllocResolutionDependentBuffers(camera.pixelWidth, camera.pixelHeight);
}
if (resolutionChanged && m_VolumetricLightingEnabled)
CreateVolumetricLightingBuffers(camera.pixelWidth, camera.pixelHeight);
// update recorded window resolution
m_CurrentWidth = camera.pixelWidth;
m_CurrentHeight = camera.pixelHeight;

cmd.SetGlobalVectorArray(HDShaderIDs._ShapeParams, sssParameters.shapeParams);
cmd.SetGlobalVectorArray(HDShaderIDs._HalfRcpVariancesAndWeights, sssParameters.halfRcpVariancesAndWeights);
cmd.SetGlobalVectorArray(HDShaderIDs._TransmissionTints, sssParameters.transmissionTints);
SetGlobalVolumeProperties(m_VolumetricLightingEnabled, cmd);
// For now we consider only PS4 to be able to read from a bound depth buffer. Need to test/implement for other platforms.
// For now we consider only PS4 to be able to read from a bound depth buffer.
// TODO: test/implement for other platforms.
return SystemInfo.graphicsDeviceType != GraphicsDeviceType.PlayStation4;
}

{
// Currently, Unity does not offer a way to access the GCN HTile even on PS4 and Xbox One.
// Therefore, it's computed in a pixel shader, and optimized to only contain the SSS bit.
return m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission;
return m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission && sssSettings.useDisneySSS;
}
bool NeedTemporarySubsurfaceBuffer()
{
// Typed UAV loads from FORMAT_R16G16B16A16_FLOAT is an optional feature of Direct3D 11.
// Most modern GPUs support it. We can avoid performing a costly copy in this case.
// TODO: test/implement for other platforms.
return m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission && (!sssSettings.useDisneySSS || (
SystemInfo.graphicsDeviceType != GraphicsDeviceType.PlayStation4 &&
SystemInfo.graphicsDeviceType != GraphicsDeviceType.XboxOne &&
SystemInfo.graphicsDeviceType != GraphicsDeviceType.XboxOneD3D12));
}
RenderTargetIdentifier GetDepthTexture()

m_ShadowSettings.maxShadowDistance = commonSettings.shadowMaxDistance;
m_ShadowSettings.directionalLightNearPlaneOffset = commonSettings.shadowNearPlaneOffset;
}
public void ConfigureForShadowMask(bool enableBakeShadowMask, CommandBuffer cmd)
{
// Globally enable (for GBuffer shader and forward lit (opaque and transparent) the keyword SHADOWS_SHADOWMASK
CoreUtils.SetKeyword(cmd, "SHADOWS_SHADOWMASK", enableBakeShadowMask);
// Configure material to use depends on shadow mask option
m_currentRendererConfigurationBakedLighting = enableBakeShadowMask ? HDUtils.k_RendererConfigurationBakedLightingWithShadowMask : HDUtils.k_RendererConfigurationBakedLighting;
m_currentDebugViewMaterialGBuffer = enableBakeShadowMask ? m_DebugViewMaterialGBufferShadowMask : m_DebugViewMaterialGBuffer;
}
CullResults m_CullResults;

return;
}
InitAndClearBuffer(hdCamera, cmd);
// Note: Legacy Unity behave like this for ShadowMask
// When you select ShadowMask in Lighting panel it recompile shaders on the fly with the SHADOW_MASK keyword.
// However there is no C# function that we can query to know what mode have been select in Lighting Panel and it will be wrong anyway. Lighting Panel setup what will be the next bake mode. But until light is bake, it is wrong.
// Currently to know if you need shadow mask you need to go through all visible lights (of CullResult), check the LightBakingOutput struct and look at lightmapBakeType/mixedLightingMode. If one light have shadow mask bake mode, then you need shadow mask features (i.e extra Gbuffer).
// It mean that when we build a standalone player, if we detect a light with bake shadow mask, we generate all shader variant (with and without shadow mask) and at runtime, when a bake shadow mask light is visible, we dynamically allocate an extra GBuffer and switch the shader.
// So the first thing to do is to go through all the light: PrepareLightsForGPU
bool enableBakeShadowMask = m_LightLoop.PrepareLightsForGPU(m_ShadowSettings, m_CullResults, camera);
ConfigureForShadowMask(enableBakeShadowMask, cmd);
InitAndClearBuffer(hdCamera, enableBakeShadowMask, cmd);
RenderDepthPrepass(m_CullResults, camera, renderContext, cmd);

}
}
m_LightLoop.PrepareLightsForGPU(m_ShadowSettings, m_CullResults, camera);
m_LightLoop.RenderShadows(renderContext, cmd, m_CullResults);
cmd.GetTemporaryRT(m_DeferredShadowBuffer, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear, 1 , true);

RenderForward(m_CullResults, camera, renderContext, cmd, ForwardPass.Transparent);
RenderForwardError(m_CullResults, camera, renderContext, cmd, ForwardPass.Transparent);
// Render volumetric lighting
VolumetricLightingPass(hdCamera, cmd);
PushFullScreenDebugTexture(cmd, m_CameraColorBuffer, camera, renderContext, FullScreenDebugMode.NanTracker);
// Planar and real time cubemap doesn't need post process and render in FP16

bool preRefractionQueue = false)
{
m_SinglePassName[0] = passName;
RenderTransparentRenderList(cull, camera, renderContext, cmd, m_SinglePassName,
RenderTransparentRenderList(cull, camera, renderContext, cmd, m_SinglePassName,
rendererConfiguration, stateBlock, overrideMaterial, preRefractionQueue);
}

var filterSettings = new FilterRenderersSettings(true)
{
renderQueueRange = preRefractionQueue
? k_RenderQueue_PreRefraction
renderQueueRange = preRefractionQueue
? k_RenderQueue_PreRefraction
: k_RenderQueue_Transparent
};

if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())
{
// When doing debug display, the shader has the clip instruction regardless of the depth prepass so we can use regular depth test.
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferDebugDisplayName, HDUtils.k_RendererConfigurationBakedLighting, RenderQueueRange.opaque, m_DepthStateOpaque);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferDebugDisplayName, m_currentRendererConfigurationBakedLighting, RenderQueueRange.opaque, m_DepthStateOpaque);
}
else
{

var rangeOpaqueAlphaTest = new RenderQueueRange { min = (int)RenderQueue.AlphaTest, max = (int)RenderQueue.GeometryLast - 1 };
// When using depth prepass for opaque alpha test only we need to use regular depth test for normal opaque objects.
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, HDUtils.k_RendererConfigurationBakedLighting, rangeOpaqueNoAlphaTest, m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass ? m_DepthStateOpaque : m_DepthStateOpaqueWithPrepass);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, m_currentRendererConfigurationBakedLighting, rangeOpaqueNoAlphaTest, m_Asset.renderingSettings.renderAlphaTestOnlyInDeferredPrepass ? m_DepthStateOpaque : m_DepthStateOpaqueWithPrepass);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferWithPrepassName, HDUtils.k_RendererConfigurationBakedLighting, rangeOpaqueAlphaTest, m_DepthStateOpaqueWithPrepass);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferWithPrepassName, m_currentRendererConfigurationBakedLighting, rangeOpaqueAlphaTest, m_DepthStateOpaqueWithPrepass);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, HDUtils.k_RendererConfigurationBakedLighting, RenderQueueRange.opaque, m_DepthStateOpaque);
RenderOpaqueRenderList(cull, camera, renderContext, cmd, HDShaderPassNames.s_GBufferName, m_currentRendererConfigurationBakedLighting, RenderQueueRange.opaque, m_DepthStateOpaque);
}
}
}

{
using (new ProfilingSample(cmd, "DebugViewMaterialGBuffer"))
{
CoreUtils.DrawFullScreen(cmd, m_DebugViewMaterialGBuffer, m_CameraColorBufferRT);
CoreUtils.DrawFullScreen(cmd, m_currentDebugViewMaterialGBuffer, m_CameraColorBufferRT);
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.All, Color.black);
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.All, CoreUtils.clearColorAllBlack);
RenderOpaqueRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.s_ForwardDebugDisplayName, HDUtils.k_RendererConfigurationBakedLighting);
RenderOpaqueRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.s_ForwardDebugDisplayName, m_currentRendererConfigurationBakedLighting);
RenderTransparentRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.s_ForwardDebugDisplayName, HDUtils.k_RendererConfigurationBakedLighting);
RenderTransparentRenderList(cull, hdCamera.camera, renderContext, cmd, HDShaderPassNames.s_ForwardDebugDisplayName, m_currentRendererConfigurationBakedLighting);
}
}

var depthTexture = GetDepthTexture();
var options = new LightLoop.LightingPassOptions();
options.volumetricLightingEnabled = m_VolumetricLightingEnabled;
if (m_CurrentDebugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)
{

cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._FilterKernels, sssParameters.filterKernels);
cmd.SetComputeVectorArrayParam(m_SubsurfaceScatteringCS, HDShaderIDs._ShapeParams, sssParameters.shapeParams);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture0, m_GbufferManager.GetGBuffers()[0]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture1, m_GbufferManager.GetGBuffers()[1]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture2, m_GbufferManager.GetGBuffers()[2]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture3, m_GbufferManager.GetGBuffers()[3]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._DepthTexture, GetDepthTexture());
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._StencilTexture, GetStencilTexture());
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._HTile, GetHTile());
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._IrradianceSource, m_CameraSssDiffuseLightingBufferRT);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._CameraColorTexture, m_CameraColorBufferRT);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._CameraFilteringBuffer, m_CameraFilteringBufferRT);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture0, m_GbufferManager.GetGBuffers()[0]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture1, m_GbufferManager.GetGBuffers()[1]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture2, m_GbufferManager.GetGBuffers()[2]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._GBufferTexture3, m_GbufferManager.GetGBuffers()[3]);
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._DepthTexture, GetDepthTexture());
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._HTile, GetHTile());
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._IrradianceSource, m_CameraSssDiffuseLightingBufferRT);
// Perform the SSS filtering pass which fills 'm_CameraFilteringBufferRT'.
cmd.DispatchCompute(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, ((int)hdCamera.screenSize.x + 15) / 16, ((int)hdCamera.screenSize.y + 15) / 16, 1);
if (NeedTemporarySubsurfaceBuffer())
{
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._CameraFilteringBuffer, m_CameraFilteringBufferRT);
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraFilteringBufferRT); // Cannot set a RT on a material
// Perform the SSS filtering pass which fills 'm_CameraFilteringBufferRT'.
cmd.DispatchCompute(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, ((int)hdCamera.screenSize.x + 15) / 16, ((int)hdCamera.screenSize.y + 15) / 16, 1);
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraFilteringBufferRT); // Cannot set a RT on a material
// Combine diffuse and specular lighting into 'm_CameraColorBufferRT'.
CoreUtils.DrawFullScreen(cmd, m_CombineLightingPass, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
// Additively blend diffuse and specular lighting into 'm_CameraColorBufferRT'.
CoreUtils.DrawFullScreen(cmd, m_CombineLightingPass, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
}
else
{
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._CameraColorTexture, m_CameraColorBufferRT);
// Perform the SSS filtering pass which performs an in-place update of 'm_CameraColorBufferRT'.
cmd.DispatchCompute(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, ((int)hdCamera.screenSize.x + 15) / 16, ((int)hdCamera.screenSize.y + 15) / 16, 1);
}
}
else
{

{
var passNames = m_Asset.renderingSettings.ShouldUseForwardRenderingOnly() ? m_ForwardAndForwardOnlyPassNames : m_ForwardOnlyPassNames;
// Forward opaque material always have a prepass (whether or not we use deferred, whether or not there is option like alpha test only) so we pass the right depth state here.
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, passNames, HDUtils.k_RendererConfigurationBakedLighting, null, m_DepthStateOpaqueWithPrepass);
RenderOpaqueRenderList(cullResults, camera, renderContext, cmd, passNames, m_currentRendererConfigurationBakedLighting, null, m_DepthStateOpaqueWithPrepass);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, m_ForwardAndForwardOnlyPassNames, HDUtils.k_RendererConfigurationBakedLighting, preRefractionQueue: pass == ForwardPass.PreRefraction);
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, m_ForwardAndForwardOnlyPassNames, m_currentRendererConfigurationBakedLighting, preRefractionQueue: pass == ForwardPass.PreRefraction);
}
}
}

}
else
{
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, m_ForwardErrorPassNames, 0,
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, m_ForwardErrorPassNames, 0,
null, m_ErrorMaterial, pass == ForwardPass.PreRefraction);
}
}

}
}
void InitAndClearBuffer(HDCamera camera, CommandBuffer cmd)
void InitAndClearBuffer(HDCamera camera, bool enableBakeShadowMask, CommandBuffer cmd)
{
using (new ProfilingSample(cmd, "InitAndClearBuffer"))
{

cmd.GetTemporaryRT(m_CameraColorBuffer, w, h, 0, FilterMode.Point, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear, 1, true); // Enable UAV
cmd.GetTemporaryRT(m_CameraSssDiffuseLightingBuffer, w, h, 0, FilterMode.Point, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear, 1, true); // Enable UAV
cmd.GetTemporaryRT(m_CameraFilteringBuffer, w, h, 0, FilterMode.Point, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear, 1, true); // Enable UAV
if (NeedTemporarySubsurfaceBuffer())
{
cmd.GetTemporaryRT(m_CameraFilteringBuffer, w, h, 0, FilterMode.Point, RenderTextureFormat.RGB111110Float, RenderTextureReadWrite.Linear, 1, true); // Enable UAV
}
// Color and depth pyramids
int s = CalculatePyramidSize(w, h);

// End
if (!m_Asset.renderingSettings.ShouldUseForwardRenderingOnly())
m_GbufferManager.InitGBuffers(w, h, cmd);
m_GbufferManager.InitGBuffers(w, h, m_DeferredMaterial, enableBakeShadowMask, cmd);
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Depth);
}

{
CoreUtils.SetRenderTarget(cmd, m_CameraSssDiffuseLightingBufferRT, ClearFlag.Color, Color.black);
CoreUtils.SetRenderTarget(cmd, m_CameraSssDiffuseLightingBufferRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
if (!sssSettings.useDisneySSS)
if (NeedTemporarySubsurfaceBuffer())
CoreUtils.SetRenderTarget(cmd, m_CameraFilteringBuffer, ClearFlag.Color, Color.black);
CoreUtils.SetRenderTarget(cmd, m_CameraFilteringBuffer, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}
}
// <<< Old SSS Model

using (new ProfilingSample(cmd, "Clear stencil texture"))
{
CoreUtils.SetRenderTarget(cmd, m_CameraStencilBufferCopyRT, ClearFlag.Color, Color.black);
CoreUtils.SetRenderTarget(cmd, m_CameraStencilBufferCopyRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}
}

{
CoreUtils.SetRenderTarget(cmd, m_HTileRT, ClearFlag.Color, Color.black);
CoreUtils.SetRenderTarget(cmd, m_HTileRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
if (m_VolumetricLightingEnabled)
ClearVolumetricLightingBuffers(cmd, camera.isFirstFrame);
// TEMP: As we are in development and have not all the setup pass we still clear the color in emissive buffer and gbuffer, but this will be removed later.
// TODO: As we are in development and have not all the setup pass we still clear the color in emissive buffer and gbuffer, but this will be removed later.
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Color, Color.black);
CoreUtils.SetRenderTarget(cmd, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}
// Clear GBuffers

{
CoreUtils.SetRenderTarget(cmd, m_GbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT, ClearFlag.Color, Color.black);
CoreUtils.SetRenderTarget(cmd, m_GbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT, ClearFlag.Color, CoreUtils.clearColorAllBlack);
}
}
// END TEMP

13
ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs


public static readonly int _CameraFilteringBuffer = Shader.PropertyToID("_CameraFilteringTexture");
public static readonly int _IrradianceSource = Shader.PropertyToID("_IrradianceSource");
public static readonly int[] _GBufferTexture =
{
Shader.PropertyToID("_GBufferTexture0"),
Shader.PropertyToID("_GBufferTexture1"),
Shader.PropertyToID("_GBufferTexture2"),
Shader.PropertyToID("_GBufferTexture3"),
Shader.PropertyToID("_GBufferTexture4"),
Shader.PropertyToID("_GBufferTexture5"),
Shader.PropertyToID("_GBufferTexture6"),
Shader.PropertyToID("_GBufferTexture7")
};
public static readonly int _ShadowMaskTexture = Shader.PropertyToID("_ShadowMaskTexture");
public static readonly int _DistortionTexture = Shader.PropertyToID("_DistortionTexture");
public static readonly int _GaussianPyramidColorTexture = Shader.PropertyToID("_GaussianPyramidColorTexture");
public static readonly int _DepthPyramidTexture = Shader.PropertyToID("_PyramidDepthTexture");

1
ScriptableRenderPipeline/HDRenderPipeline/HDUtils.cs


public class HDUtils
{
public const RendererConfiguration k_RendererConfigurationBakedLighting = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbeProxyVolume;
public const RendererConfiguration k_RendererConfigurationBakedLightingWithShadowMask = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbeProxyVolume;
public static List<RenderPipelineMaterial> GetRenderPipelineMaterialList()
{

25
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Deferred.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#pragma vertex Vert

// Split lighting is utilized during the SSS pass.
#pragma multi_compile _ OUTPUT_SPLIT_LIGHTING
#pragma multi_compile _ SHADOWS_SHADOWMASK
#pragma multi_compile _ DEBUG_DISPLAY
//-------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------
DECLARE_GBUFFER_TEXTURE(_GBufferTexture);
#ifdef SHADOWS_SHADOWMASK
TEXTURE2D(_ShadowMaskTexture);
#endif
struct Attributes
{

UpdatePositionInput(depth, _InvViewProjMatrix, _ViewProjMatrix, posInput);
float3 V = GetWorldSpaceNormalizeViewDir(posInput.positionWS);
uint featureFlags = 0xFFFFFFFF;
float3 bakeDiffuseLighting;
DECODE_FROM_GBUFFER(gbuffer, featureFlags, bsdfData, bakeDiffuseLighting);
BakeLightingData bakeLightingData;
DECODE_FROM_GBUFFER(gbuffer, MATERIAL_FEATURE_MASK_FLAGS, bsdfData, bakeLightingData.bakeDiffuseLighting);
#ifdef SHADOWS_SHADOWMASK
DecodeShadowMask(LOAD_TEXTURE2D(_ShadowMaskTexture, posInput.unPositionSS), bakeLightingData.bakeShadowMask);
#endif
LightLoop(V, posInput, preLightData, bsdfData, bakeDiffuseLighting, featureFlags, diffuseLighting, specularLighting);
LightLoop(V, posInput, preLightData, bsdfData, bakeLightingData, LIGHT_FEATURE_MASK_FLAGS_OPAQUE, diffuseLighting, specularLighting);
outputs.diffuseLighting = diffuseLighting;
// We SSSSS is enabled with use split lighting.
// SSSSS algorithm need to know which pixels contribute to SSS and which doesn't. We could use the stencil for that but it mean that it will increase the cost of SSSSS
// A simpler solution is to add a slight contribution here that isn't visible (here we chose fp16 min (which is also fp11 and fp10 min).
// The SSSSS algorithm will check if diffuse lighting is black and discard the pixel if it is the case
outputs.diffuseLighting.r = max(outputs.diffuseLighting.r, HFLT_MIN);
outputs.diffuseLighting = TagLightingForSSS(diffuseLighting);
#else
outputs.combinedLighting = float4(diffuseLighting + specularLighting, 1.0);
#endif

18
ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs


// Disk,
};
// This is use to distinguish between reflection and refraction probe in LightLoop
[GenerateHLSL]
public enum GPUImageBasedLightingType
{
Reflection,
Refraction
};
// These structures share between C# and hlsl need to be align on float4, so we pad them.
[GenerateHLSL]
public struct DirectionalLightData

public Vector3 up; // Rescaled by (2 / shapeWidth)
public float diffuseScale;
public bool dynamicShadowCasterOnly; // Use with ShadowMask feature
public Vector2 fadeDistanceScaleAndBias; // Use with ShadowMask feature
public float unused0;
public Vector4 shadowMaskSelector; // Use with ShadowMask feature
};
[GenerateHLSL]

public float angleScale; // Spot light
public float angleOffset; // Spot light
public float shadowDimmer;
public int unused0;
public bool dynamicShadowCasterOnly; // Use with ShadowMask feature
public Vector4 shadowMaskSelector; // Use with ShadowMask feature
};

37
ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs.hlsl


#define GPULIGHTTYPE_RECTANGLE (6)
//
// UnityEngine.Experimental.Rendering.HDPipeline.GPUImageBasedLightingType: static fields
//
#define GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION (0)
#define GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION (1)
//
// UnityEngine.Experimental.Rendering.HDPipeline.EnvShapeType: static fields
//
#define ENVSHAPETYPE_NONE (0)

float specularScale;
float3 up;
float diffuseScale;
bool dynamicShadowCasterOnly;
float2 fadeDistanceScaleAndBias;
float unused0;
float4 shadowMaskSelector;
};
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.LightData

float angleScale;
float angleOffset;
float shadowDimmer;
int unused0;
bool dynamicShadowCasterOnly;
float4 shadowMaskSelector;
};
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.EnvLightData

{
return value.diffuseScale;
}
bool GetDynamicShadowCasterOnly(DirectionalLightData value)
{
return value.dynamicShadowCasterOnly;
}
float2 GetFadeDistanceScaleAndBias(DirectionalLightData value)
{
return value.fadeDistanceScaleAndBias;
}
float GetUnused0(DirectionalLightData value)
{
return value.unused0;
}
float4 GetShadowMaskSelector(DirectionalLightData value)
{
return value.shadowMaskSelector;
}
//
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.LightData

{
return value.shadowDimmer;
}
int GetUnused0(LightData value)
bool GetDynamicShadowCasterOnly(LightData value)
return value.unused0;
return value.dynamicShadowCasterOnly;
}
float2 GetSize(LightData value)
{

float GetMinRoughness(LightData value)
{
return value.minRoughness;
}
float4 GetShadowMaskSelector(LightData value)
{
return value.shadowMaskSelector;
}
//

119
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/Deferred.compute


#pragma kernel Deferred_Direct_Fptl SHADE_OPAQUE_ENTRY=Deferred_Direct_Fptl USE_FPTL_LIGHTLIST
#pragma kernel Deferred_Direct_Fptl_DebugDisplay SHADE_OPAQUE_ENTRY=Deferred_Direct_Fptl_DebugDisplay USE_FPTL_LIGHTLIST DEBUG_DISPLAY
#pragma kernel Deferred_Direct_Clustered SHADE_OPAQUE_ENTRY=Deferred_Direct_Clustered USE_CLUSTERED_LIGHTLIST
#pragma kernel Deferred_Direct_Clustered_DebugDisplay SHADE_OPAQUE_ENTRY=Deferred_Direct_Clustered_DebugDisplay USE_CLUSTERED_LIGHTLIST DEBUG_DISPLAY
#pragma kernel Deferred_Direct_Fptl SHADE_OPAQUE_ENTRY=Deferred_Direct_Fptl USE_FPTL_LIGHTLIST
#pragma kernel Deferred_Direct_Fptl_DebugDisplay SHADE_OPAQUE_ENTRY=Deferred_Direct_Fptl_DebugDisplay USE_FPTL_LIGHTLIST DEBUG_DISPLAY
#pragma kernel Deferred_Direct_ShadowMask_Fptl SHADE_OPAQUE_ENTRY=Deferred_Direct_ShadowMask_Fptl USE_FPTL_LIGHTLIST SHADOWS_SHADOWMASK
#pragma kernel Deferred_Direct_ShadowMask_Fptl_DebugDisplay SHADE_OPAQUE_ENTRY=Deferred_Direct_ShadowMask_Fptl_DebugDisplay USE_FPTL_LIGHTLIST SHADOWS_SHADOWMASK DEBUG_DISPLAY
#pragma kernel Deferred_Direct_Clustered SHADE_OPAQUE_ENTRY=Deferred_Direct_Clustered USE_CLUSTERED_LIGHTLIST
#pragma kernel Deferred_Direct_Clustered_DebugDisplay SHADE_OPAQUE_ENTRY=Deferred_Direct_Clustered_DebugDisplay USE_CLUSTERED_LIGHTLIST DEBUG_DISPLAY
#pragma kernel Deferred_Direct_ShadowMask_Clustered SHADE_OPAQUE_ENTRY=Deferred_Direct_ShadowMask_Clustered USE_CLUSTERED_LIGHTLIST SHADOWS_SHADOWMASK
#pragma kernel Deferred_Direct_ShadowMask_Clustered_DebugDisplay SHADE_OPAQUE_ENTRY=Deferred_Direct_ShadowMask_Clustered_DebugDisplay USE_CLUSTERED_LIGHTLIST SHADOWS_SHADOWMASK DEBUG_DISPLAY
#pragma kernel Deferred_Indirect_Fptl_Variant0 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant0 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=0
#pragma kernel Deferred_Indirect_Fptl_Variant1 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant1 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=1
#pragma kernel Deferred_Indirect_Fptl_Variant2 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant2 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=2
#pragma kernel Deferred_Indirect_Fptl_Variant3 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant3 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=3
#pragma kernel Deferred_Indirect_Fptl_Variant4 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant4 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=4
#pragma kernel Deferred_Indirect_Fptl_Variant5 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant5 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=5
#pragma kernel Deferred_Indirect_Fptl_Variant6 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant6 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=6
#pragma kernel Deferred_Indirect_Fptl_Variant7 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant7 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=7
#pragma kernel Deferred_Indirect_Fptl_Variant8 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant8 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=8
#pragma kernel Deferred_Indirect_Fptl_Variant9 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant9 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=9
#pragma kernel Deferred_Indirect_Fptl_Variant10 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant10 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=10
#pragma kernel Deferred_Indirect_Fptl_Variant11 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant11 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=11
#pragma kernel Deferred_Indirect_Fptl_Variant12 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant12 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=12
#pragma kernel Deferred_Indirect_Fptl_Variant13 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant13 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=13
#pragma kernel Deferred_Indirect_Fptl_Variant14 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant14 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=14
#pragma kernel Deferred_Indirect_Fptl_Variant15 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant15 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=15
#pragma kernel Deferred_Indirect_Fptl_Variant16 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant16 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=16
#pragma kernel Deferred_Indirect_Fptl_Variant17 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant17 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=17
#pragma kernel Deferred_Indirect_Fptl_Variant18 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant18 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=18
#pragma kernel Deferred_Indirect_Fptl_Variant19 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant19 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=19
#pragma kernel Deferred_Indirect_Fptl_Variant20 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant20 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=20
#pragma kernel Deferred_Indirect_Fptl_Variant21 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant21 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=21
#pragma kernel Deferred_Indirect_Fptl_Variant22 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant22 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=22
#pragma kernel Deferred_Indirect_Fptl_Variant23 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant23 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=23
#pragma kernel Deferred_Indirect_Fptl_Variant24 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant24 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=24
#pragma kernel Deferred_Indirect_Fptl_Variant25 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant25 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=25
#pragma kernel Deferred_Indirect_Fptl_Variant26 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant26 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=26
// Variant with and without shadowmask
#pragma kernel Deferred_Indirect_Fptl_Variant0 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant0 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=0
#pragma kernel Deferred_Indirect_Fptl_Variant1 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant1 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=1
#pragma kernel Deferred_Indirect_Fptl_Variant2 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant2 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=2
#pragma kernel Deferred_Indirect_Fptl_Variant3 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant3 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=3
#pragma kernel Deferred_Indirect_Fptl_Variant4 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant4 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=4
#pragma kernel Deferred_Indirect_Fptl_Variant5 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant5 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=5
#pragma kernel Deferred_Indirect_Fptl_Variant6 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant6 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=6
#pragma kernel Deferred_Indirect_Fptl_Variant7 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant7 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=7
#pragma kernel Deferred_Indirect_Fptl_Variant8 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant8 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=8
#pragma kernel Deferred_Indirect_Fptl_Variant9 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant9 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=9
#pragma kernel Deferred_Indirect_Fptl_Variant10 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant10 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=10
#pragma kernel Deferred_Indirect_Fptl_Variant11 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant11 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=11
#pragma kernel Deferred_Indirect_Fptl_Variant12 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant12 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=12
#pragma kernel Deferred_Indirect_Fptl_Variant13 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant13 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=13
#pragma kernel Deferred_Indirect_Fptl_Variant14 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant14 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=14
#pragma kernel Deferred_Indirect_Fptl_Variant15 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant15 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=15
#pragma kernel Deferred_Indirect_Fptl_Variant16 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant16 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=16
#pragma kernel Deferred_Indirect_Fptl_Variant17 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant17 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=17
#pragma kernel Deferred_Indirect_Fptl_Variant18 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant18 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=18
#pragma kernel Deferred_Indirect_Fptl_Variant19 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant19 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=19
#pragma kernel Deferred_Indirect_Fptl_Variant20 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant20 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=20
#pragma kernel Deferred_Indirect_Fptl_Variant21 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant21 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=21
#pragma kernel Deferred_Indirect_Fptl_Variant22 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant22 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=22
#pragma kernel Deferred_Indirect_Fptl_Variant23 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant23 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=23
#pragma kernel Deferred_Indirect_Fptl_Variant24 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant24 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=24
#pragma kernel Deferred_Indirect_Fptl_Variant25 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant25 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=25
#pragma kernel Deferred_Indirect_Fptl_Variant26 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Fptl_Variant26 USE_FPTL_LIGHTLIST USE_INDIRECT VARIANT=26
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant0 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant0 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=0
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant1 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant1 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=1
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant2 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant2 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=2
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant3 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant3 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=3
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant4 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant4 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=4
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant5 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant5 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=5
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant6 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant6 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=6
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant7 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant7 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=7
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant8 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant8 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=8
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant9 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant9 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=9
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant10 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant10 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=10
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant11 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant11 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=11
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant12 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant12 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=12
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant13 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant13 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=13
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant14 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant14 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=14
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant15 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant15 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=15
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant16 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant16 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=16
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant17 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant17 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=17
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant18 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant18 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=18
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant19 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant19 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=19
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant20 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant20 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=20
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant21 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant21 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=21
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant22 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant22 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=22
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant23 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant23 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=23
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant24 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant24 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=24
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant25 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant25 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=25
#pragma kernel Deferred_Indirect_ShadowMask_Fptl_Variant26 SHADE_OPAQUE_ENTRY=Deferred_Indirect_ShadowMask_Fptl_Variant26 USE_FPTL_LIGHTLIST USE_INDIRECT SHADOWS_SHADOWMASK VARIANT=26
/* Tag: SUPPORT_COMPUTE_CLUSTER_OPAQUE - Uncomment this if you want to do cluster opaque with compute shader (by default we support only fptl on opaque)
#pragma kernel Deferred_Indirect_Clustered_Variant0 SHADE_OPAQUE_ENTRY=Deferred_Indirect_Clustered_Variant0 USE_CLUSTERED_LIGHTLIST USE_INDIRECT VARIANT=0

//-------------------------------------------------------------------------------------
DECLARE_GBUFFER_TEXTURE(_GBufferTexture);
#ifdef SHADOWS_SHADOWMASK
TEXTURE2D(_ShadowMaskTexture);
#endif
RWTexture2D<float3> diffuseLightingUAV;
RWTexture2D<float4> specularLightingUAV;

CBUFFER_END
#if USE_INDIRECT
#ifdef USE_INDIRECT
StructuredBuffer<uint> g_TileList;
// Indirect

{
uint2 tileCoord = (16 * groupId) / GetTileSize();
uint2 pixelCoord = dispatchThreadId;
uint featureFlags = 0xFFFFFFFF;
uint featureFlags = LIGHT_FEATURE_MASK_FLAGS_OPAQUE | MATERIAL_FEATURE_MASK_FLAGS;
#endif

FETCH_GBUFFER(gbuffer, _GBufferTexture, posInput.unPositionSS);
BSDFData bsdfData;
float3 bakeDiffuseLighting;
DECODE_FROM_GBUFFER(gbuffer, featureFlags, bsdfData, bakeDiffuseLighting);
BakeLightingData bakeLightingData;
DECODE_FROM_GBUFFER(gbuffer, featureFlags, bsdfData, bakeLightingData.bakeDiffuseLighting);
#ifdef SHADOWS_SHADOWMASK
DecodeShadowMask(LOAD_TEXTURE2D(_ShadowMaskTexture, posInput.unPositionSS), bakeLightingData.bakeShadowMask);
#endif
LightLoop(V, posInput, preLightData, bsdfData, bakeDiffuseLighting, featureFlags, diffuseLighting, specularLighting);
LightLoop(V, posInput, preLightData, bsdfData, bakeLightingData, featureFlags, diffuseLighting, specularLighting);
// We SSSSS is enabled with use split lighting.
// SSSSS algorithm need to know which pixels contribute to SSS and which doesn't. We could use the stencil for that but it mean that it will increase the cost of SSSSS
// A simpler solution is to add a slight contribution here that isn't visible (here we chose fp16 min (which is also fp11 and fp10 min).
// The SSSSS algorithm will check if diffuse lighting is black and discard the pixel if it is the case
diffuseLighting.r = max(diffuseLighting.r, HFLT_MIN);
diffuseLightingUAV[pixelCoord] = diffuseLighting;
diffuseLightingUAV[pixelCoord] = TagLightingForSSS(diffuseLighting);
}
else
{

502
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs


public enum LightFeatureFlags
{
// Light bit mask must match LightDefinitions.s_LightFeatureMaskFlags value
Punctual = 1 << 8,
Area = 1 << 9,
Directional = 1 << 10,
Env = 1 << 11,
Sky = 1 << 12,
SSL = 1 << 13 // If adding more light be sure to not overflow LightDefinitions.s_LightFeatureMaskFlags
Punctual = 1 << 12,
Area = 1 << 13,
Directional = 1 << 14,
Env = 1 << 15,
Sky = 1 << 16,
SSRefraction = 1 << 17,
SSReflection = 1 << 18,
// If adding more light be sure to not overflow LightDefinitions.s_LightFeatureMaskFlags
}
[GenerateHLSL]

public static int s_NumFeatureVariants = 27;
// Following define the maximum number of bits use in each feature category.
public static uint s_LightFeatureMaskFlags = 0xFF00;
public static uint s_MaterialFeatureMaskFlags = 0x00FF; // don't use all bits just to be safe from signed and/or float conversions :/
public static uint s_LightFeatureMaskFlags = 0xFFF000;
public static uint s_LightFeatureMaskFlagsOpaque = 0xFFF000 & ~((uint)LightFeatureFlags.SSRefraction); // Opaque don't support screen space refraction
public static uint s_LightFeatureMaskFlagsTransparent = 0xFFF000 & ~((uint)LightFeatureFlags.SSReflection); // Transparent don't support screen space reflection
public static uint s_MaterialFeatureMaskFlags = 0x000FFF; // don't use all bits just to be safe from signed and/or float conversions :/
}
[GenerateHLSL]

int m_punctualLightCount = 0;
int m_areaLightCount = 0;
int m_lightCount = 0;
bool m_enableBakeShadowMask = false; // Track if any light require shadow mask. In this case we will need to enable the keyword shadow mask
float m_maxShadowDistance = 0.0f; // Save value from shadow settings
private ComputeShader buildScreenAABBShader { get { return m_Resources.buildScreenAABBShader; } }
private ComputeShader buildPerTileLightListShader { get { return m_Resources.buildPerTileLightListShader; } }

static int s_BuildDispatchIndirectKernel;
static int s_BuildMaterialFlagsWriteKernel;
static int s_BuildMaterialFlagsOrKernel;
static int s_shadeOpaqueDirectShadowMaskClusteredKernel;
static int s_shadeOpaqueDirectShadowMaskFptlKernel;
static int s_shadeOpaqueDirectShadowMaskClusteredDebugDisplayKernel;
static int s_shadeOpaqueDirectShadowMaskFptlDebugDisplayKernel;
static int[] s_shadeOpaqueIndirectShadowMaskFptlKernels = new int[LightDefinitions.s_NumFeatureVariants];
static int s_deferredDirectionalShadowKernel;

}
}
Material m_DeferredAllMaterialSRT = null;
Material m_DeferredAllMaterialMRT = null;
Material m_DebugViewTilesMaterial = null;
Material m_SingleDeferredMaterialSRT = null;
Material m_SingleDeferredMaterialMRT = null;
// Following is an array of material of size eight for all combination of keyword: OUTPUT_SPLIT_LIGHTING - LIGHTLOOP_TILE_PASS - SHADOWS_SHADOWMASK - USE_FPTL_LIGHTLIST/USE_CLUSTERED_LIGHTLIST - DEBUG_DISPLAY
Material[, , , ,] m_lightingMaterial;
Material m_DebugViewTilesMaterial;
Light m_CurrentSunLight = null;
Light m_CurrentSunLight;
int m_CurrentSunLightShadowIndex = -1;
public Light GetCurrentSunLight() { return m_CurrentSunLight; }

s_shadeOpaqueDirectClusteredDebugDisplayKernel = deferredComputeShader.FindKernel("Deferred_Direct_Clustered_DebugDisplay");
s_shadeOpaqueDirectFptlDebugDisplayKernel = deferredComputeShader.FindKernel("Deferred_Direct_Fptl_DebugDisplay");
s_shadeOpaqueDirectShadowMaskClusteredKernel = deferredComputeShader.FindKernel("Deferred_Direct_ShadowMask_Clustered");
s_shadeOpaqueDirectShadowMaskFptlKernel = deferredComputeShader.FindKernel("Deferred_Direct_ShadowMask_Fptl");
s_shadeOpaqueDirectShadowMaskClusteredDebugDisplayKernel = deferredComputeShader.FindKernel("Deferred_Direct_ShadowMask_Clustered_DebugDisplay");
s_shadeOpaqueDirectShadowMaskFptlDebugDisplayKernel = deferredComputeShader.FindKernel("Deferred_Direct_ShadowMask_Fptl_DebugDisplay");
s_deferredDirectionalShadowKernel = deferredDirectionalShadowComputeShader.FindKernel("DeferredDirectionalShadow");
for (int variant = 0; variant < LightDefinitions.s_NumFeatureVariants; variant++)

s_shadeOpaqueIndirectFptlKernels[variant] = deferredComputeShader.FindKernel("Deferred_Indirect_Fptl_Variant" + variant);
s_shadeOpaqueIndirectShadowMaskFptlKernels[variant] = deferredComputeShader.FindKernel("Deferred_Indirect_ShadowMask_Fptl_Variant" + variant);
}
s_LightList = null;

m_DeferredAllMaterialSRT = CoreUtils.CreateEngineMaterial(m_Resources.deferredShader);
m_DeferredAllMaterialSRT.EnableKeyword("LIGHTLOOP_TILE_PASS");
m_DeferredAllMaterialSRT.DisableKeyword("OUTPUT_SPLIT_LIGHTING");
m_DeferredAllMaterialSRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.RegularLighting);
m_DeferredAllMaterialSRT.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
m_DeferredAllMaterialSRT.SetInt(HDShaderIDs._SrcBlend, (int)BlendMode.One);
m_DeferredAllMaterialSRT.SetInt(HDShaderIDs._DstBlend, (int)BlendMode.Zero);
m_DeferredAllMaterialMRT = CoreUtils.CreateEngineMaterial(m_Resources.deferredShader);
m_DeferredAllMaterialMRT.EnableKeyword("LIGHTLOOP_TILE_PASS");
m_DeferredAllMaterialMRT.EnableKeyword("OUTPUT_SPLIT_LIGHTING");
m_DeferredAllMaterialMRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.SplitLighting);
m_DeferredAllMaterialMRT.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
m_DeferredAllMaterialMRT.SetInt(HDShaderIDs._SrcBlend, (int)BlendMode.One);
m_DeferredAllMaterialMRT.SetInt(HDShaderIDs._DstBlend, (int)BlendMode.Zero);
// OUTPUT_SPLIT_LIGHTING - LIGHTLOOP_TILE_PASS - SHADOWS_SHADOWMASK - USE_FPTL_LIGHTLIST/USE_CLUSTERED_LIGHTLIST - DEBUG_DISPLAY
m_lightingMaterial = new Material[2, 2, 2, 2, 2];
m_SingleDeferredMaterialSRT = CoreUtils.CreateEngineMaterial(m_Resources.deferredShader);
m_SingleDeferredMaterialSRT.EnableKeyword("LIGHTLOOP_SINGLE_PASS");
m_SingleDeferredMaterialSRT.DisableKeyword("OUTPUT_SPLIT_LIGHTING");
m_SingleDeferredMaterialSRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.RegularLighting);
m_SingleDeferredMaterialSRT.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
m_SingleDeferredMaterialSRT.SetInt(HDShaderIDs._SrcBlend, (int)BlendMode.One);
m_SingleDeferredMaterialSRT.SetInt(HDShaderIDs._DstBlend, (int)BlendMode.Zero);
for (int outputSplitLighting = 0; outputSplitLighting < 2; ++outputSplitLighting)
{
for (int lightLoopTilePass = 0; lightLoopTilePass < 2; ++lightLoopTilePass)
{
for (int ShadowMask = 0; ShadowMask < 2; ++ShadowMask)
{
for (int clustered = 0; clustered < 2; ++clustered)
{
for (int debugDisplay = 0; debugDisplay < 2; ++debugDisplay)
{
m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay] = CoreUtils.CreateEngineMaterial(m_Resources.deferredShader);
CoreUtils.SetKeyword(m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay], "OUTPUT_SPLIT_LIGHTING", outputSplitLighting == 1);
CoreUtils.SelectKeyword(m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay], "LIGHTLOOP_TILE_PASS", "LIGHTLOOP_SINGLE_PASS", lightLoopTilePass == 1);
CoreUtils.SetKeyword(m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay], "SHADOWS_SHADOWMASK", ShadowMask == 1);
CoreUtils.SelectKeyword(m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay], "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", clustered == 1);
CoreUtils.SetKeyword(m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay], "DEBUG_DISPLAY", debugDisplay == 1);
m_SingleDeferredMaterialMRT = CoreUtils.CreateEngineMaterial(m_Resources.deferredShader);
m_SingleDeferredMaterialMRT.EnableKeyword("LIGHTLOOP_SINGLE_PASS");
m_SingleDeferredMaterialMRT.EnableKeyword("OUTPUT_SPLIT_LIGHTING");
m_SingleDeferredMaterialMRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.SplitLighting);
m_SingleDeferredMaterialMRT.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
m_SingleDeferredMaterialMRT.SetInt(HDShaderIDs._SrcBlend, (int)BlendMode.One);
m_SingleDeferredMaterialMRT.SetInt(HDShaderIDs._DstBlend, (int)BlendMode.Zero);
m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay].SetInt(HDShaderIDs._StencilRef, outputSplitLighting == 1 ? (int)StencilLightingUsage.SplitLighting : (int)StencilLightingUsage.RegularLighting);
m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay].SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay].SetInt(HDShaderIDs._SrcBlend, (int)BlendMode.One);
m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay].SetInt(HDShaderIDs._DstBlend, (int)BlendMode.Zero);
}
}
}
}
}
m_DebugViewTilesMaterial = CoreUtils.CreateEngineMaterial(m_Resources.debugViewTilesShader);

// enableClustered
CoreUtils.SafeRelease(s_GlobalLightListAtomic);
CoreUtils.Destroy(m_DeferredAllMaterialSRT);
CoreUtils.Destroy(m_DeferredAllMaterialMRT);
for (int outputSplitLighting = 0; outputSplitLighting < 2; ++outputSplitLighting)
{
for (int lightLoopTilePass = 0; lightLoopTilePass < 2; ++lightLoopTilePass)
{
for (int ShadowMask = 0; ShadowMask < 2; ++ShadowMask)
{
for (int clustered = 0; clustered < 2; ++clustered)
{
for (int debugDisplay = 0; debugDisplay < 2; ++debugDisplay)
{
CoreUtils.Destroy(m_lightingMaterial[outputSplitLighting, lightLoopTilePass, ShadowMask, clustered, debugDisplay]);
}
}
}
}
}
CoreUtils.Destroy(m_SingleDeferredMaterialSRT);
CoreUtils.Destroy(m_SingleDeferredMaterialMRT);
}
public void NewFrame()

m_CurrentSunLight = light.light;
m_CurrentSunLightShadowIndex = shadowIdx;
}
// TODO: Currently m_maxShadowDistance is based on shadow settings, but this value is define for a whole level. We should be able to change this value during gameplay
float scale;
float bias;
GetSCaleAndBiasForLinearDistanceFade(m_maxShadowDistance, out scale, out bias);
directionalLightData.fadeDistanceScaleAndBias = new Vector2(scale, bias);
directionalLightData.shadowMaskSelector = Vector4.zero;
if (IsBakedShadowMaskLight(light.light))
{
directionalLightData.shadowMaskSelector[light.light.bakingOutput.occlusionMaskChannel] = 1.0f;
// TODO: make this option per light, not global
directionalLightData.dynamicShadowCasterOnly = QualitySettings.shadowmaskMode == ShadowmaskMode.Shadowmask;
}
else
{
// use -1 to say that we don't use shadow mask
directionalLightData.shadowMaskSelector.x = -1.0f;
directionalLightData.dynamicShadowCasterOnly = false;
}
m_CurrentSunLight = m_CurrentSunLight == null ? light.light : m_CurrentSunLight;
m_lightList.directionalLights.Add(directionalLightData);

float ComputeLinearDistanceFade(float distanceToCamera, float fadeDistance)
void GetSCaleAndBiasForLinearDistanceFade(float fadeDistance, out float scale, out float bias)
return 1.0f - Mathf.Clamp01((distanceToCamera - distanceFadeNear) / (fadeDistance - distanceFadeNear));
scale = 1.0f / (fadeDistance - distanceFadeNear);
bias = - distanceFadeNear / (fadeDistance - distanceFadeNear);
}
float ComputeLinearDistanceFade(float distanceToCamera, float fadeDistance)
{
float scale;
float bias;
GetSCaleAndBiasForLinearDistanceFade(fadeDistance, out scale, out bias);
return 1.0f - Mathf.Clamp01(distanceToCamera * scale + bias);
}
public bool GetLightData(ShadowSettings shadowSettings, Camera camera, GPULightType gpuLightType, VisibleLight light, HDAdditionalLightData additionalLightData, AdditionalShadowData additionalshadowData, int lightIndex)

// Value of max smoothness is from artists point of view, need to convert from perceptual smoothness to roughness
lightData.minRoughness = (1.0f - additionalLightData.maxSmoothness) * (1.0f - additionalLightData.maxSmoothness);
lightData.shadowMaskSelector = Vector4.zero;
if (IsBakedShadowMaskLight(light.light))
{
lightData.shadowMaskSelector[light.light.bakingOutput.occlusionMaskChannel] = 1.0f;
// TODO: make this option per light, not global
lightData.dynamicShadowCasterOnly = QualitySettings.shadowmaskMode == ShadowmaskMode.Shadowmask;
}
else
{
// use -1 to say that we don't use shadow mask
lightData.shadowMaskSelector.x = -1.0f;
lightData.dynamicShadowCasterOnly = false;
}
m_lightList.lights.Add(lightData);

m_ShadowMgr.UpdateCullingParameters( ref cullingParams );
}
public void PrepareLightsForGPU(ShadowSettings shadowSettings, CullResults cullResults, Camera camera)
public bool IsBakedShadowMaskLight(Light light)
{
return light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed &&
light.bakingOutput.mixedLightingMode == MixedLightingMode.Shadowmask &&
light.bakingOutput.occlusionMaskChannel != -1; // We need to have an occlusion mask channel assign, else we have no shadow mask
}
// Return true if BakedShadowMask are enabled
public bool PrepareLightsForGPU(ShadowSettings shadowSettings, CullResults cullResults, Camera camera)
// If any light require it, we need to enabled bake shadow mask feature
m_enableBakeShadowMask = false;
m_lightList.Clear();
Vector3 camPosWS = camera.transform.position;

// Debug.Assert(additionalData == null, "Missing HDAdditionalData on a light - Should have been create by HDLightEditor");
if (additionalData == null)
return;
return false;
LightCategory lightCategory = LightCategory.Count;
GPULightType gpuLightType = GPULightType.Point;

int lightIndex = (int)(sortKey & 0xFFFF);
var light = cullResults.visibleLights[lightIndex];
m_enableBakeShadowMask = m_enableBakeShadowMask || IsBakedShadowMaskLight(light.light);
var additionalLightData = light.light.GetComponent<HDAdditionalLightData>();
var additionalShadowData = light.light.GetComponent<AdditionalShadowData>(); // Can be null

Debug.Assert(m_lightList.lightVolumes.Count == m_lightCount);
UpdateDataBuffers();
m_maxShadowDistance = shadowSettings.maxShadowDistance;
return m_enableBakeShadowMask;
}
void VoxelLightListGeneration(CommandBuffer cmd, Camera camera, Matrix4x4 projscr, Matrix4x4 invProjscr, RenderTargetIdentifier cameraDepthBufferRT)

cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture1, HDShaderIDs._GBufferTexture1);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture2, HDShaderIDs._GBufferTexture2);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._GBufferTexture3, HDShaderIDs._GBufferTexture3);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._ShadowMaskTexture, HDShaderIDs._ShadowMaskTexture);
cmd.SetComputeTextureParam(buildMaterialFlagsShader, buildMaterialFlagsKernel, HDShaderIDs._VelocityTexture, HDShaderIDs._VelocityTexture);
cmd.DispatchCompute(buildMaterialFlagsShader, buildMaterialFlagsKernel, numTilesX, numTilesY, 1);
}

m_ShadowMgr.RenderShadows(m_FrameId, renderContext, cmd, cullResults, cullResults.visibleLights);
}
private void SetupDebugDisplayMode(bool debugDisplayEnable)
{
CoreUtils.SetKeyword(m_DeferredAllMaterialSRT, "DEBUG_DISPLAY", debugDisplayEnable);
CoreUtils.SetKeyword(m_DeferredAllMaterialMRT, "DEBUG_DISPLAY", debugDisplayEnable);
CoreUtils.SetKeyword(m_SingleDeferredMaterialSRT, "DEBUG_DISPLAY", debugDisplayEnable);
CoreUtils.SetKeyword(m_SingleDeferredMaterialMRT, "DEBUG_DISPLAY", debugDisplayEnable);
}
public void RenderLightingDebug(HDCamera hdCamera, CommandBuffer cmd, RenderTargetIdentifier colorBuffer, DebugDisplaySettings debugDisplaySettings)
{
LightingDebugSettings lightingDebug = debugDisplaySettings.lightingDebugSettings;

public struct LightingPassOptions
{
public bool outputSplitLighting;
public bool volumetricLightingEnabled;
}
public void RenderDeferredDirectionalShadow(HDCamera hdCamera, RenderTargetIdentifier deferredShadowRT, RenderTargetIdentifier depthTexture, CommandBuffer cmd)

{
var camera = hdCamera.camera;
SetupDebugDisplayMode(debugDisplaySettings.IsDebugDisplayEnabled());
if (!m_TileSettings.enableTileAndCluster)
{
PushGlobalParams(camera, cmd, null, 0);
// This is a debug brute force renderer to debug tile/cluster which render all the lights
if (options.outputSplitLighting)
{
CoreUtils.DrawFullScreen(cmd, m_SingleDeferredMaterialMRT, colorBuffers, depthStencilBuffer);
}
else
{
// If SSS is disable, do lighting for both split lighting and no split lighting
if (!debugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)
{
m_SingleDeferredMaterialSRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.NoLighting);
m_SingleDeferredMaterialSRT.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.NotEqual);
}
else
{
m_SingleDeferredMaterialSRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.RegularLighting);
m_SingleDeferredMaterialSRT.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
}
CoreUtils.DrawFullScreen(cmd, m_SingleDeferredMaterialSRT, colorBuffers[0], depthStencilBuffer);
}
}
else
// Compute path
if (m_TileSettings.enableTileAndCluster && m_TileSettings.enableComputeLightEvaluation)
{
int w = camera.pixelWidth;
int h = camera.pixelHeight;

if (m_TileSettings.enableComputeLightEvaluation)
{
bool enableFeatureVariants = GetFeatureVariantsEnabled(m_TileSettings) && !debugDisplaySettings.IsDebugDisplayEnabled();
bool enableFeatureVariants = GetFeatureVariantsEnabled(m_TileSettings) && !debugDisplaySettings.IsDebugDisplayEnabled();
int numVariants = 1;
if (enableFeatureVariants)
numVariants = LightDefinitions.s_NumFeatureVariants;
int numVariants = 1;
if (enableFeatureVariants)
numVariants = LightDefinitions.s_NumFeatureVariants;
int debugViewMaterial = Shader.GetGlobalInt(HDShaderIDs._DebugViewMaterial);
int debugLightingMode = Shader.GetGlobalInt(HDShaderIDs._DebugLightingMode);
Vector4 debugLightingAlbedo = Shader.GetGlobalVector(HDShaderIDs._DebugLightingAlbedo);
Vector4 debugLightingSmoothness = Shader.GetGlobalVector(HDShaderIDs._DebugLightingSmoothness);
int debugViewMaterial = Shader.GetGlobalInt(HDShaderIDs._DebugViewMaterial);
int debugLightingMode = Shader.GetGlobalInt(HDShaderIDs._DebugLightingMode);
Vector4 debugLightingAlbedo = Shader.GetGlobalVector(HDShaderIDs._DebugLightingAlbedo);
Vector4 debugLightingSmoothness = Shader.GetGlobalVector(HDShaderIDs._DebugLightingSmoothness);
Texture ltcData = Shader.GetGlobalTexture(HDShaderIDs._LtcData);
Texture preIntegratedFGD = Shader.GetGlobalTexture(HDShaderIDs._PreIntegratedFGD);
Texture ltcGGXMatrix = Shader.GetGlobalTexture(HDShaderIDs._LtcGGXMatrix);
Texture ltcDisneyDiffuseMatrix = Shader.GetGlobalTexture(HDShaderIDs._LtcDisneyDiffuseMatrix);
Texture ltcMultiGGXFresnelDisneyDiffuse = Shader.GetGlobalTexture(HDShaderIDs._LtcMultiGGXFresnelDisneyDiffuse);
Texture ltcData = Shader.GetGlobalTexture(HDShaderIDs._LtcData);
Texture preIntegratedFGD = Shader.GetGlobalTexture(HDShaderIDs._PreIntegratedFGD);
Texture ltcGGXMatrix = Shader.GetGlobalTexture(HDShaderIDs._LtcGGXMatrix);
Texture ltcDisneyDiffuseMatrix = Shader.GetGlobalTexture(HDShaderIDs._LtcDisneyDiffuseMatrix);
Texture ltcMultiGGXFresnelDisneyDiffuse = Shader.GetGlobalTexture(HDShaderIDs._LtcMultiGGXFresnelDisneyDiffuse);
Matrix4x4 invScrProjection = Shader.GetGlobalMatrix(HDShaderIDs.g_mInvScrProjection);
int useTileLightList = Shader.GetGlobalInt(HDShaderIDs._UseTileLightList);
Matrix4x4 invScrProjection = Shader.GetGlobalMatrix(HDShaderIDs.g_mInvScrProjection);
int useTileLightList = Shader.GetGlobalInt(HDShaderIDs._UseTileLightList);
Vector4 time = Shader.GetGlobalVector(HDShaderIDs._Time);
Vector4 sinTime = Shader.GetGlobalVector(HDShaderIDs._SinTime);
Vector4 cosTime = Shader.GetGlobalVector(HDShaderIDs._CosTime);
Vector4 unity_DeltaTime = Shader.GetGlobalVector(HDShaderIDs.unity_DeltaTime);
int envLightSkyEnabled = Shader.GetGlobalInt(HDShaderIDs._EnvLightSkyEnabled);
Vector4 ambientOcclusionParam = Shader.GetGlobalVector(HDShaderIDs._AmbientOcclusionParam);
Vector4 time = Shader.GetGlobalVector(HDShaderIDs._Time);
Vector4 sinTime = Shader.GetGlobalVector(HDShaderIDs._SinTime);
Vector4 cosTime = Shader.GetGlobalVector(HDShaderIDs._CosTime);
Vector4 unity_DeltaTime = Shader.GetGlobalVector(HDShaderIDs.unity_DeltaTime);
int envLightSkyEnabled = Shader.GetGlobalInt(HDShaderIDs._EnvLightSkyEnabled);
Vector4 ambientOcclusionParam = Shader.GetGlobalVector(HDShaderIDs._AmbientOcclusionParam);
int enableSSSAndTransmission = Shader.GetGlobalInt(HDShaderIDs._EnableSSSAndTransmission);
int texturingModeFlags = Shader.GetGlobalInt(HDShaderIDs._TexturingModeFlags);
int transmissionFlags = Shader.GetGlobalInt(HDShaderIDs._TransmissionFlags);
int useDisneySSS = Shader.GetGlobalInt(HDShaderIDs._UseDisneySSS);
Vector4[] thicknessRemaps = Shader.GetGlobalVectorArray(HDShaderIDs._ThicknessRemaps);
Vector4[] shapeParams = Shader.GetGlobalVectorArray(HDShaderIDs._ShapeParams);
Vector4[] transmissionTints = Shader.GetGlobalVectorArray(HDShaderIDs._TransmissionTints);
Vector4[] halfRcpVariancesAndWeights = Shader.GetGlobalVectorArray(HDShaderIDs._HalfRcpVariancesAndWeights);
int enableSSSAndTransmission = Shader.GetGlobalInt(HDShaderIDs._EnableSSSAndTransmission);
int texturingModeFlags = Shader.GetGlobalInt(HDShaderIDs._TexturingModeFlags);
int transmissionFlags = Shader.GetGlobalInt(HDShaderIDs._TransmissionFlags);
int useDisneySSS = Shader.GetGlobalInt(HDShaderIDs._UseDisneySSS);
Vector4[] thicknessRemaps = Shader.GetGlobalVectorArray(HDShaderIDs._ThicknessRemaps);
Vector4[] shapeParams = Shader.GetGlobalVectorArray(HDShaderIDs._ShapeParams);
Vector4[] transmissionTints = Shader.GetGlobalVectorArray(HDShaderIDs._TransmissionTints);
Vector4[] halfRcpVariancesAndWeights = Shader.GetGlobalVectorArray(HDShaderIDs._HalfRcpVariancesAndWeights);
Texture skyTexture = Shader.GetGlobalTexture(HDShaderIDs._SkyTexture);
float skyTextureMipCount = Shader.GetGlobalFloat(HDShaderIDs._SkyTextureMipCount);
Texture skyTexture = Shader.GetGlobalTexture(HDShaderIDs._SkyTexture);
float skyTextureMipCount = Shader.GetGlobalFloat(HDShaderIDs._SkyTextureMipCount);
for (int variant = 0; variant < numVariants; variant++)
{
int kernel;
for (int variant = 0; variant < numVariants; variant++)
{
int kernel;
if (enableFeatureVariants)
{
// Tag: SUPPORT_COMPUTE_CLUSTER_OPAQUE - Uncomment this if you want to do cluster opaque with compute shader (by default we support only fptl on opaque)
// kernel = usingFptl ? s_shadeOpaqueIndirectFptlKernels[variant] : s_shadeOpaqueIndirectClusteredKernels[variant];
kernel = s_shadeOpaqueIndirectFptlKernels[variant];
}
if (enableFeatureVariants)
{
// Tag: SUPPORT_COMPUTE_CLUSTER_OPAQUE - Update the code with following comment this if you want to do cluster opaque with compute shader (by default we support only fptl on opaque)
// kernel = usingFptl ? s_shadeOpaqueIndirectFptlKernels[variant] : s_shadeOpaqueIndirectClusteredKernels[variant];
if (m_enableBakeShadowMask)
kernel = s_shadeOpaqueIndirectShadowMaskFptlKernels[variant];
kernel = s_shadeOpaqueIndirectFptlKernels[variant];
}
else
{
if (m_enableBakeShadowMask)
{
}
{
}
else
{
if (debugDisplaySettings.IsDebugDisplayEnabled())
kernel = usingFptl ? s_shadeOpaqueDirectShadowMaskFptlDebugDisplayKernel : s_shadeOpaqueDirectShadowMaskClusteredDebugDisplayKernel;
else
kernel = usingFptl ? s_shadeOpaqueDirectShadowMaskFptlKernel : s_shadeOpaqueDirectShadowMaskClusteredKernel;
}
}
// Pass global parameters to compute shader
// TODO: get rid of this by making global parameters visible to compute shaders
PushGlobalParams(camera, cmd, deferredComputeShader, kernel);
hdCamera.SetupComputeShader(deferredComputeShader, cmd);
// Pass global parameters to compute shader
// TODO: get rid of this by making global parameters visible to compute shaders
PushGlobalParams(camera, cmd, deferredComputeShader, kernel);
hdCamera.SetupComputeShader(deferredComputeShader, cmd);
// TODO: Update value like in ApplyDebugDisplaySettings() call. Sadly it is high likely that this will not be keep in sync. we really need to get rid of this by making global parameters visible to compute shaders
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._DebugViewMaterial, debugViewMaterial);
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._DebugLightingMode, debugLightingMode);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._DebugLightingAlbedo, debugLightingAlbedo);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._DebugLightingSmoothness, debugLightingSmoothness);
// TODO: Update value like in ApplyDebugDisplaySettings() call. Sadly it is high likely that this will not be keep in sync. we really need to get rid of this by making global parameters visible to compute shaders
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._DebugViewMaterial, debugViewMaterial);
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._DebugLightingMode, debugLightingMode);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._DebugLightingAlbedo, debugLightingAlbedo);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._DebugLightingSmoothness, debugLightingSmoothness);
cmd.SetComputeBufferParam(deferredComputeShader, kernel, HDShaderIDs.g_vLightListGlobal, bUseClusteredForDeferred ? s_PerVoxelLightLists : s_LightList);
cmd.SetComputeBufferParam(deferredComputeShader, kernel, HDShaderIDs.g_vLightListGlobal, bUseClusteredForDeferred ? s_PerVoxelLightLists : s_LightList);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._DeferredShadowTexture, deferredShadowTexture);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._DeferredShadowTexture, deferredShadowTexture);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._MainDepthTexture, depthTexture);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._MainDepthTexture, depthTexture);
// TODO: Don't know why but If we use Shader.GetGlobalTexture(HDShaderIDs._GBufferTexture0) instead of HDShaderIDs._GBufferTexture0 the screen start to flicker in SceneView...
// Need to investigate what is happening. But this may be unnecessary as development of SetGlobalTexture for compute shader have begin
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture0, HDShaderIDs._GBufferTexture0);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture1, HDShaderIDs._GBufferTexture1);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture2, HDShaderIDs._GBufferTexture2);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture3, HDShaderIDs._GBufferTexture3);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._ShadowMaskTexture, HDShaderIDs._ShadowMaskTexture);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._VelocityTexture, HDShaderIDs._VelocityTexture);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._AmbientOcclusionTexture, HDShaderIDs._AmbientOcclusionTexture);
// TODO: Don't know why but If we use Shader.GetGlobalTexture(HDShaderIDs._GBufferTexture0) instead of HDShaderIDs._GBufferTexture0 the screen start to flicker in SceneView...
// Need to investigate what is happening. But this may be unnecessary as development of SetGlobalTexture for compute shader have begin
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture0, HDShaderIDs._GBufferTexture0);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture1, HDShaderIDs._GBufferTexture1);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture2, HDShaderIDs._GBufferTexture2);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._GBufferTexture3, HDShaderIDs._GBufferTexture3);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._AmbientOcclusionTexture, HDShaderIDs._AmbientOcclusionTexture);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcData, ltcData);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._PreIntegratedFGD, preIntegratedFGD);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcGGXMatrix, ltcGGXMatrix);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcDisneyDiffuseMatrix, ltcDisneyDiffuseMatrix);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcMultiGGXFresnelDisneyDiffuse, ltcMultiGGXFresnelDisneyDiffuse);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcData, ltcData);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._PreIntegratedFGD, preIntegratedFGD);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcGGXMatrix, ltcGGXMatrix);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcDisneyDiffuseMatrix, ltcDisneyDiffuseMatrix);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._LtcMultiGGXFresnelDisneyDiffuse, ltcMultiGGXFresnelDisneyDiffuse);
cmd.SetComputeMatrixParam(deferredComputeShader, HDShaderIDs.g_mInvScrProjection, invScrProjection);
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._UseTileLightList, useTileLightList);
cmd.SetComputeMatrixParam(deferredComputeShader, HDShaderIDs.g_mInvScrProjection, invScrProjection);
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._UseTileLightList, useTileLightList);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._Time, time);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._SinTime, sinTime);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._CosTime, cosTime);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs.unity_DeltaTime, unity_DeltaTime);
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._EnvLightSkyEnabled, envLightSkyEnabled);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._AmbientOcclusionParam, ambientOcclusionParam);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._Time, time);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._SinTime, sinTime);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._CosTime, cosTime);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs.unity_DeltaTime, unity_DeltaTime);
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs._EnvLightSkyEnabled, envLightSkyEnabled);
cmd.SetComputeVectorParam(deferredComputeShader, HDShaderIDs._AmbientOcclusionParam, ambientOcclusionParam);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._SkyTexture, skyTexture ? skyTexture : m_DefaultTexture2DArray);
cmd.SetComputeFloatParam(deferredComputeShader, HDShaderIDs._SkyTextureMipCount, skyTextureMipCount);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs._SkyTexture, skyTexture ? skyTexture : m_DefaultTexture2DArray);
cmd.SetComputeFloatParam(deferredComputeShader, HDShaderIDs._SkyTextureMipCount, skyTextureMipCount);
// Set SSS parameters.
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._EnableSSSAndTransmission, enableSSSAndTransmission);
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._TexturingModeFlags, texturingModeFlags);
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._TransmissionFlags, transmissionFlags);
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._UseDisneySSS, useDisneySSS);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._ThicknessRemaps, thicknessRemaps);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._ShapeParams, shapeParams);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._TransmissionTints, transmissionTints);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._HalfRcpVariancesAndWeights, halfRcpVariancesAndWeights);
// Set SSS parameters.
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._EnableSSSAndTransmission, enableSSSAndTransmission);
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._TexturingModeFlags, texturingModeFlags);
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._TransmissionFlags, transmissionFlags);
cmd.SetComputeIntParam( deferredComputeShader, HDShaderIDs._UseDisneySSS, useDisneySSS);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._ThicknessRemaps, thicknessRemaps);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._ShapeParams, shapeParams);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._TransmissionTints, transmissionTints);
cmd.SetComputeVectorArrayParam(deferredComputeShader, HDShaderIDs._HalfRcpVariancesAndWeights, halfRcpVariancesAndWeights);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs.specularLightingUAV, colorBuffers[0]);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs.diffuseLightingUAV, colorBuffers[1]);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs.specularLightingUAV, colorBuffers[0]);
cmd.SetComputeTextureParam(deferredComputeShader, kernel, HDShaderIDs.diffuseLightingUAV, colorBuffers[1]);
// always do deferred lighting in blocks of 16x16 (not same as tiled light size)
HDRenderPipeline.SetGlobalVolumeProperties(options.volumetricLightingEnabled, cmd, deferredComputeShader);
if (enableFeatureVariants)
{
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs.g_TileListOffset, variant * numTiles);
cmd.SetComputeBufferParam(deferredComputeShader, kernel, HDShaderIDs.g_TileList, s_TileList);
cmd.DispatchCompute(deferredComputeShader, kernel, s_DispatchIndirectBuffer, (uint)variant * 3 * sizeof(uint));
}
else
{
cmd.DispatchCompute(deferredComputeShader, kernel, numTilesX, numTilesY, 1);
}
}
}
else // Pixel shader evaluation
{
// OUTPUT_SPLIT_LIGHTING - LIGHTLOOP_TILE_PASS - SHADOWS_SHADOWMASK - USE_FPTL_LIGHTLIST/USE_CLUSTERED_LIGHTLIST - DEBUG_DISPLAY
Material currentLightingMaterial = m_lightingMaterial[options.outputSplitLighting ? 1 : 0,
m_TileSettings.enableTileAndCluster ? 1 : 0,
m_enableBakeShadowMask ? 1 : 0,
bUseClusteredForDeferred ? 1 : 0,
debugDisplaySettings.IsDebugDisplayEnabled() ? 1 : 0];
// always do deferred lighting in blocks of 16x16 (not same as tiled light size)
PushGlobalParams(camera, cmd, null, 0);
if (enableFeatureVariants)
{
cmd.SetComputeIntParam(deferredComputeShader, HDShaderIDs.g_TileListOffset, variant * numTiles);
cmd.SetComputeBufferParam(deferredComputeShader, kernel, HDShaderIDs.g_TileList, s_TileList);
cmd.DispatchCompute(deferredComputeShader, kernel, s_DispatchIndirectBuffer, (uint)variant * 3 * sizeof(uint));
}
else
{
cmd.DispatchCompute(deferredComputeShader, kernel, numTilesX, numTilesY, 1);
}
}
if (options.outputSplitLighting)
{
CoreUtils.DrawFullScreen(cmd, currentLightingMaterial, colorBuffers, depthStencilBuffer);
// Pixel shader evaluation
PushGlobalParams(camera, cmd, null, 0);
if (options.outputSplitLighting)
// If SSS is disable, do lighting for both split lighting and no split lighting
// This is for debug purpose, so fine to use immediate material mode here to modify render state
if (!debugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)
CoreUtils.SelectKeyword(m_DeferredAllMaterialMRT, "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", bUseClusteredForDeferred);
CoreUtils.DrawFullScreen(cmd, m_DeferredAllMaterialMRT, colorBuffers, depthStencilBuffer);
currentLightingMaterial.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.NoLighting);
currentLightingMaterial.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.NotEqual);
// If SSS is disable, do lighting for both split lighting and no split lighting
if (!debugDisplaySettings.renderingDebugSettings.enableSSSAndTransmission)
{
m_DeferredAllMaterialSRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.NoLighting);
m_DeferredAllMaterialSRT.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.NotEqual);
}
else
{
m_DeferredAllMaterialSRT.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.RegularLighting);
m_DeferredAllMaterialSRT.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
}
currentLightingMaterial.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.RegularLighting);
currentLightingMaterial.SetInt(HDShaderIDs._StencilCmp, (int)CompareFunction.Equal);
}
CoreUtils.SelectKeyword(m_DeferredAllMaterialSRT, "USE_CLUSTERED_LIGHTLIST", "USE_FPTL_LIGHTLIST", bUseClusteredForDeferred);
CoreUtils.DrawFullScreen(cmd, m_DeferredAllMaterialSRT, colorBuffers[0], depthStencilBuffer);
}
CoreUtils.DrawFullScreen(cmd, currentLightingMaterial, colorBuffers[0], depthStencilBuffer);
} // TilePass - Deferred Lighting Pass
} // End profiling
// Note: SHADOWS_SHADOWMASK keyword is enabled in HDRenderPipeline.cs ConfigureForShadowMask
// Note: if we use render opaque with deferred tiling we need to render a opaque depth pass for these opaque objects
if (!m_TileSettings.enableTileAndCluster)

19
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs.hlsl


//
// UnityEngine.Experimental.Rendering.HDPipeline.TilePass.LightFeatureFlags: static fields
//
#define LIGHTFEATUREFLAGS_PUNCTUAL (256)
#define LIGHTFEATUREFLAGS_AREA (512)
#define LIGHTFEATUREFLAGS_DIRECTIONAL (1024)
#define LIGHTFEATUREFLAGS_ENV (2048)
#define LIGHTFEATUREFLAGS_SKY (4096)
#define LIGHTFEATUREFLAGS_SSL (8192)
#define LIGHTFEATUREFLAGS_PUNCTUAL (4096)
#define LIGHTFEATUREFLAGS_AREA (8192)
#define LIGHTFEATUREFLAGS_DIRECTIONAL (16384)
#define LIGHTFEATUREFLAGS_ENV (32768)
#define LIGHTFEATUREFLAGS_SKY (65536)
#define LIGHTFEATUREFLAGS_SSREFRACTION (131072)
#define LIGHTFEATUREFLAGS_SSREFLECTION (262144)
//
// UnityEngine.Experimental.Rendering.HDPipeline.TilePass.LightDefinitions: static fields

#define TILE_SIZE_FPTL (16)
#define TILE_SIZE_CLUSTERED (32)
#define NUM_FEATURE_VARIANTS (27)
#define LIGHT_FEATURE_MASK_FLAGS (65280)
#define MATERIAL_FEATURE_MASK_FLAGS (255)
#define LIGHT_FEATURE_MASK_FLAGS (16773120)
#define LIGHT_FEATURE_MASK_FLAGS_OPAQUE (16642048)
#define LIGHT_FEATURE_MASK_FLAGS_TRANSPARENT (16510976)
#define MATERIAL_FEATURE_MASK_FLAGS (4095)
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.TilePass.SFiniteLightBound
// PackingRules = Exact

18
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.hlsl


ShadowContext shadowContext;
};
// Store all the accumulated lighting produce by the light loop
struct LightLoopAccumulatedLighting
{
float3 dirDiffuseLighting;
float3 dirSpecularLighting;
float3 punctualDiffuseLighting;
float3 punctualSpecularLighting;
float3 areaDiffuseLighting;
float3 areaSpecularLighting;
float3 envDiffuseLighting;
float3 envSpecularLighting;
float envDiffuseLightingWeight;
};
//-----------------------------------------------------------------------------
// Cookie sampling functions
// ----------------------------------------------------------------------------

151
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePassLoop.hlsl


#endif // LIGHTLOOP_TILE_PASS
void applyWeigthedIblLighting(float3 localDiffuseLighting, float3 localSpecularLighting, float2 weight, inout float3 iblDiffuseLighting, inout float3 iblSpecularLighting, inout float totalIblWeight)
{
// IBL weights should not exceed 1.
float accumulatedWeight = totalIblWeight + weight.y;
totalIblWeight = saturate(accumulatedWeight);
weight.y -= saturate(accumulatedWeight - totalIblWeight);
iblDiffuseLighting = lerp(iblDiffuseLighting, localDiffuseLighting, weight.x);
iblSpecularLighting = lerp(iblSpecularLighting, localSpecularLighting, weight.y);
}
void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BSDFData bsdfData, float3 bakeDiffuseLighting, uint featureFlags,
void LightLoop( float3 V, PositionInputs posInput, PreLightData preLightData, BSDFData bsdfData, BakeLightingData bakeLightingData, uint featureFlags,
out float3 diffuseLighting,
out float3 specularLighting)
{

// This struct is use to store accumulated lighting, summation is done in PostEvaluateBSDF
LightLoopAccumulatedLighting accLighting;
ZERO_INITIALIZE(LightLoopAccumulatedLighting, accLighting);
// This struct is define in the material. the Lightloop must not access it
// PostEvaluateBSDF call at the end will convert Lighting to diffuse and specular lighting
AggregateLighting aggregateLighting;
ZERO_INITIALIZE(AggregateLighting, aggregateLighting); // LightLoop is in charge of initializing the struct
uint i = 0; // Declare once to avoid the D3D11 compiler warning.

{
float3 localDiffuseLighting, localSpecularLighting;
EvaluateBSDF_Directional(context, V, posInput, preLightData, _DirectionalLightDatas[i], bsdfData,
localDiffuseLighting, localSpecularLighting);
accLighting.dirDiffuseLighting += localDiffuseLighting;
accLighting.dirSpecularLighting += localSpecularLighting;
DirectLighting lighting = EvaluateBSDF_Directional(context, V, posInput, preLightData, _DirectionalLightDatas[i], bsdfData, bakeLightingData);
AccumulateDirectLighting(lighting, aggregateLighting);
}
}

for (i = 0; i < punctualLightCount; ++i)
{
float3 localDiffuseLighting, localSpecularLighting;
EvaluateBSDF_Punctual( context, V, posInput, preLightData, _LightDatas[punctualIndex], bsdfData, _LightDatas[punctualIndex].lightType,
localDiffuseLighting, localSpecularLighting);
accLighting.punctualDiffuseLighting += localDiffuseLighting;
accLighting.punctualSpecularLighting += localSpecularLighting;
DirectLighting lighting = EvaluateBSDF_Punctual(context, V, posInput, preLightData, _LightDatas[punctualIndex], bsdfData, bakeLightingData, _LightDatas[punctualIndex].lightType);
AccumulateDirectLighting(lighting, aggregateLighting);
}
#else

float3 localDiffuseLighting, localSpecularLighting;
EvaluateBSDF_Punctual( context, V, posInput, preLightData, _LightDatas[i], bsdfData, _LightDatas[i].lightType,
localDiffuseLighting, localSpecularLighting);
accLighting.punctualDiffuseLighting += localDiffuseLighting;
accLighting.punctualSpecularLighting += localSpecularLighting;
DirectLighting lighting = EvaluateBSDF_Punctual(context, V, posInput, preLightData, _LightDatas[i], bsdfData, bakeLightingData, _LightDatas[i].lightType);
AccumulateDirectLighting(lighting, aggregateLighting);
}
#endif

while (i < areaLightCount && lightType == GPULIGHTTYPE_LINE)
{
float3 localDiffuseLighting, localSpecularLighting;
EvaluateBSDF_Area( context, V, posInput, preLightData, _LightDatas[areaIndex], bsdfData, GPULIGHTTYPE_LINE,
localDiffuseLighting, localSpecularLighting);
accLighting.areaDiffuseLighting += localDiffuseLighting;
accLighting.areaSpecularLighting += localSpecularLighting;
DirectLighting lighting = EvaluateBSDF_Area(context, V, posInput, preLightData, _LightDatas[areaIndex], bsdfData, bakeLightingData, GPULIGHTTYPE_LINE);
AccumulateDirectLighting(lighting, aggregateLighting);
i++;
areaIndex = i < areaLightCount ? FetchIndex(areaLightStart, i) : 0;

while (i < areaLightCount && lightType == GPULIGHTTYPE_RECTANGLE)
{
float3 localDiffuseLighting, localSpecularLighting;
EvaluateBSDF_Area( context, V, posInput, preLightData, _LightDatas[areaIndex], bsdfData, GPULIGHTTYPE_RECTANGLE,
localDiffuseLighting, localSpecularLighting);
accLighting.areaDiffuseLighting += localDiffuseLighting;
accLighting.areaSpecularLighting += localSpecularLighting;
DirectLighting lighting = EvaluateBSDF_Area(context, V, posInput, preLightData, _LightDatas[areaIndex], bsdfData, bakeLightingData, GPULIGHTTYPE_RECTANGLE);
AccumulateDirectLighting(lighting, aggregateLighting);
i++;
areaIndex = i < areaLightCount ? FetchIndex(areaLightStart, i) : 0;

#else
float3 localDiffuseLighting, localSpecularLighting;
EvaluateBSDF_Area( context, V, posInput, preLightData, _LightDatas[i], bsdfData, _LightDatas[i].lightType,
localDiffuseLighting, localSpecularLighting);
accLighting.areaDiffuseLighting += localDiffuseLighting;
accLighting.areaSpecularLighting += localSpecularLighting;
DirectLighting lighting = EvaluateBSDF_Area(context, V, posInput, preLightData, _LightDatas[i], bsdfData, bakeLightingData, _LightDatas[i].lightType);
AccumulateDirectLighting(lighting, aggregateLighting);
float totalIblWeight = 0.0; // Max: 1
float reflectionHierarchyWeight = 0.0; // Max: 1.0
float refractionHierarchyWeight = 0.0; // Max: 1.0
if (featureFlags & LIGHTFEATUREFLAGS_SSL)
if (featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION)
{
IndirectLighting lighting = EvaluateBSDF_SSRefraction(context, V, posInput, preLightData, bsdfData, refractionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
}
if (featureFlags & LIGHTFEATUREFLAGS_SSREFLECTION)
// SSR and rough refraction
float3 localDiffuseLighting, localSpecularLighting;
float2 weight;
EvaluateBSDF_SSL(V, posInput, bsdfData, localDiffuseLighting, localSpecularLighting, weight);
applyWeigthedIblLighting(localDiffuseLighting, localSpecularLighting, weight, accLighting.envDiffuseLighting, accLighting.envSpecularLighting, totalIblWeight);
accLighting.envDiffuseLightingWeight = weight.x;
IndirectLighting lighting = EvaluateBSDF_SSReflection(context, V, posInput, preLightData, bsdfData, reflectionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
}
if (featureFlags & LIGHTFEATUREFLAGS_ENV || featureFlags & LIGHTFEATUREFLAGS_SKY)

{
float3 localDiffuseLighting, localSpecularLighting;
float2 weight;
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES;
#ifdef LIGHTLOOP_TILE_PASS

#endif
// Note: In case of IBL we are sorted from smaller to bigger projected solid angle bounds. We are not sorted by type so we can't do a 'while' approach like for area light.
for (i = 0; i < envLightCount && totalIblWeight < 1.0; ++i)
for (i = 0; i < envLightCount && reflectionHierarchyWeight < 1.0; ++i)
{
#ifdef LIGHTLOOP_TILE_PASS
uint envLightIndex = FetchIndex(envLightStart, i);

EvaluateBSDF_Env(context, V, posInput, preLightData, _EnvLightDatas[envLightIndex], bsdfData, _EnvLightDatas[envLightIndex].envShapeType, localDiffuseLighting, localSpecularLighting, weight);
applyWeigthedIblLighting(localDiffuseLighting, localSpecularLighting, weight, accLighting.envDiffuseLighting, accLighting.envSpecularLighting, totalIblWeight);
IndirectLighting lighting = EvaluateBSDF_Env( context, V, posInput, preLightData, _EnvLightDatas[envLightIndex], bsdfData, _EnvLightDatas[envLightIndex].envShapeType,
GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION, reflectionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
}
// Refraction probe and reflection probe will process exactly the same weight. It will be good for performance to be able to share this computation
// However it is hard to deal with the fact that reflectionHierarchyWeight and refractionHierarchyWeight have not the same values, they are independent
// The refraction probe is rarely used and happen only with sphere shape and high IOR. So we accept the slow path that use more simple code and
// doesn't affect the performance of the reflection which is more important.
// We reuse LIGHTFEATUREFLAGS_SSREFRACTION flag as refraction is mainly base on the screen. Would be aa waste to not use screen and only cubemap.
if (featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION)
{
for (i = 0; i < envLightCount && refractionHierarchyWeight < 1.0; ++i)
{
#ifdef LIGHTLOOP_TILE_PASS
uint envLightIndex = FetchIndex(envLightStart, i);
#else
uint envLightIndex = i;
#endif
IndirectLighting lighting = EvaluateBSDF_Env( context, V, posInput, preLightData, _EnvLightDatas[envLightIndex], bsdfData, _EnvLightDatas[envLightIndex].envShapeType,
GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION, refractionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
}
if (featureFlags & LIGHTFEATUREFLAGS_SKY)
// Only apply the sky IBL if the sky texture is available
if (featureFlags & LIGHTFEATUREFLAGS_SKY && _EnvLightSkyEnabled)
// Only apply the sky IBL if the sky texture is available, and if we haven't yet accumulated enough IBL lighting.
if (_EnvLightSkyEnabled && totalIblWeight < 1.0)
// Only apply the sky if we haven't yet accumulated enough IBL lighting.
if (reflectionHierarchyWeight < 1.0)
float3 localDiffuseLighting, localSpecularLighting;
float2 weight;
EvaluateBSDF_Env(context, V, posInput, preLightData, envLightSky, bsdfData, ENVSHAPETYPE_SKY, localDiffuseLighting, localSpecularLighting, weight);
applyWeigthedIblLighting(localDiffuseLighting, localSpecularLighting, weight, accLighting.envDiffuseLighting, accLighting.envSpecularLighting, totalIblWeight);
IndirectLighting lighting = EvaluateBSDF_Env(context, V, posInput, preLightData, envLightSky, bsdfData, ENVSHAPETYPE_SKY, GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION, reflectionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
}
if (featureFlags & LIGHTFEATUREFLAGS_SSREFRACTION)
{
if (refractionHierarchyWeight < 1.0)
{
// The sky is a single cubemap texture separate from the reflection probe texture array (different resolution and compression)
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_SKY;
EnvLightData envLightSky = InitSkyEnvLightData(0); // The sky data are generated on the fly so the compiler can optimize the code
IndirectLighting lighting = EvaluateBSDF_Env(context, V, posInput, preLightData, envLightSky, bsdfData, ENVSHAPETYPE_SKY, GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION, refractionHierarchyWeight);
AccumulateIndirectLighting(lighting, aggregateLighting);
}
}
}
}

PostEvaluateBSDF( context, V, posInput, preLightData, accLighting, bsdfData, bakeDiffuseLighting,
PostEvaluateBSDF( context, V, posInput, preLightData, bsdfData, bakeLightingData, aggregateLighting,
diffuseLighting, specularLighting);
ApplyDebug(context, posInput.positionWS, diffuseLighting, specularLighting);

21
ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs


[SurfaceDataAttributes("Bake Diffuse Lighting", false, true)]
public Vector3 bakeDiffuseLighting; // This is the result of sampling lightmap/lightprobe/proxyvolume
// Use for float instead of vector4 to ease the debug (no performance impact)
// Note: We have no way to remove these value automatically based on either SHADEROPTIONS_BAKED_SHADOW_MASK_ENABLE or s_BakedShadowMaskEnable here. Unless we make two structure... For now always keep this value
[SurfaceDataAttributes("Shadow Mask 0")]
public float shadowMask0;
[SurfaceDataAttributes("Shadow Mask 1")]
public float shadowMask1;
[SurfaceDataAttributes("Shadow Mask 2")]
public float shadowMask2;
[SurfaceDataAttributes("Shadow Mask 3")]
public float shadowMask3;
[SurfaceDataAttributes("Emissive Color", false, true)]
public Vector3 emissiveColor;
[SurfaceDataAttributes("Emissive Intensity")]

public Vector3 diffuseColor;
public Vector3 emissiveColor; // HDR value
};
public static RenderTextureFormat GetShadowMaskBufferFormat()
{
return RenderTextureFormat.ARGB32;
}
public static RenderTextureReadWrite GetShadowMaskBufferReadWrite()
{
return RenderTextureReadWrite.Linear;
}
public static RenderTextureFormat GetVelocityBufferFormat()
{

32
ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs.hlsl


//
#define DEBUGVIEW_BUILTIN_BUILTINDATA_OPACITY (100)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_BAKE_DIFFUSE_LIGHTING (101)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_COLOR (102)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_INTENSITY (103)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_VELOCITY (104)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DISTORTION (105)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DISTORTION_BLUR (106)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DEPTH_OFFSET (107)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK0 (102)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK1 (103)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK2 (104)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK3 (105)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_COLOR (106)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_INTENSITY (107)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_VELOCITY (108)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DISTORTION (109)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DISTORTION_BLUR (110)
#define DEBUGVIEW_BUILTIN_BUILTINDATA_DEPTH_OFFSET (111)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Builtin+LightTransportData: static fields

{
float opacity;
float3 bakeDiffuseLighting;
float shadowMask0;
float shadowMask1;
float shadowMask2;
float shadowMask3;
float3 emissiveColor;
float emissiveIntensity;
float2 velocity;

case DEBUGVIEW_BUILTIN_BUILTINDATA_BAKE_DIFFUSE_LIGHTING:
result = builtindata.bakeDiffuseLighting;
needLinearToSRGB = true;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK0:
result = builtindata.shadowMask0.xxx;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK1:
result = builtindata.shadowMask1.xxx;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK2:
result = builtindata.shadowMask2.xxx;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_SHADOW_MASK3:
result = builtindata.shadowMask3.xxx;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_EMISSIVE_COLOR:
result = builtindata.emissiveColor;

25
ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.hlsl


//-----------------------------------------------------------------------------
// common Encode/Decode functions
//-----------------------------------------------------------------------------
struct BakeLightingData
{
float3 bakeDiffuseLighting;
#ifdef SHADOWS_SHADOWMASK
float4 bakeShadowMask;
#endif
};
// Guideline for velocity buffer.
// We support various architecture for HDRenderPipeline
// - Forward only rendering

// - Same velocity buffer is use for all scenario, so if deferred define a velocity buffer, the same is reuse for forward case.
// For these reasons we chose to avoid to pack velocity buffer with anything else in case of PackgbufferInFP16 (and also in case the format change)
// Encode/Decode velocity/distortion in a buffer (either forward of deferred)
// Encode/Decode shadowmask/velocity/distortion in a buffer (either forward of deferred)
// Design note: We assume that shadowmask/velocity/distortion fit into a single buffer (i.e not spread on several buffer)
void EncodeShadowMask(float4 shadowMask, out float4 outBuffer)
{
// RT - RGBA
outBuffer = shadowMask;
}
void DecodeShadowMask(float4 inBuffer, out float4 shadowMask)
{
shadowMask = inBuffer;
}
// Design note: We assume that velocity/distortion fit into a single buffer (i.e not spread on several buffer)
void EncodeVelocity(float2 velocity, out float4 outBuffer)
{

break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_DEPTH_OFFSET:
result = builtinData.depthOffset.xxx * 10.0; // * 10 assuming 1 unity is 1m
break;
break;
case DEBUGVIEW_BUILTIN_BUILTINDATA_DISTORTION:
result = float3((builtinData.distortion / (abs(builtinData.distortion) + 1) + 1) * 0.5, 0.5);
break;

51
ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader


_ThicknessMap2("Thickness Map", 2D) = "white" {}
_ThicknessMap3("Thickness Map", 2D) = "white" {}
_ThicknessRemap0("Thickness Remap", Vector) = (0, 1, 0, 0)
_ThicknessRemap1("Thickness Remap", Vector) = (0, 1, 0, 0)
_ThicknessRemap2("Thickness Remap", Vector) = (0, 1, 0, 0)
_ThicknessRemap3("Thickness Remap", Vector) = (0, 1, 0, 0)
// All the following properties exist only in layered lit material
// Layer blending options

[ToggleOff] _EnableSpecularOcclusion("Enable specular occlusion", Float) = 0.0
_EmissiveColor("EmissiveColor", Color) = (0, 0, 0)
_EmissiveColor("EmissiveColor", Color) = (1, 1, 1)
_EmissiveColorMap("EmissiveColorMap", 2D) = "white" {}
_EmissiveIntensity("EmissiveIntensity", Float) = 0
[ToggleOff] _AlbedoAffectEmissive("Albedo Affect Emissive", Float) = 0.0

// Transparency
[ToggleOff] _PreRefractionPass("PreRefractionPass", Float) = 0.0
// HACK: GI Baking system relies on some properties existing in the shader ("_MainTex", "_Cutoff" and "_Color") for opacity handling, so we need to store our version of those parameters in the hard-coded name the GI baking system recognizes.
_MainTex("Albedo", 2D) = "white" {}
_Color("Color", Color) = (1,1,1,1)
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#pragma shader_feature _ALPHATEST_ON

// Note _MATID_STANDARD is not define as there is always the default case "_". We assign default as _MATID_STANDARD, so we never test _MATID_STANDARD
#pragma shader_feature _ _MATID_SSS
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
// TODO: We should have this keyword only if VelocityInGBuffer is enable, how to do that ?

HLSLPROGRAM
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"

HLSLPROGRAM
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"

HLSLPROGRAM
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define DEBUG_DISPLAY
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"

#define SHADERPASS SHADERPASS_LIGHT_TRANSPORT
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitMetaPass.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"

Cull[_CullMode]
ZClip Off
ZClip [_ZClip]
ZWrite On
ZTest LEqual

HLSLPROGRAM
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
// TEMP until pragma work in include
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#include "../../Lighting/Lighting.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"

Cull[_CullMode]
HLSLPROGRAM
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#define DEBUG_DISPLAY
#define SHADERPASS SHADERPASS_FORWARD

54
ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader


_ThicknessMap2("Thickness Map", 2D) = "white" {}
_ThicknessMap3("Thickness Map", 2D) = "white" {}
_ThicknessRemap0("Thickness Remap", Vector) = (0, 1, 0, 0)
_ThicknessRemap1("Thickness Remap", Vector) = (0, 1, 0, 0)
_ThicknessRemap2("Thickness Remap", Vector) = (0, 1, 0, 0)
_ThicknessRemap3("Thickness Remap", Vector) = (0, 1, 0, 0)
// All the following properties exist only in layered lit material
// Layer blending options

[ToggleOff] _EnableSpecularOcclusion("Enable specular occlusion", Float) = 0.0
_EmissiveColor("EmissiveColor", Color) = (0, 0, 0)
_EmissiveColor("EmissiveColor", Color) = (1, 1, 1)
_EmissiveColorMap("EmissiveColorMap", 2D) = "white" {}
_EmissiveIntensity("EmissiveIntensity", Float) = 0
[ToggleOff] _AlbedoAffectEmissive("Albedo Affect Emissive", Float) = 0.0

// Transparency
[ToggleOff] _PreRefractionPass("PreRefractionPass", Float) = 0.0
// HACK: GI Baking system relies on some properties existing in the shader ("_MainTex", "_Cutoff" and "_Color") for opacity handling, so we need to store our version of those parameters in the hard-coded name the GI baking system recognizes.
_MainTex("Albedo", 2D) = "white" {}
_Color("Color", Color) = (1,1,1,1)
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
#pragma only_renderers d3d11 ps4 // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#pragma shader_feature _ALPHATEST_ON

// Note _MATID_STANDARD is not define as there is always the default case "_". We assign default as _MATID_STANDARD, so we never test _MATID_STANDARD
#pragma shader_feature _ _MATID_SSS
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
// TODO: We should have this keyword only if VelocityInGBuffer is enable, how to do that ?

#pragma hull Hull
#pragma domain Domain
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"

#pragma hull Hull
#pragma domain Domain
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST

#pragma hull Hull
#pragma domain Domain
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define DEBUG_DISPLAY
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"

#define SHADERPASS SHADERPASS_LIGHT_TRANSPORT
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitMetaPass.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"

Cull[_CullMode]
ZClip Off
ZClip [_ZClip]
ZWrite On
ZTest LEqual

#pragma hull Hull
#pragma domain Domain
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
// TEMP until pragma work in include
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#include "../../Lighting/Lighting.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"

#pragma hull Hull
#pragma domain Domain
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
// TEMP until pragma work in include
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#include "../../Lighting/Lighting.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "LayeredLitData.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs


TessellationMode tessMode = (TessellationMode)material.GetFloat(kTessellationMode);
SetKeyword(material, "_TESSELLATION_PHONG", tessMode == TessellationMode.Phong);
}
SetupMainTexForAlphaTestGI("_BaseColorMap", "_BaseColor", material);
}
static public void SetupBaseLitMaterialPass(Material material)

40
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs


public static GUIContent subsurfaceRadiusMapText = new GUIContent("Subsurface radius map (R)", "Determines the range of the blur.");
public static GUIContent thicknessText = new GUIContent("Thickness", "If subsurface scattering is enabled, low values allow some light to be transmitted through the object.");
public static GUIContent thicknessMapText = new GUIContent("Thickness map (R)", "If subsurface scattering is enabled, low values allow some light to be transmitted through the object.");
public static GUIContent thicknessRemapText = new GUIContent("Thickness Remap", "Remaps values of the thickness map from [0, 1] to the specified range.");
// Clear Coat
public static GUIContent coatCoverageText = new GUIContent("Coat Coverage", "Percentage of clear coat coverage");

// Transparency
public static string refractionModeText = "Refraction Mode";
public static GUIContent refractionIORText = new GUIContent("Indice of refraction", "Indice of refraction");
public static GUIContent refractionIORText = new GUIContent("Index of refraction", "Index of refraction");
public static GUIContent refractionThicknessMultiplierText = new GUIContent("Refraction Thickness multiplier", "Thickness multiplier");
public static GUIContent refractionThicknessMultiplierText = new GUIContent("Refraction Thickness multiplier (m)", "Thickness multiplier");
public static GUIContent atDistanceText = new GUIContent("Transmittance Absorption Distance", "Absorption distance reference");
public static GUIContent atDistanceText = new GUIContent("Transmittance Absorption Distance (m)", "Absorption distance reference");
public static GUIContent perPixelDisplacementDetailsWarning = new GUIContent("For pixel displacement to work correctly, details and base map must use same UV mapping");
}

protected const string kThickness = "_Thickness";
protected MaterialProperty[] thicknessMap = new MaterialProperty[kMaxLayerCount];
protected const string kThicknessMap = "_ThicknessMap";
protected MaterialProperty[] thicknessRemap = new MaterialProperty[kMaxLayerCount];
protected const string kThicknessRemap = "_ThicknessRemap";
protected MaterialProperty[] UVDetail = new MaterialProperty[kMaxLayerCount];
protected const string kUVDetail = "_UVDetail";

protected const string kIOR = "_IOR";
protected MaterialProperty transmittanceColor = null;
protected const string kTransmittanceColor = "_TransmittanceColor";
protected MaterialProperty transmittanceColorMap = null;
protected const string kTransmittanceColorMap = "_TransmittanceColorMap";
protected MaterialProperty atDistance = null;
protected const string kATDistance = "_ATDistance";
protected MaterialProperty thicknessMultiplier = null;

subsurfaceRadiusMap[i] = FindProperty(string.Format("{0}{1}", kSubsurfaceRadiusMap, m_PropertySuffixes[i]), props);
thickness[i] = FindProperty(string.Format("{0}{1}", kThickness, m_PropertySuffixes[i]), props);
thicknessMap[i] = FindProperty(string.Format("{0}{1}", kThicknessMap, m_PropertySuffixes[i]), props);
thicknessRemap[i] = FindProperty(string.Format("{0}{1}", kThicknessRemap, m_PropertySuffixes[i]), props);
// Details
UVDetail[i] = FindProperty(string.Format("{0}{1}", kUVDetail, m_PropertySuffixes[i]), props);

// Transparency
refractionMode = FindProperty(kRefractionMode, props, false);
transmittanceColor = FindProperty(kTransmittanceColor, props, false);
transmittanceColorMap = FindProperty(kTransmittanceColorMap, props, false);
atDistance = FindProperty(kATDistance, props, false);
thicknessMultiplier = FindProperty(kThicknessMultiplier, props, false);
ior = FindProperty(kIOR, props, false);

for (int i = 0; i < profiles.Length; i++)
{
names[i + 1] = new GUIContent(profiles[i].name);
values[i + 1] = i;
values[i + 1] = i + 1;
}
using (var scope = new EditorGUI.ChangeCheckScope())

m_MaterialEditor.ShaderProperty(subsurfaceRadius[layerIndex], Styles.subsurfaceRadiusText);
m_MaterialEditor.TexturePropertySingleLine(Styles.subsurfaceRadiusMapText, subsurfaceRadiusMap[layerIndex]);
m_MaterialEditor.ShaderProperty(thickness[layerIndex], Styles.thicknessText);
if (thicknessMap[layerIndex].textureValue != null)
{
// Display the remap of texture values.
Vector2 remap = thicknessRemap[layerIndex].vectorValue;
EditorGUI.BeginChangeCheck();
EditorGUILayout.MinMaxSlider(Styles.thicknessRemapText, ref remap.x, ref remap.y, 0.0f, 1.0f);
if (EditorGUI.EndChangeCheck())
{
thicknessRemap[layerIndex].vectorValue = remap;
}
}
else
{
// Allow the user to set the constant value of thickness if no thickness map is provided.
m_MaterialEditor.ShaderProperty(thickness[layerIndex], Styles.thicknessText);
}
}
protected void ShaderClearCoatInputGUI()

var mode = (Lit.RefractionMode)refractionMode.floatValue;
if (mode != Lit.RefractionMode.None)
{
++EditorGUI.indentLevel;
m_MaterialEditor.ShaderProperty(ior, Styles.refractionIORText);
blendMode.floatValue = (float)BlendMode.Alpha;

m_MaterialEditor.ShaderProperty(thicknessMultiplier, Styles.refractionThicknessMultiplierText);
--EditorGUI.indentLevel;
m_MaterialEditor.ShaderProperty(transmittanceColor, Styles.transmittanceColorText);
m_MaterialEditor.TexturePropertySingleLine(Styles.transmittanceColorText, transmittanceColorMap, transmittanceColor);
--EditorGUI.indentLevel;
--EditorGUI.indentLevel;
}
}

}
EditorGUI.indentLevel++;
m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveText, emissiveColorMap, emissiveColor);
m_MaterialEditor.TextureScaleOffsetProperty(emissiveColorMap);
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
m_MaterialEditor.ShaderProperty(albedoAffectEmissive, Styles.albedoAffectEmissiveText);
EditorGUI.indentLevel--;

var canHaveRefraction = !material.HasProperty(kPreRefractionPass) || material.GetFloat(kPreRefractionPass) <= 0.0;
SetKeyword(material, "_REFRACTION_PLANE", (refractionModeValue == Lit.RefractionMode.Plane) && canHaveRefraction);
SetKeyword(material, "_REFRACTION_SPHERE", (refractionModeValue == Lit.RefractionMode.Sphere) && canHaveRefraction);
SetKeyword(material, "_TRANSMITTANCECOLORMAP", material.GetTexture(kTransmittanceColorMap) && canHaveRefraction);
}
}
} // namespace UnityEditor

21
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs


public override int GetMaterialGBufferCount() { return (int)GBufferMaterial.Count; }
RenderTextureFormat[] m_RTFormat4 = { RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB2101010, RenderTextureFormat.ARGB32, RenderTextureFormat.RGB111110Float };
RenderTextureReadWrite[] m_RTReadWrite4 = { RenderTextureReadWrite.sRGB, RenderTextureReadWrite.Linear, RenderTextureReadWrite.Linear, RenderTextureReadWrite.Linear };
// TODO: Just discovered that Unity doesn't support unsigned 16 RT format.
RenderTextureFormat[] m_RTFormat2 = { RenderTextureFormat.ARGBInt, RenderTextureFormat.ARGBInt };
RenderTextureReadWrite[] m_RTReadWrite2 = { RenderTextureReadWrite.Linear, RenderTextureReadWrite.Linear };
RTFormat = new RenderTextureFormat[(int)GBufferMaterial.Count];
RTReadWrite = new RenderTextureReadWrite[(int)GBufferMaterial.Count];
// TODO: Just discovered that Unity doesn't support unsigned 16 RT format.
RTFormat[0] = RenderTextureFormat.ARGBInt; RTReadWrite[0] = RenderTextureReadWrite.Linear;
RTFormat[1] = RenderTextureFormat.ARGBInt; RTReadWrite[1] = RenderTextureReadWrite.Linear;
RTFormat = m_RTFormat2;
RTReadWrite = m_RTReadWrite2;
RTFormat[0] = RenderTextureFormat.ARGB32; RTReadWrite[0] = RenderTextureReadWrite.sRGB;
RTFormat[1] = RenderTextureFormat.ARGB2101010; RTReadWrite[1] = RenderTextureReadWrite.Linear;
RTFormat[2] = RenderTextureFormat.ARGB32; RTReadWrite[2] = RenderTextureReadWrite.Linear;
RTFormat[3] = RenderTextureFormat.RGB111110Float; RTReadWrite[3] = RenderTextureReadWrite.Linear;
RTFormat = m_RTFormat4;
RTReadWrite = m_RTReadWrite4;
}
}

678
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl


#include "Lit.cs.hlsl"
#include "SubsurfaceScatteringSettings.cs.hlsl"
// Enables attenuation of light source contributions by participating media (fog).
#define VOLUMETRIC_SHADOWING_ENABLED
#ifdef VOLUMETRIC_SHADOWING_ENABLED
// Apparently, not all shaders include "ShaderVariables.hlsl".
#include "../../ShaderVariables.hlsl"
#include "../../../Core/ShaderLibrary/VolumeRendering.hlsl"
#endif
#if HAS_REFRACTION
# include "../../../Core/ShaderLibrary/Refraction.hlsl"
# if defined(_REFRACTION_PLANE)
# define REFRACTION_MODEL(V, posInputs, bsdfData) RefractionModelPlane(V, posInputs.positionWS, bsdfData.normalWS, bsdfData.ior, bsdfData.thickness)
# elif defined(_REFRACTION_SPHERE)
# define REFRACTION_MODEL(V, posInputs, bsdfData) RefractionModelSphere(V, posInputs.positionWS, bsdfData.normalWS, bsdfData.ior, bsdfData.thickness)
# endif
#endif
// In case we pack data uint16 buffer we need to change the output render target format to uint16
// TODO: Is there a way to automate these output type based on the format declare in lit.cs ?

// TODO: How to abstract that ? We would like to avoid this PS4 test here
#ifdef SHADER_API_PS4
#ifdef SHADER_API_PSSL
// On PS4 we need to specify manually the format of the output render target, output type is not enough
#pragma PSSL_target_output_format(target 0 FMT_UINT16_ABGR)
#pragma PSSL_target_output_format(target 1 FMT_UINT16_ABGR)

#define LTC_LUT_OFFSET (0.5 * rcp(LTC_LUT_SIZE))
// Subsurface scattering constant
#define SSS_WRAP_ANGLE (PI/12) // Used for wrap lighting
#define SSS_WRAP_ANGLE (PI/12) // 15 degrees
#define SSS_WRAP_LIGHT cos(PI/2 - SSS_WRAP_ANGLE)
CBUFFER_START(UnitySSSParameters)

CBUFFER_END
// General constant
#define MIN_N_DOT_V 0.0001 // The minimum value of 'NdotV'
#define MIN_N_DOT_V SMALL_FLT_VALUE // The minimum value of 'NdotV'
//-----------------------------------------------------------------------------
// Helper for cheap screen space raycasting
//-----------------------------------------------------------------------------
float3 EstimateRaycast(float3 V, PositionInputs posInputs, float3 positionWS, float3 rayWS)
{
// For all refraction approximation, to calculate the refracted point in world space,
// we approximate the scene as a plane (back plane) with normal -V at the depth hit point.
// (We avoid to raymarch the depth texture to get the refracted point.)
uint2 depthSize = uint2(_PyramidDepthMipSize.xy);
// Get the depth of the approximated back plane
float pyramidDepth = LOAD_TEXTURE2D_LOD(_PyramidDepthTexture, posInputs.positionSS * (depthSize >> 2), 2).r;
float depth = LinearEyeDepth(pyramidDepth, _ZBufferParams);
// Distance from point to the back plane
float depthFromPositionInput = depth - posInputs.depthVS;
float offset = dot(-V, positionWS - posInputs.positionWS);
float depthFromPosition = depthFromPositionInput - offset;
float hitDistanceFromPosition = depthFromPosition / dot(-V, rayWS);
return positionWS + rayWS * hitDistanceFromPosition;
}
//-----------------------------------------------------------------------------
// Ligth and material classification for the deferred rendering path

/* 2 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_AREA | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 3 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 4 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | LIGHTFEATUREFLAGS_ENV | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 5 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 5 */ LIGHT_FEATURE_MASK_FLAGS_OPAQUE | MATERIALFEATUREFLAGS_LIT_STANDARD,
// SSS
/* 6 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_SSS,

/* 10 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_SSS,
/* 10 */ LIGHT_FEATURE_MASK_FLAGS_OPAQUE | MATERIALFEATUREFLAGS_LIT_SSS,
// Aniso
/* 11 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_ANISO,

/* 15 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_ANISO,
/* 15 */ LIGHT_FEATURE_MASK_FLAGS_OPAQUE | MATERIALFEATUREFLAGS_LIT_ANISO,
// With foliage or crowd with SSS and standard can overlap a lot, better to have a dedicated combination
/* 16 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,

/* 20 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
/* 20 */ LIGHT_FEATURE_MASK_FLAGS_OPAQUE | MATERIALFEATUREFLAGS_LIT_SSS | MATERIALFEATUREFLAGS_LIT_STANDARD,
// ClearCoat
/* 21 */ LIGHTFEATUREFLAGS_SKY | LIGHTFEATUREFLAGS_DIRECTIONAL | LIGHTFEATUREFLAGS_PUNCTUAL | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,

/* 25 */ LIGHT_FEATURE_MASK_FLAGS | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 25 */ LIGHT_FEATURE_MASK_FLAGS_OPAQUE | MATERIALFEATUREFLAGS_LIT_CLEAR_COAT,
/* 26 */ LIGHT_FEATURE_MASK_FLAGS | MATERIAL_FEATURE_MASK_FLAGS, // Catch all case with MATERIAL_FEATURE_MASK_FLAGS is needed in case we disable material classification
/* 26 */ LIGHT_FEATURE_MASK_FLAGS_OPAQUE | MATERIAL_FEATURE_MASK_FLAGS, // Catch all case with MATERIAL_FEATURE_MASK_FLAGS is needed in case we disable material classification
};
uint FeatureFlagsToTileVariant(uint featureFlags)

uint transmissionMode = BitFieldExtract(_TransmissionFlags, 2u, 2u * subsurfaceProfile);
bsdfData.enableTransmission = transmissionMode != SSS_TRSM_MODE_NONE && (_EnableSSSAndTransmission > 0);
bsdfData.useThinObjectMode = transmissionMode == SSS_TRSM_MODE_THIN;
bool performPostScatterTexturing = IsBitSet(_TexturingModeFlags, subsurfaceProfile);
#if defined(SHADERPASS) && (SHADERPASS == SHADERPASS_LIGHT_TRANSPORT) // In case of GI pass don't modify the diffuseColor
bool enableSssAndTransmission = false;
#elif defined(SHADERPASS) && (SHADERPASS == SHADERPASS_SUBSURFACE_SCATTERING)
bool enableSssAndTransmission = true;
#else
bool enableSssAndTransmission = _EnableSSSAndTransmission != 0;
#endif
if (enableSssAndTransmission) // If we globally disable SSS effect, don't modify diffuseColor
{
// We modify the albedo here as this code is used by all lighting (including light maps and GI).
if (performPostScatterTexturing)
{
#if !defined(SHADERPASS) || (SHADERPASS != SHADERPASS_SUBSURFACE_SCATTERING)
bsdfData.diffuseColor = float3(1.0, 1.0, 1.0);
#endif
}
else
{
bsdfData.diffuseColor = sqrt(bsdfData.diffuseColor);
}
}
bsdfData.useThinObjectMode = transmissionMode == SSS_TRSM_MODE_THIN;
bsdfData.transmittance = ComputeTransmittance(_ShapeParams[subsurfaceProfile].rgb,
_TransmissionTints[subsurfaceProfile].rgb,
bsdfData.thickness, bsdfData.subsurfaceRadius);
bsdfData.transmittance = ComputeTransmittanceDisney(_ShapeParams[subsurfaceProfile].rgb,
_TransmissionTints[subsurfaceProfile].rgb,
bsdfData.thickness, bsdfData.subsurfaceRadius);
}
else
{

_TransmissionTints[subsurfaceProfile].rgb,
bsdfData.thickness, bsdfData.subsurfaceRadius);
}
}
}
bsdfData.transmittance *= bsdfData.diffuseColor; // Premultiply
// Returns the modified albedo (diffuse color) for materials with subsurface scattering.
// Ref: Advanced Techniques for Realistic Real-Time Skin Rendering.
float3 ApplyDiffuseTexturingMode(BSDFData bsdfData)
{
float3 albedo = bsdfData.diffuseColor;
if (bsdfData.materialId == MATERIALID_LIT_SSS)
{
#if defined(SHADERPASS) && (SHADERPASS == SHADERPASS_SUBSURFACE_SCATTERING)
// If the SSS pass is executed, we know we have SSS enabled.
bool enableSssAndTransmission = true;
#else
bool enableSssAndTransmission = _EnableSSSAndTransmission != 0;
#endif
if (enableSssAndTransmission)
{
bool performPostScatterTexturing = IsBitSet(_TexturingModeFlags, bsdfData.subsurfaceProfile);
if (performPostScatterTexturing)
{
// Post-scatter texturing mode: the albedo is only applied during the SSS pass.
#if !defined(SHADERPASS) || (SHADERPASS != SHADERPASS_SUBSURFACE_SCATTERING)
albedo = float3(1, 1, 1);
#endif
}
else
{
// Pre- and pos- scatter texturing mode.
albedo = sqrt(albedo);
}
}
return albedo;
}
void FillMaterialIdClearCoatData(float3 coatNormalWS, float coatCoverage, float coatIOR, inout BSDFData bsdfData)

bsdfData.coatCoverage = coatCoverage;
}
void FillMaterialIdTransparencyData(float ior, float3 transmittanceColor, float atDistance, float thickness, float transmittanceMask, inout BSDFData bsdfData)
void FillMaterialIdTransparencyData(float3 baseColor, float metallic, float ior, float3 transmittanceColor, float atDistance, float thickness, float transmittanceMask, inout BSDFData bsdfData)
// Absorption coefficient from Disney: http://blog.selfshadow.com/publications/s2015-shading-course/burley/s2015_pbs_disney_bsdf_notes.pdf
bsdfData.absorptionCoefficient = -log(transmittanceColor + 0.00001) / max(atDistance, 0.000001);
// IOR define the fresnel0 value, so update it also for consistency (and even if not physical we still need to take into account any metal mask)
bsdfData.fresnel0 = lerp(IORToFresnel0(ior).xxx, baseColor, metallic);
bsdfData.absorptionCoefficient = TransmittanceColorAtDistanceToAbsorption (transmittanceColor, atDistance);
bsdfData.transmittanceMask = transmittanceMask;
bsdfData.thickness = max(thickness, 0.0001);
}

#if HAS_REFRACTION
// Note: Will override thickness of SSS's property set
FillMaterialIdTransparencyData(
surfaceData.ior, surfaceData.transmittanceColor, surfaceData.atDistance, surfaceData.thickness, surfaceData.transmittanceMask,
surfaceData.baseColor, surfaceData.metallic, surfaceData.ior, surfaceData.transmittanceColor, surfaceData.atDistance, surfaceData.thickness, surfaceData.transmittanceMask,
bsdfData);
#endif

float ltcClearCoatFresnelTerm;
float3x3 ltcCoatT;
#ifdef VOLUMETRIC_SHADOWING_ENABLED
float globalFogExtinction;
#endif
// Refraction
float3 transmissionRefractV; // refracted view vector after exiting the shape
float3 transmissionPositionWS; // start of the refracted ray after exiting the shape
float3 transmissionTransmittance; // transmittance due to absorption
float transmissionSSMipLevel; // mip level of the screen space gaussian pyramid for rough refraction
// This is a refract - TODO: do we call original refract or this one, original maybe slightly emore expensive, to check
// This is a refract - TODO: do we call original refract or this one, original maybe slightly more expensive, to check
float3 ClearCoatTransform(float3 X, float3 N, float ieta)
{
float XdotN = saturate(dot(N, X));

// We deem the intensity difference of a couple of percent for high values of roughness
// to not be worth the cost of another precomputed table.
// Note: this formulation bakes the BSDF non-symmetric!
preLightData.energyCompensation = 1 / reflectivity - 1;
preLightData.energyCompensation = 1.0 / reflectivity - 1.0;
preLightData.energyCompensation = 0;
preLightData.energyCompensation = 0.0;
#endif // LIT_USE_GGX_ENERGY_COMPENSATION
// Area light

preLightData.ltcMagnitudeFresnel = bsdfData.fresnel0 * ltcGGXFresnelMagnitudeDiff + (float3)ltcGGXFresnelMagnitude;
}
#ifdef VOLUMETRIC_SHADOWING_ENABLED
preLightData.globalFogExtinction = _GlobalFog_Extinction;
#ifdef REFRACTION_MODEL
RefractionModelResult refraction = REFRACTION_MODEL(V, posInput, bsdfData);
preLightData.transmissionRefractV = refraction.rayWS;
preLightData.transmissionPositionWS = refraction.positionWS;
preLightData.transmissionTransmittance = exp(-bsdfData.absorptionCoefficient * refraction.distance);
// Empirical remap to try to match a bit the refractio probe blurring for the fallback
preLightData.transmissionSSMipLevel = sqrt(bsdfData.perceptualRoughness) * uint(_GaussianPyramidColorMipSize.z);
#else
preLightData.transmissionRefractV = -V;
preLightData.transmissionPositionWS = posInput.positionWS;
preLightData.transmissionTransmittance = float3(1.0, 1.0, 1.0);
preLightData.transmissionSSMipLevel = 0;
#endif
return preLightData;

// This function require the 3 structure surfaceData, builtinData, bsdfData because it may require both the engine side data, and data that will not be store inside the gbuffer.
float3 GetBakedDiffuseLigthing(SurfaceData surfaceData, BuiltinData builtinData, BSDFData bsdfData, PreLightData preLightData)
{
bsdfData.diffuseColor = ApplyDiffuseTexturingMode(bsdfData);
// Premultiply bake diffuse lighting information with DisneyDiffuse pre-integration
return builtinData.bakeDiffuseLighting * preLightData.diffuseFGD * surfaceData.ambientOcclusion * bsdfData.diffuseColor + builtinData.emissiveColor;
}

#ifdef HAS_LIGHTLOOP
//-----------------------------------------------------------------------------
// Lighting structure for light accumulation
//-----------------------------------------------------------------------------
// These structure allow to accumulate lighting accross the Lit material
// AggregateLighting is init to zero and transfer to EvaluateBSDF, but the LightLoop can't access its content.
struct DirectLighting
{
float3 diffuse;
float3 specular;
};
struct IndirectLighting
{
float3 specularReflected;
float3 specularTransmitted;
};
struct AggregateLighting
{
DirectLighting direct;
IndirectLighting indirect;
};
void AccumulateDirectLighting(DirectLighting src, inout AggregateLighting dst)
{
dst.direct.diffuse += src.diffuse;
dst.direct.specular += src.specular;
}
void AccumulateIndirectLighting(IndirectLighting src, inout AggregateLighting dst)
{
dst.indirect.specularReflected += src.specularReflected;
dst.indirect.specularTransmitted += src.specularTransmitted;
}
//-----------------------------------------------------------------------------
// BSDF share between directional light, punctual light and area light (reference)
//-----------------------------------------------------------------------------

float NdotL = saturate(dot(bsdfData.normalWS, L)); // Must have the same value without the clamp
float NdotV = preLightData.NdotV; // Get the unaltered (geometric) version
float LdotV = dot(L, V);
float invLenLV = rsqrt(abs(2 * LdotV + 2)); // invLenLV = rcp(length(L + V))
float invLenLV = rsqrt(max(2 * LdotV + 2, SMALL_FLT_VALUE)); // invLenLV = rcp(length(L + V)) - caution about the case where V and L are opposite, it can happen, use max to avoid this
float NdotH = saturate((NdotL + NdotV) * invLenLV);
float LdotH = saturate(invLenLV * LdotV + invLenLV);

// TODO: Do comparison between this correct version and the one from isotropic and see if there is any visual difference
DV = DV_SmithJointGGXAniso(TdotH, BdotH, NdotH,
preLightData.TdotV, preLightData.BdotV, preLightData.NdotV,
preLightData.TdotV, preLightData.BdotV, NdotV,
TdotL, BdotL, NdotL,
bsdfData.roughnessT, bsdfData.roughnessB
#ifdef LIT_USE_BSDF_PRE_LAMBDAV

#elif LIT_DIFFUSE_GGX_BRDF
float3 diffuseTerm = DiffuseGGX(bsdfData.diffuseColor, NdotV, NdotL, NdotH, LdotV, bsdfData.roughness);
#else
float diffuseTerm = DisneyDiffuse(NdotV, NdotL, LdotV, bsdfData.perceptualRoughness);
// A note on subsurface scattering.
// The correct way to handle SSS is to transmit light inside the surface, perform SSS,
// and then transmit it outside towards the viewer.
// Transmit(X) = F_Transm_Schlick(F0, F90, NdotX), where F0 = 0, F90 = 1.
// Therefore, the diffuse BSDF should be decomposed as follows:
// f_d = A / Pi * F_Transm_Schlick(0, 1, NdotL) * F_Transm_Schlick(0, 1, NdotV) + f_d_reflection,
// with F_Transm_Schlick(0, 1, NdotV) applied after the SSS pass.
// The alternative (artistic) formulation of Disney is to set F90 = 0.5:
// f_d = A / Pi * F_Transm_Schlick(0, 0.5, NdotL) * F_Transm_Schlick(0, 0.5, NdotV) + f_retro_reflection.
// That way, darkening at grading angles is reduced to 0.5.
// In practice, applying F_Transm_Schlick(F0, F90, NdotV) after the SSS pass is expensive,
// as it forces us to read the normal buffer at the end of the SSS pass.
// Separating f_retro_reflection also has a small cost (mostly due to energy compensation
// for multi-bounce GGX), and the visual difference is negligible.
// Therefore, we choose not to separate diffuse lighting into reflected and transmitted.
float diffuseTerm = DisneyDiffuse(NdotV, NdotL, LdotV, bsdfData.perceptualRoughness);
diffuseLighting = bsdfData.diffuseColor * diffuseTerm;
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
diffuseLighting = diffuseTerm;
}
// Currently, we only model diffuse transmission. Specular transmission is not yet supported.

}
else
{
isInBounds = Max3(abs(positionNDC.x), abs(positionNDC.y), 1 - positionLS.z) <= 1;
isInBounds = Max3(abs(positionNDC.x), abs(positionNDC.y), 1.0 - positionLS.z) <= 1.0;
}
// We let the sampler handle tiling or clamping to border.

cookie.a = isInBounds ? cookie.a : 0;
cookie.a = isInBounds ? cookie.a : 0.0;
void EvaluateBSDF_Directional(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput, PreLightData preLightData,
DirectionalLightData lightData, BSDFData bsdfData,
out float3 diffuseLighting,
out float3 specularLighting)
DirectLighting EvaluateBSDF_Directional( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput, PreLightData preLightData,
DirectionalLightData lightData, BSDFData bsdfData, BakeLightingData bakeLightingData)
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
float3 positionWS = posInput.positionWS;
float3 L = -lightData.forward; // Lights are pointing backward in Unity

diffuseLighting = float3(0, 0, 0); // TODO: check whether using 'out' instead of 'inout' increases the VGPR pressure
specularLighting = float3(0, 0, 0); // TODO: check whether using 'out' instead of 'inout' increases the VGPR pressure
float shadow = 1;
float shadow = 1.0;
float shadowMask = 1.0;
#ifdef SHADOWS_SHADOWMASK
// shadowMaskSelector.x is -1 if there is no shadow mask
// Note that we override shadow value (in case we don't have any dynamic shadow)
shadow = shadowMask = (lightData.shadowMaskSelector.x >= 0.0) ? dot(bakeLightingData.bakeShadowMask, lightData.shadowMaskSelector) : 1.0;
#endif
[branch] if (lightData.shadowIndex >= 0)
{

shadow = LOAD_TEXTURE2D(_DeferredShadowTexture, posInput.unPositionSS).x;
#endif
illuminance *= shadow;
#ifdef SHADOWS_SHADOWMASK
float fade = saturate(posInput.depthVS * lightData.fadeDistanceScaleAndBias.x + lightData.fadeDistanceScaleAndBias.y);
// See comment in EvaluateBSDF_Punctual
shadow = lightData.dynamicShadowCasterOnly ? min(shadowMask, shadow) : shadow;
shadow = lerp(shadow, shadowMask, fade); // Caution to lerp parameter: fade is the reverse of shadowDimmer
// Note: There is no shadowDimmer when there is no shadow mask
#endif
illuminance *= shadow;
[branch] if (lightData.cookieIndex >= 0)
{

[branch] if (illuminance > 0.0)
{
BSDF(V, L, positionWS, preLightData, bsdfData, diffuseLighting, specularLighting);
BSDF(V, L, positionWS, preLightData, bsdfData, lighting.diffuse, lighting.specular);
diffuseLighting *= illuminance * lightData.diffuseScale;
specularLighting *= illuminance * lightData.specularScale;
lighting.diffuse *= illuminance * lightData.diffuseScale;
lighting.specular *= illuminance * lightData.specularScale;
// We apply wrapped lighting instead of the regular Lambertian diffuse
// to compensate for approximations within EvaluateTransmission().
float illuminance = Lambert() * ComputeWrappedDiffuseLighting(-NdotL, SSS_WRAP_LIGHT);
// Apply wrapped lighting to better handle thin objects (cards) at grazing angles.
float wrappedNdotL = ComputeWrappedDiffuseLighting(-NdotL, SSS_WRAP_LIGHT);
#ifdef LIT_DIFFUSE_LAMBERT_BRDF
illuminance = Lambert() * wrappedNdotL;
#else
float tNdotL = saturate(-NdotL);
float NdotV = max(preLightData.NdotV, MIN_N_DOT_V);
illuminance = INV_PI * F_Transm_Schlick(0, 0.5, NdotV) * F_Transm_Schlick(0, 0.5, tNdotL) * wrappedNdotL;
#endif
diffuseLighting += EvaluateTransmission(bsdfData, illuminance * lightData.diffuseScale, shadow);
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse += EvaluateTransmission(bsdfData, illuminance * lightData.diffuseScale, shadow);
diffuseLighting *= lightData.color;
specularLighting *= lightData.color;
lighting.diffuse *= lightData.color;
lighting.specular *= lightData.color;
return lighting;
}
//-----------------------------------------------------------------------------

return attenuation * GetAngleAttenuation(L, -lightData.forward, lightData.angleScale, lightData.angleOffset);
}
void EvaluateBSDF_Punctual( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData, int GPULightType,
out float3 diffuseLighting,
out float3 specularLighting)
DirectLighting EvaluateBSDF_Punctual( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData, BakeLightingData bakeLightingData, int GPULightType)
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
float3 positionWS = posInput.positionWS;
int lightType = GPULightType;

lightData.diffuseScale *= attenuation;
lightData.specularScale *= attenuation;
diffuseLighting = float3(0, 0, 0); // TODO: check whether using 'out' instead of 'inout' increases the VGPR pressure
specularLighting = float3(0, 0, 0); // TODO: check whether using 'out' instead of 'inout' increases the VGPR pressure
float shadow = 1;
float shadow = 1.0;
float shadowMask = 1.0;
#ifdef SHADOWS_SHADOWMASK
// shadowMaskSelector.x is -1 if there is no shadow mask
// Note that we override shadow value (in case we don't have any dynamic shadow)
shadow = shadowMask = (lightData.shadowMaskSelector.x >= 0.0) ? dot(bakeLightingData.bakeShadowMask, lightData.shadowMaskSelector) : 1.0;
#endif
[branch] if (lightData.shadowIndex >= 0)
{

shadow = GetPunctualShadowAttenuation(lightLoopContext.shadowContext, positionWS + offset, bsdfData.normalWS, lightData.shadowIndex, L_dist, posInput.unPositionSS);
#ifdef SHADOWS_SHADOWMASK
// Note: Legacy Unity have two shadow mask mode. ShadowMask (ShadowMask contain static objects shadow and ShadowMap contain only dynamic objects shadow, final result is the minimun of both value)
// and ShadowMask_Distance (ShadowMask contain static objects shadow and ShadowMap contain everything and is blend with ShadowMask based on distance (Global distance setup in QualitySettigns)).
// HDRenderPipeline change this behavior. Only ShadowMask mode is supported but we support both blend with distance AND minimun of both value. Distance is control by light.
// The following code do this.
// The min handle the case of having only dynamic objects in the ShadowMap
// The second case for blend with distance is handled with ShadowDimmer. ShadowDimmer is define manually and by shadowDistance by light.
// With distance, ShadowDimmer become one and only the ShadowMask appear, we get the blend with distance behavior.
shadow = lightData.dynamicShadowCasterOnly ? min(shadowMask, shadow) : shadow;
shadow = lerp(shadowMask, shadow, lightData.shadowDimmer);
#else
illuminance *= shadow;
#endif
#ifdef VOLUMETRIC_SHADOWING_ENABLED
float volumetricShadow = Transmittance(OpticalDepthHomogeneous(preLightData.globalFogExtinction, dist));
// Premultiply.
lightData.diffuseScale *= volumetricShadow;
lightData.specularScale *= volumetricShadow;
#endif
illuminance *= shadow;
// Projector lights always have a cookies, so we can perform clipping inside the if().
[branch] if (lightData.cookieIndex >= 0)

[branch] if (illuminance > 0.0)
{
bsdfData.roughness = max(bsdfData.roughness, lightData.minRoughness); // Simulate that a punctual ligth have a radius with this hack
BSDF(V, L, positionWS, preLightData, bsdfData, diffuseLighting, specularLighting);
bsdfData.roughness = max(bsdfData.roughness, lightData.minRoughness); // Simulate that a punctual light have a radius with this hack
BSDF(V, L, positionWS, preLightData, bsdfData, lighting.diffuse, lighting.specular);
diffuseLighting *= illuminance * lightData.diffuseScale;
specularLighting *= illuminance * lightData.specularScale;
lighting.diffuse *= illuminance * lightData.diffuseScale;
lighting.specular *= illuminance * lightData.specularScale;
// We apply wrapped lighting instead of the regular Lambertian diffuse
// to compensate for approximations within EvaluateTransmission().
float illuminance = Lambert() * ComputeWrappedDiffuseLighting(-NdotL, SSS_WRAP_LIGHT);
// Apply wrapped lighting to better handle thin objects (cards) at grazing angles.
float wrappedNdotL = ComputeWrappedDiffuseLighting(-NdotL, SSS_WRAP_LIGHT);
#ifdef LIT_DIFFUSE_LAMBERT_BRDF
illuminance = Lambert() * wrappedNdotL;
#else
float tNdotL = saturate(-NdotL);
float NdotV = max(preLightData.NdotV, MIN_N_DOT_V);
illuminance = INV_PI * F_Transm_Schlick(0, 0.5, NdotV) * F_Transm_Schlick(0, 0.5, tNdotL) * wrappedNdotL;
#endif
diffuseLighting += EvaluateTransmission(bsdfData, illuminance * lightData.diffuseScale, shadow);
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse += EvaluateTransmission(bsdfData, illuminance * lightData.diffuseScale, shadow);
diffuseLighting *= lightData.color;
specularLighting *= lightData.color;
lighting.diffuse *= lightData.color;
lighting.specular *= lightData.color;
return lighting;
}
#include "LitReference.hlsl"

//-----------------------------------------------------------------------------
void EvaluateBSDF_Line(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData,
out float3 diffuseLighting, out float3 specularLighting)
DirectLighting EvaluateBSDF_Line( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData, BakeLightingData bakeLightingData)
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
diffuseLighting, specularLighting);
lighting.diffuse, lighting.specular);
diffuseLighting = float3(0.0, 0.0, 0.0);
specularLighting = float3(0.0, 0.0, 0.0);
float len = lightData.size.x;
float3 T = lightData.right;

axis, invAspectRatio);
// Terminate if the shaded point is too far away.
if (intensity == 0.0) return;
if (intensity == 0.0)
return lighting;
lightData.diffuseScale *= intensity;
lightData.specularScale *= intensity;

{
ltcValue = LTCEvaluate(P1, P2, B, preLightData.ltcTransformDiffuse);
ltcValue *= lightData.diffuseScale;
diffuseLighting = bsdfData.diffuseColor * (preLightData.ltcMagnitudeDiffuse * ltcValue);
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse = preLightData.ltcMagnitudeDiffuse * ltcValue;
}
[branch] if (bsdfData.enableTransmission)

ltcValue *= lightData.diffuseScale;
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
diffuseLighting += EvaluateTransmission(bsdfData, ltcValue, 1);
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse += EvaluateTransmission(bsdfData, ltcValue, 1);
}
// Evaluate the coat part

{
ltcValue = LTCEvaluate(P1, P2, B, preLightData.ltcTransformSpecular);
ltcValue *= lightData.specularScale;
specularLighting += preLightData.ltcMagnitudeFresnel * ltcValue;
lighting.specular += preLightData.ltcMagnitudeFresnel * ltcValue;
diffuseLighting *= lightData.color;
specularLighting *= lightData.color;
lighting.diffuse *= lightData.color;
lighting.specular *= lightData.color;
return lighting;
}
//-----------------------------------------------------------------------------

// #define ELLIPSOIDAL_ATTENUATION
void EvaluateBSDF_Rect( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData,
out float3 diffuseLighting, out float3 specularLighting)
DirectLighting EvaluateBSDF_Rect( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData, BakeLightingData bakeLightingData)
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
diffuseLighting, specularLighting);
lighting.diffuse, lighting.specular);
diffuseLighting = float3(0.0, 0.0, 0.0);
specularLighting = float3(0.0, 0.0, 0.0);
float3 unL = lightData.positionWS - positionWS;
[branch]

return;
return lighting;
}
// Rotate the light direction into the light space.

#endif
// Terminate if the shaded point is too far away.
if (intensity == 0.0) return;
if (intensity == 0.0)
return lighting;
lightData.diffuseScale *= intensity;
lightData.specularScale *= intensity;

// Polygon irradiance in the transformed configuration.
ltcValue = PolygonIrradiance(mul(lightVerts, preLightData.ltcTransformDiffuse));
ltcValue *= lightData.diffuseScale;
diffuseLighting = bsdfData.diffuseColor * (preLightData.ltcMagnitudeDiffuse * ltcValue);
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse = preLightData.ltcMagnitudeDiffuse * ltcValue;
}
[branch] if (bsdfData.enableTransmission)

ltcValue *= lightData.diffuseScale;
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
diffuseLighting += EvaluateTransmission(bsdfData, ltcValue, 1);
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse += EvaluateTransmission(bsdfData, ltcValue, 1);
}
// Evaluate the coat part

// ltcValue = LTCEvaluate(lightVerts, V, bsdfData.coatNormalWS, preLightData.coatNdotV, preLightData.ltcXformClearCoat);
// specularLighting = preLightData.ltcClearCoatFresnelTerm * (ltcValue * bsdfData.coatCoverage);
// lighting.specular = preLightData.ltcClearCoatFresnelTerm * (ltcValue * bsdfData.coatCoverage);
// modify matL value based on Fresnel transmission
// matL = mul(matL, preLightData.ltcCoatT);

// Polygon irradiance in the transformed configuration.
ltcValue = PolygonIrradiance(mul(lightVerts, preLightData.ltcTransformSpecular));
ltcValue *= lightData.specularScale;
specularLighting += preLightData.ltcMagnitudeFresnel * ltcValue;
lighting.specular += preLightData.ltcMagnitudeFresnel * ltcValue;
diffuseLighting *= lightData.color;
specularLighting *= lightData.color;
lighting.diffuse *= lightData.color;
lighting.specular *= lightData.color;
return lighting;
void EvaluateBSDF_Area( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData, int GPULightType,
out float3 diffuseLighting, out float3 specularLighting)
DirectLighting EvaluateBSDF_Area( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightData lightData, BSDFData bsdfData, BakeLightingData bakeLightingData, int GPULightType)
EvaluateBSDF_Line(lightLoopContext, V, posInput, preLightData, lightData, bsdfData, diffuseLighting, specularLighting);
return EvaluateBSDF_Line(lightLoopContext, V, posInput, preLightData, lightData, bsdfData, bakeLightingData);
EvaluateBSDF_Rect(lightLoopContext, V, posInput, preLightData, lightData, bsdfData, diffuseLighting, specularLighting);
return EvaluateBSDF_Rect(lightLoopContext, V, posInput, preLightData, lightData, bsdfData, bakeLightingData);
// EvaluateBSDF_SSL
// EvaluateBSDF_SSLighting for screen space lighting
void EvaluateBSDF_SSL(float3 V, PositionInputs posInput, BSDFData bsdfData, out float3 diffuseLighting, out float3 specularLighting, out float2 weight)
IndirectLighting EvaluateBSDF_SSReflection(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, BSDFData bsdfData,
inout float hierarchyWeight)
{
IndirectLighting lighting;
ZERO_INITIALIZE(IndirectLighting, lighting);
// TODO
return lighting;
}
IndirectLighting EvaluateBSDF_SSRefraction(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, BSDFData bsdfData,
inout float hierarchyWeight)
diffuseLighting = float3(0.0, 0.0, 0.0);
specularLighting = float3(0.0, 0.0, 0.0);
weight = float2(0.0, 0.0);
IndirectLighting lighting;
ZERO_INITIALIZE(IndirectLighting, lighting);
// 3. If this point is available (ie: in color GBuffer and point is not in front of the object)
// 3. If this point is available (ie: in color buffer and point is not in front of the object)
weight.x = bsdfData.transmittanceMask;
float3 refractedBackPointWS = float3(0.0, 0.0, 0.0);
float opticalDepth = 0.0;
uint2 depthSize = uint2(_PyramidDepthMipSize.xy);
// For all refraction approximation, to calculate the refracted point in world space,
// we approximate the scene as a plane (back plane) with normal -V at the depth hit point.
// (We avoid to raymarch the depth texture to get the refracted point.)
#if defined(_REFRACTION_PLANE)
// Plane shape model:
// We approximate locally the shape of the object as a plane with normal {bsdfData.normalWS} at {bsdfData.positionWS}
// with a thickness {bsdfData.thickness}
// Refracted ray
float3 R = refract(-V, bsdfData.normalWS, 1.0 / bsdfData.ior);
// Get the depth of the approximated back plane
float pyramidDepth = LOAD_TEXTURE2D_LOD(_PyramidDepthTexture, posInput.positionSS * (depthSize >> 2), 2).r;
float depth = LinearEyeDepth(pyramidDepth, _ZBufferParams);
// Distance from point to the back plane
float distFromP = depth - posInput.depthVS;
// Optical depth within the thin plane
opticalDepth = bsdfData.thickness / dot(R, -bsdfData.normalWS);
// The refracted ray exiting the thin plane is the same as the incident ray (parallel interfaces and same ior)
float VoR = dot(-V, R);
float VoN = dot(V, bsdfData.normalWS);
refractedBackPointWS = posInput.positionWS + R * opticalDepth - V * (distFromP - VoR * opticalDepth);
#elif defined(_REFRACTION_SPHERE)
// Sphere shape model:
// We approximate locally the shape of the object as sphere, that is tangent to the shape.
// The sphere has a diameter of {bsdfData.thickness}
// The center of the sphere is at {bsdfData.positionWS} - {bsdfData.normalWS} * {bsdfData.thickness}
//
// So the light is refracted twice: in and out of the tangent sphere
// Get the depth of the approximated back plane
float pyramidDepth = LOAD_TEXTURE2D_LOD(_PyramidDepthTexture, posInput.positionSS * (depthSize >> 2), 2).r;
float depth = LinearEyeDepth(pyramidDepth, _ZBufferParams);
// Distance from point to the back plane
float depthFromPosition = depth - posInput.depthVS;
// First refraction (tangent sphere in)
// Refracted ray
float3 R1 = refract(-V, bsdfData.normalWS, 1.0 / bsdfData.ior);
// Center of the tangent sphere
float3 C = posInput.positionWS - bsdfData.normalWS * bsdfData.thickness * 0.5;
// Second refraction (tangent sphere out)
float NoR1 = dot(bsdfData.normalWS, R1);
// Optical depth within the sphere
opticalDepth = -NoR1 * bsdfData.thickness;
// Out hit point in the tangent sphere
float3 P1 = posInput.positionWS + R1 * opticalDepth;
// Out normal
float3 N1 = normalize(C - P1);
// Out refracted ray
float3 R2 = refract(R1, N1, bsdfData.ior);
float N1oR2 = dot(N1, R2);
float VoR1 = dot(V, R1);
// Refracted source point
refractedBackPointWS = P1 - R2 * (depthFromPosition - NoR1 * VoR1 * bsdfData.thickness) / N1oR2;
#endif
float3 refractedBackPointWS = EstimateRaycast(V, posInput, preLightData.transmissionPositionWS, preLightData.transmissionRefractV);
uint2 depthSize = uint2(_PyramidDepthMipSize.xy);
float refractedBackPointDepth = LinearEyeDepth(LOAD_TEXTURE2D_LOD(_PyramidDepthTexture, refractedBackPointSS * depthSize, 0).r, _ZBufferParams);
// Exit if texel is out of color buffer

|| any(refractedBackPointSS > 1.0))
{
diffuseLighting = SAMPLE_TEXTURE2D_LOD(_GaussianPyramidColorTexture, s_trilinear_clamp_sampler, posInput.positionSS, 0.0).rgb;
return;
// Do nothing and don't update the hierarchy weight so we can fall back on refraction probe
return lighting;
float mipLevel = PerceptualRoughnessToMipmapLevel(bsdfData.perceptualRoughness, uint(_GaussianPyramidColorMipSize.z));
diffuseLighting = SAMPLE_TEXTURE2D_LOD(_GaussianPyramidColorTexture, s_trilinear_clamp_sampler, refractedBackPointSS, mipLevel).rgb;
lighting.specularTransmitted = SAMPLE_TEXTURE2D_LOD(_GaussianPyramidColorTexture, s_trilinear_clamp_sampler, refractedBackPointSS, preLightData.transmissionSSMipLevel).rgb;
float3 transmittance = exp(-bsdfData.absorptionCoefficient * opticalDepth);
diffuseLighting *= transmittance;
#endif // HAS_REFRACTION
lighting.specularTransmitted *= preLightData.transmissionTransmittance;
float weight = 1.0;
UpdateLightingHierarchyWeights(hierarchyWeight, weight); // Shouldn't be needed, but safer in case we decide to change hierarchy priority
// We use specularFGD as an approximation of the fresnel effect (that also handle smoothness), so take the remaining for transmission
lighting.specularTransmitted *= (1.0 - preLightData.specularFGD) * weight;
#else
// No refraction, no need to go further
hierarchyWeight = 1.0;
#endif
return lighting;
}
//-----------------------------------------------------------------------------

// _preIntegratedFGD and _CubemapLD are unique for each BRDF
void EvaluateBSDF_Env( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, EnvLightData lightData, BSDFData bsdfData, int envShapeType,
out float3 diffuseLighting, out float3 specularLighting, out float2 weight)
IndirectLighting EvaluateBSDF_Env( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, EnvLightData lightData, BSDFData bsdfData, int envShapeType, int GPUImageBasedLightingType,
inout float hierarchyWeight)
weight = float2(0.0, 1.0);
IndirectLighting lighting;
ZERO_INITIALIZE(IndirectLighting, lighting);
#if !HAS_REFRACTION
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
return lighting;
#endif
float3 envLighting = float3(0.0, 0.0, 0.0);
float weight = 1.0;
specularLighting = IntegrateSpecularGGXIBLRef(lightLoopContext, V, preLightData, lightData, bsdfData);
envLighting = IntegrateSpecularGGXIBLRef(lightLoopContext, V, preLightData, lightData, bsdfData);
// TODO: Do refraction reference (is it even possible ?)
/*
#ifdef LIT_DIFFUSE_LAMBERT_BRDF
diffuseLighting = IntegrateLambertIBLRef(lightData, V, bsdfData);
#else
diffuseLighting = IntegrateDisneyDiffuseIBLRef(lightLoopContext, V, preLightData, lightData, bsdfData);
#endif
*/
diffuseLighting = float3(0.0, 0.0, 0.0);
// #ifdef LIT_DIFFUSE_LAMBERT_BRDF
// envLighting += IntegrateLambertIBLRef(lightData, V, bsdfData);
// #else
// envLighting += IntegrateDisneyDiffuseIBLRef(lightLoopContext, V, preLightData, lightData, bsdfData);
// #endif
weight = 1.0;
#else

float3 R = preLightData.iblDirWS;
float3 coatR = preLightData.coatIblDirWS;
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
{
positionWS = preLightData.transmissionPositionWS;
R = preLightData.transmissionRefractV;
}
// In Unity the cubemaps are capture with the localToWorld transform of the component.
// This mean that location and orientation matter. So after intersection of proxy volume we need to convert back to world.

// 2. Process the influence
float distFade = max(length(positionLS) - lightData.innerDistance.x, 0.0);
weight.y = saturate(1.0 - distFade / max(lightData.blendDistance, 0.0001)); // avoid divide by zero
weight = saturate(1.0 - distFade / max(lightData.blendDistance, 0.0001)); // avoid divide by zero
}
else if (envShapeType == ENVSHAPETYPE_BOX)
{

// Influence volume
// Calculate falloff value, so reflections on the edges of the volume would gradually blend to previous reflection.
float distFade = DistancePointBox(positionLS, -lightData.innerDistance, lightData.innerDistance);
weight.y = saturate(1.0 - distFade / max(lightData.blendDistance, 0.0001)); // avoid divide by zero
weight = saturate(1.0 - distFade / max(lightData.blendDistance, 0.0001)); // avoid divide by zero
weight.y = Smoothstep01(weight.y);
weight = Smoothstep01(weight);
specularLighting = float3(0.0, 0.0, 0.0);
// Evaluate the Clear Coat component if needed and change the BSDF roughness to match Fresnel transmission
if (bsdfData.materialId == MATERIALID_LIT_CLEAR_COAT && HasMaterialFeatureFlag(MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))

// Evaluate the Clear Coat color
float4 preLD = SampleEnv(lightLoopContext, lightData.envIndex, coatR, 0.0);
specularLighting += F * preLD.rgb * bsdfData.coatCoverage;
envLighting += F * preLD.rgb * bsdfData.coatCoverage;
// Change the Fresnel term to account for transmission through Clear Coat and reflection on the base layer.
F = Sqr(-F * bsdfData.coatCoverage + 1.0);

specularLighting += F * preLD.rgb * preLightData.specularFGD;
diffuseLighting = float3(0.0, 0.0, 0.0);
envLighting += F * preLD.rgb;
UpdateLightingHierarchyWeights(hierarchyWeight, weight);
envLighting *= weight;
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
lighting.specularReflected = envLighting * preLightData.specularFGD;
else
// specular transmisted lighting is the remaining of the reflection (let's use this approx)
lighting.specularTransmitted = (1.0 - preLightData.specularFGD) * envLighting * preLightData.transmissionTransmittance;
return lighting;
}
//-----------------------------------------------------------------------------

void PostEvaluateBSDF( LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, LightLoopAccumulatedLighting accLighting, BSDFData bsdfData, float3 bakeDiffuseLighting,
PreLightData preLightData, BSDFData bsdfData, BakeLightingData bakeLightingData, AggregateLighting lighting,
float3 bakeDiffuseLighting = bakeLightingData.bakeDiffuseLighting;
// Use GTAOMultiBounce approximation for ambient occlusion (allow to get a tint from the baseColor)
#define GTAO_MULTIBOUNCE_APPROX 1

// Try to mimic multibounce with specular color. Not the point of the original formula but ok result.
// Take the min of screenspace specular occlusion and visibility cone specular occlusion
#if GTAO_MULTIBOUNCE_APPROX
accLighting.envSpecularLighting *= GTAOMultiBounce(min(bsdfData.specularOcclusion, specularOcclusion), bsdfData.fresnel0);
lighting.indirect.specularReflected *= GTAOMultiBounce(min(bsdfData.specularOcclusion, specularOcclusion), bsdfData.fresnel0);
accLighting.envSpecularLighting *= lerp(_AmbientOcclusionParam.rgb, float3(1.0, 1.0, 1.0), min(bsdfData.specularOcclusion, specularOcclusion));
lighting.indirect.specularReflected *= lerp(_AmbientOcclusionParam.rgb, float3(1.0, 1.0, 1.0), min(bsdfData.specularOcclusion, specularOcclusion));
// TODO: we could call a function like PostBSDF that will apply albedo and divide by PI once for the loop
float3 directDiffuseLighting = (accLighting.dirDiffuseLighting + accLighting.punctualDiffuseLighting + accLighting.areaDiffuseLighting)
lighting.direct.diffuse *=
* GTAOMultiBounce(directAmbientOcclusion, bsdfData.diffuseColor);
GTAOMultiBounce(directAmbientOcclusion, bsdfData.diffuseColor);
* lerp(_AmbientOcclusionParam.rgb, float3(1.0, 1.0, 1.0), directAmbientOcclusion);
lerp(_AmbientOcclusionParam.rgb, float3(1.0, 1.0, 1.0), directAmbientOcclusion);
// envDiffuseLighting is used for refraction in this Lit material. Use the weight to balance between transmission and reflection
diffuseLighting = lerp(directDiffuseLighting + bakeDiffuseLighting, accLighting.envDiffuseLighting, accLighting.envDiffuseLightingWeight);
specularLighting = accLighting.dirSpecularLighting + accLighting.punctualSpecularLighting + accLighting.areaSpecularLighting + accLighting.envSpecularLighting;
float3 modifiedDiffuseColor = ApplyDiffuseTexturingMode(bsdfData);
// Apply the albedo to the direct diffuse lighting (only once). The indirect (baked)
// diffuse lighting has already had the albedo applied in GetBakedDiffuseLigthing().
diffuseLighting = modifiedDiffuseColor * lighting.direct.diffuse + bakeDiffuseLighting;
// If refraction is enable we use the transmittanceMask to lerp between current diffuse lighting and refraction value
// Physically speaking, it should be transmittanceMask should be 1, but for artistic reasons, we let the value vary
#if HAS_REFRACTION
diffuseLighting = lerp(diffuseLighting, lighting.indirect.specularTransmitted, bsdfData.transmittanceMask);
#endif
specularLighting = lighting.direct.specular + lighting.indirect.specularReflected;
specularLighting *= 1 + bsdfData.fresnel0 * preLightData.energyCompensation;
specularLighting *= 1.0 + bsdfData.fresnel0 * preLightData.energyCompensation;
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_OCCLUSION_FROM_SSAO)

#endif
#endif
}
#endif // #ifdef HAS_LIGHTLOOP

52
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader


_SubsurfaceRadiusMap("Subsurface Radius Map", 2D) = "white" {}
_Thickness("Thickness", Range(0.0, 1.0)) = 1.0
_ThicknessMap("Thickness Map", 2D) = "white" {}
_ThicknessRemap("Thickness Remap", Vector) = (0, 1, 0, 0)
_CoatCoverage("Coat Coverage", Range(0.0, 1.0)) = 1.0
_CoatIOR("Coat IOR", Range(0.0, 1.0)) = 0.5

// These option below will cause different compilation flag.
[ToggleOff] _EnableSpecularOcclusion("Enable specular occlusion", Float) = 0.0
_EmissiveColor("EmissiveColor", Color) = (0, 0, 0)
_EmissiveColor("EmissiveColor", Color) = (1, 1, 1)
_EmissiveColorMap("EmissiveColorMap", 2D) = "white" {}
_EmissiveIntensity("EmissiveIntensity", Float) = 0
[ToggleOff] _AlbedoAffectEmissive("Albedo Affect Emissive", Float) = 0.0

_IOR("Indice Of Refraction", Range(1.0, 2.5)) = 1.0
_ThicknessMultiplier("Thickness Multiplier", Float) = 1.0
_TransmittanceColor("Transmittance Color", Color) = (1.0, 1.0, 1.0)
_TransmittanceColorMap("TransmittanceColorMap", 2D) = "white" {}
_ATDistance("Transmittance Absorption Distance", Float) = 1.0
[ToggleOff] _PreRefractionPass("PreRefractionPass", Float) = 0.0

// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.
// TODO: Fix the code in legacy unity so we can customize the beahvior for GI
_EmissionColor("Color", Color) = (1, 1, 1)
// HACK: GI Baking system relies on some properties existing in the shader ("_MainTex", "_Cutoff" and "_Color") for opacity handling, so we need to store our version of those parameters in the hard-coded name the GI baking system recognizes.
_MainTex("Albedo", 2D) = "white" {}
_Color("Color", Color) = (1,1,1,1)
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go futher in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go futher in dev
//#pragma enable_d3d11_debug_symbols
//-------------------------------------------------------------------------------------

#pragma shader_feature _SUBSURFACE_RADIUS_MAP
#pragma shader_feature _THICKNESSMAP
#pragma shader_feature _SPECULARCOLORMAP
#pragma shader_feature _TRANSMITTANCECOLORMAP
// Keyword for transparent
#pragma shader_feature _SURFACE_TYPE_TRANSPARENT

// Note _MATID_STANDARD is not define as there is always the default case "_". We assign default as _MATID_STANDARD, so we never test _MATID_STANDARD
#pragma shader_feature _ _MATID_SSS _MATID_ANISO _MATID_SPECULAR _MATID_CLEARCOAT
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
// TODO: We should have this keyword only if VelocityInGBuffer is enable, how to do that ?

}
HLSLPROGRAM
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"

HLSLPROGRAM
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"

HLSLPROGRAM
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define DEBUG_DISPLAY
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"

#define SHADERPASS SHADERPASS_LIGHT_TRANSPORT
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/LitMetaPass.hlsl"
#include "ShaderPass/LitSharePass.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"

Cull[_CullMode]
ZClip Off
ZClip [_ZClip]
ZWrite On
ZTest LEqual

HLSLPROGRAM
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
// TEMP until pragma work in include
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#include "../../Lighting/Lighting.hlsl"
#include "ShaderPass/LitSharePass.hlsl"
#include "LitData.hlsl"

HLSLPROGRAM
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
// TEMP until pragma work in include
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#include "../../Lighting/Lighting.hlsl"
#include "ShaderPass/LitSharePass.hlsl"
#include "LitData.hlsl"

17
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl


builtinData.bakeDiffuseLighting += SampleBakedGI(input.positionWS, -input.worldToTangent[2], input.texCoord1, input.texCoord2) * bsdfData.transmittance;
}
#ifdef SHADOWS_SHADOWMASK
float4 shadowMask = SampleShadowMask(input.positionWS, input.texCoord1);
builtinData.shadowMask0 = shadowMask.x;
builtinData.shadowMask1 = shadowMask.y;
builtinData.shadowMask2 = shadowMask.z;
builtinData.shadowMask3 = shadowMask.w;
#else
builtinData.shadowMask0 = 0.0;
builtinData.shadowMask1 = 0.0;
builtinData.shadowMask2 = 0.0;
builtinData.shadowMask3 = 0.0;
#endif
builtinData.emissiveColor *= SAMPLE_TEXTURE2D(_EmissiveColorMap, sampler_EmissiveColorMap, input.texCoord0).rgb;
builtinData.emissiveColor *= SAMPLE_TEXTURE2D(_EmissiveColorMap, sampler_EmissiveColorMap, TRANSFORM_TEX(input.texCoord0, _EmissiveColorMap)).rgb;
float3 distortion = SAMPLE_TEXTURE2D(_DistortionVectorMap, sampler_DistortionVectorMap, input.texCoord0).rgb;
float3 distortion = SAMPLE_TEXTURE2D(_DistortionVectorMap, sampler_DistortionVectorMap, input.texCoord0).rgb * 2.0 - 1.0;
builtinData.distortion = distortion.rg * _DistortionScale;
builtinData.distortionBlur = clamp(distortion.b * _DistortionBlurScale, 0.0, 1.0) * (_DistortionBlurRemapMax - _DistortionBlurRemapMin) + _DistortionBlurRemapMin;
#else

10
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataIndividualLayer.hlsl


surfaceData.subsurfaceProfile = ADD_IDX(_SubsurfaceProfile);
surfaceData.subsurfaceRadius = ADD_IDX(_SubsurfaceRadius);
surfaceData.thickness = ADD_IDX(_Thickness);
#ifdef _SUBSURFACE_RADIUS_MAP_IDX
surfaceData.subsurfaceRadius *= SAMPLE_UVMAPPING_TEXTURE2D(ADD_IDX(_SubsurfaceRadiusMap), SAMPLER_SUBSURFACE_RADIUSMAP_IDX, ADD_IDX(layerTexCoord.base)).r;

surfaceData.thickness *= SAMPLE_UVMAPPING_TEXTURE2D(ADD_IDX(_ThicknessMap), SAMPLER_THICKNESSMAP_IDX, ADD_IDX(layerTexCoord.base)).r;
surfaceData.thickness = SAMPLE_UVMAPPING_TEXTURE2D(ADD_IDX(_ThicknessMap), SAMPLER_THICKNESSMAP_IDX, ADD_IDX(layerTexCoord.base)).r;
surfaceData.thickness = ADD_IDX(_ThicknessRemap).x + ADD_IDX(_ThicknessRemap).y * surfaceData.thickness;
#else
surfaceData.thickness = ADD_IDX(_Thickness);
#endif
// This part of the code is not used in case of layered shader but we keep the same macro system for simplicity

#if HAS_REFRACTION
surfaceData.ior = _IOR;
surfaceData.transmittanceColor = _TransmittanceColor;
#ifdef _TRANSMITTANCECOLORMAP
surfaceData.transmittanceColor *= SAMPLE_UVMAPPING_TEXTURE2D(ADD_IDX(_TransmittanceColorMap), ADD_ZERO_IDX(sampler_TransmittanceColorMap), ADD_IDX(layerTexCoord.base)).rgb;
#endif
surfaceData.atDistance = _ATDistance;
// Thickness already defined with SSS (from both thickness and thicknessMap)
surfaceData.thickness *= _ThicknessMultiplier;

6
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitProperties.hlsl


TEXTURE2D(_SpecularColorMap);
SAMPLER2D(sampler_SpecularColorMap);
TEXTURE2D(_TransmittanceColorMap);
SAMPLER2D(sampler_TransmittanceColorMap);
#else
// Set of users variables

// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.
// TODO: Fix the code in legacy unity so we can customize the beahvior for GI
float3 _EmissionColor;
float4 _EmissiveColorMap_ST;
float4 _InvPrimScale; // Only XY are used

int _SubsurfaceProfile;
float _SubsurfaceRadius;
float _Thickness;
float4 _ThicknessRemap;
float _CoatCoverage;
float _CoatIOR;

PROP_DECL(int, _SubsurfaceProfile);
PROP_DECL(float, _SubsurfaceRadius);
PROP_DECL(float, _Thickness);
PROP_DECL(float4, _ThicknessRemap);
PROP_DECL(float, _OpacityAsDensity);
float _InheritBaseNormal1;

8
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitReference.hlsl


{
float4 val = SampleEnv(lightLoopContext, lightData.envIndex, L, 0);
// diffuse Albedo is apply here as describe in ImportanceSampleLambert function
acc += bsdfData.diffuseColor * LambertNoPI() * weightOverPdf * val.rgb;
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
acc += LambertNoPI() * weightOverPdf * val.rgb;
}
}

// in weightOverPdf of ImportanceSampleLambert call.
float disneyDiffuse = DisneyDiffuse(NdotV, NdotL, LdotV, bsdfData.perceptualRoughness);
// diffuse Albedo is apply here as describe in ImportanceSampleLambert function
acc += bsdfData.diffuseColor * disneyDiffuse * weightOverPdf * val.rgb;
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
acc += disneyDiffuse * weightOverPdf * val.rgb;
}
}

52
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader


_SubsurfaceRadiusMap("Subsurface Radius Map", 2D) = "white" {}
_Thickness("Thickness", Range(0.0, 1.0)) = 1.0
_ThicknessMap("Thickness Map", 2D) = "white" {}
_ThicknessRemap("Thickness Remap", Vector) = (0, 1, 0, 0)
_CoatCoverage("Coat Coverage", Range(0.0, 1.0)) = 1.0
_CoatIOR("Coat IOR", Range(0.0, 1.0)) = 0.5

// These option below will cause different compilation flag.
[ToggleOff] _EnableSpecularOcclusion("Enable specular occlusion", Float) = 0.0
_EmissiveColor("EmissiveColor", Color) = (0, 0, 0)
_EmissiveColor("EmissiveColor", Color) = (1, 1, 1)
_EmissiveColorMap("EmissiveColorMap", 2D) = "white" {}
_EmissiveIntensity("EmissiveIntensity", Float) = 0
[ToggleOff] _AlbedoAffectEmissive("Albedo Affect Emissive", Float) = 0.0

_IOR("Indice Of Refraction", Range(1.0, 2.5)) = 1.0
_ThicknessMultiplier("Thickness Multiplier", Float) = 1.0
_TransmittanceColor("Transmittance Color", Color) = (1.0, 1.0, 1.0)
_TransmittanceColorMap("TransmittanceColorMap", 2D) = "white" {}
_ATDistance("Transmittance Absorption Distance", Float) = 1.0
[ToggleOff] _PreRefractionPass("PreRefractionPass", Float) = 0.0

_TessellationShapeFactor("Tessellation shape factor", Range(0.0, 1.0)) = 0.75 // Only use with Phong
_TessellationBackFaceCullEpsilon("Tessellation back face epsilon", Range(-1.0, 0.0)) = -0.25
// TODO: Handle culling mode for backface culling
// HACK: GI Baking system relies on some properties existing in the shader ("_MainTex", "_Cutoff" and "_Color") for opacity handling, so we need to store our version of those parameters in the hard-coded name the GI baking system recognizes.
_MainTex("Albedo", 2D) = "white" {}
_Color("Color", Color) = (1,1,1,1)
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
#pragma only_renderers d3d11 ps4// TEMP: until we go futher in dev
#pragma only_renderers d3d11 ps4 vulkan// TEMP: until we go futher in dev
// #pragma enable_d3d11_debug_symbols
//-------------------------------------------------------------------------------------

#pragma shader_feature _SUBSURFACE_RADIUS_MAP
#pragma shader_feature _THICKNESSMAP
#pragma shader_feature _SPECULARCOLORMAP
#pragma shader_feature _TRANSMITTANCECOLORMAP
// Keyword for transparent
#pragma shader_feature _SURFACE_TYPE_TRANSPARENT

// Note _MATID_STANDARD is not define as there is always the default case "_". We assign default as _MATID_STANDARD, so we never test _MATID_STANDARD
#pragma shader_feature _ _MATID_SSS _MATID_ANISO _MATID_SPECULAR _MATID_CLEARCOAT
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
// TODO: We should have this keyword only if VelocityInGBuffer is enable, how to do that ?

#pragma hull Hull
#pragma domain Domain
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"

#pragma hull Hull
#pragma domain Domain
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define SHADERPASS SHADERPASS_GBUFFER
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"

#pragma hull Hull
#pragma domain Domain
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#define DEBUG_DISPLAY
#define SHADERPASS SHADERPASS_GBUFFER
#include "../../ShaderVariables.hlsl"

#define SHADERPASS SHADERPASS_LIGHT_TRANSPORT
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/LitMetaPass.hlsl"
#include "ShaderPass/LitSharePass.hlsl"
#include "LitData.hlsl"
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"

Cull[_CullMode]
ZClip Off
ZClip [_ZClip]
ZWrite On
ZTest LEqual

#pragma hull Hull
#pragma domain Domain
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
// TEMP until pragma work in include
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#include "../../Lighting/Lighting.hlsl"
#include "ShaderPass/LitSharePass.hlsl"
#include "LitData.hlsl"

#pragma hull Hull
#pragma domain Domain
#pragma multi_compile LIGHTMAP_OFF LIGHTMAP_ON
#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
// TEMP until pragma work in include
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#include "../../Lighting/Lighting.hlsl"
#include "ShaderPass/LitSharePass.hlsl"
#include "LitData.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CombineLighting.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#pragma vertex Vert

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/CopyStencilBuffer.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma multi_compile _ EXPORT_HTILE
// #pragma enable_d3d11_debug_symbols

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/PreIntegratedFGD.shader


#pragma vertex Vert
#pragma fragment Frag
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#include "../../../../Core/ShaderLibrary/Common.hlsl"
#include "../../../../Core/ShaderLibrary/ImageBasedLighting.hlsl"

106
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.compute


// Tweak parameters.
#define SSS_BILATERAL_FILTER 1
#define SSS_USE_LDS_CACHE 1
#define SSS_ENABLE_NEAR_FIELD 0
#define SSS_SAMPLE_TEST_HTILE 0
#define SSS_USE_TANGENT_PLANE 0
#define SSS_CLAMP_ARTIFACT 0
#define SSS_ENABLE_NEAR_FIELD 0 // Greatly increases the number of samples. Comes at a high cost.
#define SSS_SAMPLE_TEST_HTILE 0 // Potential optimization. YMMV.
#define SSS_USE_TANGENT_PLANE 0 // Improves the accuracy of the approximation(0 -> 1st order). High cost. Does not work with back-facing normals.
#define SSS_CLAMP_ARTIFACT 0 // Reduces bleeding. Use with SSS_USE_TANGENT_PLANE.
#define SSS_DEBUG_LOD 0
#define SSS_DEBUG_NORMAL_VS 0

#define GROUP_SIZE_2D (GROUP_SIZE_1D * GROUP_SIZE_1D)
#define TEXTURE_CACHE_BORDER 2
#define TEXTURE_CACHE_SIZE_1D (GROUP_SIZE_1D + 2 * TEXTURE_CACHE_BORDER)
// Check for support of typed UAV loads from FORMAT_R16G16B16A16_FLOAT.
// TODO: query the format support more precisely.
#if !(defined(SHADER_API_PSSL) || defined(SHADER_API_XBOXONE))
#define USE_INTERMEDIATE_BUFFER
#endif
//--------------------------------------------------------------------------------------------------
// Included headers

float4 _WorldScales[SSS_N_PROFILES]; // Size of the world unit in meters (only the X component is used)
float4 _FilterKernels[SSS_N_PROFILES][SSS_N_SAMPLES_NEAR_FIELD]; // XY = near field, ZW = far field; 0 = radius, 1 = reciprocal of the PDF
DECLARE_GBUFFER_TEXTURE(_GBufferTexture); // Contains the albedo and SSS parameters
TEXTURE2D(_DepthTexture); // Z-buffer
TEXTURE2D(_StencilTexture); // DXGI_FORMAT_R8_UINT is not supported by Unity
TEXTURE2D(_HTile); // DXGI_FORMAT_R8_UINT is not supported by Unity
TEXTURE2D(_IrradianceSource); // Includes transmitted light
RW_TEXTURE2D(float4, _CameraFilteringTexture); // Target texture
DECLARE_GBUFFER_TEXTURE(_GBufferTexture); // Contains the albedo and SSS parameters
TEXTURE2D(_DepthTexture); // Z-buffer
TEXTURE2D(_HTile); // DXGI_FORMAT_R8_UINT is not supported by Unity
TEXTURE2D(_IrradianceSource); // Includes transmitted light
#ifdef USE_INTERMEDIATE_BUFFER
RW_TEXTURE2D(float4, _CameraFilteringTexture); // Target texture
#else
RW_TEXTURE2D(float4, _CameraColorTexture); // Target texture
#endif
//--------------------------------------------------------------------------------------------------
// Implementation

bool passedStencilTest;
#if SSS_SAMPLE_TEST_HTILE
int2 tileCoord = pixelCoord >> 3; // Divide by 8
int2 tileCoord = pixelCoord / 8;
// Perform the stencil test (reject at the tile rate).
passedStencilTest = stencilRef == LOAD_TEXTURE2D(_HTile, tileCoord).r;

{
// Unfortunately, our copy of HTile does not allow to accept at the tile rate.
// Therefore, we have to additionally perform the stencil test at the pixel rate.
passedStencilTest = (uint)stencilRef == UnpackByte(LOAD_TEXTURE2D(_StencilTexture, pixelCoord).r);
// We check the tagged irradiance buffer to avoid an extra stencil texture fetch.
passedStencilTest = TestLightingForSSS(LOAD_TEXTURE2D(_IrradianceSource, pixelCoord).rgb);
}
return passedStencilTest;

}
}
// Computes the value of the integrand over a disk: (2 * PI * r) * KernelVal().
// N.b.: the returned value is multiplied by 4. It is irrelevant due to weight renormalization.
float3 KernelValCircle(float r, float3 S)
// Computes the value of the integrand in polar coordinates: f(r, s) = r * R(r, s).
// f(r, s) = (Exp[-r * s] + Exp[-r * s / 3]) * (s / (8 * Pi))
// We can drop the constant (s / (8 * Pi)) due to the subsequent weight renormalization.
float3 DisneyProfilePolar(float r, float3 S)
#if 0
return /* 0.25 * */ S * (expOneThird + expOneThird * expOneThird * expOneThird);
#else
// Help the compiler.
float k = (-1.0 / 3.0) * LOG2_E;
float3 p = (k * r) * S;
float3 expOneThird = exp2(p);
#endif
return expOneThird + expOneThird * expOneThird * expOneThird;
// Computes F(r)/P(r), s.t. r = sqrt(xy^2 + z^2).
// Computes f(r, s)/p(r, s), s.t. r = sqrt(xy^2 + z^2).
// Rescaling of the PDF is handled by 'totalWeight'.
float3 ComputeBilateralWeight(float xy2, float z, float mmPerUnit, float3 S, float rcpPdf)
{

#endif
#if SSS_CLAMP_ARTIFACT
return saturate(KernelValCircle(r, S) * rcpPdf);
return saturate(DisneyProfilePolar(r, S) * rcpPdf);
return KernelValCircle(r, S) * rcpPdf;
return DisneyProfilePolar(r, S) * rcpPdf;
#endif
}

float4 textureSample = LoadSample(position, cacheAnchor);
float3 irradiance = textureSample.rgb;
float linearDepth = textureSample.a;
if (linearDepth > 0)
if (TestLightingForSSS(irradiance))
float linearDepth = textureSample.a;
float z = linearDepth - centerPosVS.z;
float p = _FilterKernels[profileID][i][iP];
float3 w = ComputeBilateralWeight(xy2, z, mmPerUnit, shapeParam, p);

}
else
{
// The irradiance is 0. This could happen for 2 reasons.
// Most likely, the surface fragment does not have an SSS material.
// Alternatively, our sample comes from a region without any geometry.
// Our blur is energy-preserving, so 'centerWeight' should be set to 0.
// We do not terminate the loop since we want to gather the contribution
// of the remaining samples (e.g. in case of hair covering skin).
}
}
void StoreResult(uint2 pixelCoord, float3 irradiance)
{
#ifdef USE_INTERMEDIATE_BUFFER
_CameraFilteringTexture[pixelCoord] = float4(irradiance, 1);
#else
_CameraColorTexture[pixelCoord] += float4(irradiance, 0);
#endif
}
#pragma kernel SubsurfaceScattering

uint groupThreadId : SV_GroupThreadID)
{
// Note: any factor of 64 is a suitable wave size for our algorithm.
uint waveIndex = groupThreadId / 64;
uint waveIndex = WaveReadFirstLane(groupThreadId / 64);
uint laneIndex = groupThreadId % 64;
uint quadIndex = laneIndex / 4;

float3 centerIrradiance = 0;
float centerDepth = 0;
float4 cachedValue = float4(0, 0, 0, 0);
float4 cachedValue = 0;
bool passedStencilTest = StencilTest((int2)pixelCoord, stencilRef);

uint2 cacheCoord2 = 2 * (startQuad + quadCoord) + uint2(laneIndex & 1, (laneIndex >> 1) & 1);
int2 pixelCoord2 = (int2)(tileAnchor + cacheCoord2) - TEXTURE_CACHE_BORDER;
float4 cachedValue2 = float4(0, 0, 0, 0);
float4 cachedValue2 = 0;
[branch] if (StencilTest(pixelCoord2, stencilRef))
{

// don't want the orientation of the tangent plane to create
// divergence of execution across the warp.
float maxDistInPixels = maxDistance * max(pixelsPerMm.x, pixelsPerMm.y);
float3 albedo = ApplyDiffuseTexturingMode(bsdfData);
_CameraFilteringTexture[pixelCoord] = float4(0, 0, 1, 1);
StoreResult(pixelCoord, float3(0, 0, 1));
_CameraFilteringTexture[pixelCoord] = float4(bsdfData.diffuseColor * centerIrradiance, 1);
StoreResult(pixelCoord, albedo * centerIrradiance);
#endif
return;
}

float3 tangentY = GetLocalFrame(normalVS)[1] * unitsPerMm;
#if SSS_DEBUG_NORMAL_VS
// We expect the view-space normal to be front-facing.
if (normalVS.z >= 0)
// We expect the normal to be front-facing.
float3 viewDirVS = normalize(centerPosVS);
if (dot(normalVS, viewDirVS) >= 0)
_CameraFilteringTexture[pixelCoord] = float4(1, 1, 1, 1);
StoreResult(pixelCoord, float3(1, 1, 1));
return;
}
#endif

#if SSS_DEBUG_LOD
_CameraFilteringTexture[pixelCoord] = useNearFieldKernel ? float4(1, 0, 0, 1) : float4(0.5, 0.5, 0, 1);
StoreResult(pixelCoord, useNearFieldKernel ? float3(1, 0, 0) : float3(0.5, 0.5, 0);
return;
#endif

float centerRadius = _FilterKernels[profileID][0][iR];
float centerRcpPdf = _FilterKernels[profileID][0][iP];
float3 centerWeight = KernelValCircle(centerRadius, shapeParam) * centerRcpPdf;
float3 centerWeight = DisneyProfilePolar(centerRadius, shapeParam) * centerRcpPdf;
// Accumulate filtered irradiance and bilateral weights (for renormalization).
float3 totalIrradiance = centerWeight * centerIrradiance;

[branch] if (!useNearFieldKernel)
{
_CameraFilteringTexture[pixelCoord] = float4(bsdfData.diffuseColor * totalIrradiance / totalWeight, 1);
StoreResult(pixelCoord, albedo * totalIrradiance / totalWeight);
return;
}

totalIrradiance, totalWeight);
}
_CameraFilteringTexture[pixelCoord] = float4(bsdfData.diffuseColor * totalIrradiance / totalWeight, 1);
StoreResult(pixelCoord, albedo * totalIrradiance / totalWeight);
}

16
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
// #pragma enable_d3d11_debug_symbols
#pragma vertex Vert

float halfRcpVariance = _HalfRcpWeightedVariances[profileID].a;
#endif
float3 albedo = ApplyDiffuseTexturingMode(bsdfData);
bsdfData.diffuseColor = float3(1, 1, 1);
albedo = float3(1, 1, 1);
#endif
// Take the first (central) sample.

#if SSS_DEBUG_LOD
return float4(0, 0, 1, 1);
#else
return float4(bsdfData.diffuseColor * sampleIrradiance, 1);
return float4(albedo * sampleIrradiance, 1);
#endif
}

sampleWeight = _FilterKernelsBasic[profileID][i].rgb;
sampleIrradiance = LOAD_TEXTURE2D(_IrradianceSource, samplePosition).rgb;
[flatten]
if (any(sampleIrradiance))
if (TestLightingForSSS(sampleIrradiance))
{
// Apply bilateral weighting.
// Ref #1: Skin Rendering by Pseudo–Separable Cross Bilateral Filtering.

}
else
{
// The irradiance is 0. This could happen for 3 reasons.
// The irradiance is 0. This could happen for 2 reasons.
// Finally, the surface fragment could be completely shadowed.
// Our blur is energy-preserving, so 'centerWeight' should be set to 0.
// We do not terminate the loop since we want to gather the contribution
// of the remaining samples (e.g. in case of hair covering skin).

return float4(bsdfData.diffuseColor * totalIrradiance / totalWeight, 1);
return float4(albedo * totalIrradiance / totalWeight, 1);
}
ENDHLSL
}

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitSharePass.hlsl


#define ATTRIBUTES_NEED_TEXCOORD1
#define ATTRIBUTES_NEED_COLOR
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3) || defined(DYNAMICLIGHTMAP_ON) || defined(DEBUG_DISPLAY)
#if defined(_REQUIRE_UV2) || defined(_REQUIRE_UV3) || defined(DYNAMICLIGHTMAP_ON) || defined(DEBUG_DISPLAY) || (SHADERPASS == SHADERPASS_LIGHT_TRANSPORT)
#define ATTRIBUTES_NEED_TEXCOORD2
#endif
#if defined(_REQUIRE_UV3) || defined(DEBUG_DISPLAY)

100
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs


[GenerateHLSL]
public class SssConstants
{
public const int SSS_N_PROFILES = 16; // Max. number of profiles, including the slot taken by the neutral profile
public const int SSS_NEUTRAL_PROFILE_ID = SSS_N_PROFILES - 1; // Does not result in blurring
public const int SSS_N_PROFILES = 16; // Max. number of profiles, including the slot taken by the neutral profile
public const int SSS_NEUTRAL_PROFILE_ID = 0; // Does not result in blurring
public const int SSS_N_SAMPLES_NEAR_FIELD = 55; // Used for extreme close ups; must be a Fibonacci number
public const int SSS_N_SAMPLES_FAR_FIELD = 21; // Used at a regular distance; must be a Fibonacci number
public const int SSS_LOD_THRESHOLD = 4; // The LoD threshold of the near-field kernel (in pixels)

// We importance sample the color channel with the widest scattering distance.
float s = Mathf.Min(shapeParam.x, shapeParam.y, shapeParam.z);
// Importance sample the normalized diffusion profile for the computed value of 's'.
// Importance sample the normalized diffuse reflectance profile for the computed value of 's'.
// R(r, s) = s * (Exp[-r * s] + Exp[-r * s / 3]) / (8 * Pi * r)
// PDF(r, s) = s * (Exp[-r * s] + Exp[-r * s / 3]) / 4
// CDF(r, s) = 1 - 1/4 * Exp[-r * s] - 3/4 * Exp[-r * s / 3]
// R[r, phi, s] = s * (Exp[-r * s] + Exp[-r * s / 3]) / (8 * Pi * r)
// PDF[r, phi, s] = r * R[r, phi, s]
// CDF[r, s] = 1 - 1/4 * Exp[-r * s] - 3/4 * Exp[-r * s / 3]
// ------------------------------------------------------------------------------------
// Importance sample the near field kernel.

float r = KernelCdfInverse(p, s);
float r = DisneyProfileCdfInverse(p, s);
filterKernelNearField[i].y = 1f / KernelPdf(r, s);
filterKernelNearField[i].y = 1f / DisneyProfilePdf(r, s);
}
// Importance sample the far field kernel.

float r = KernelCdfInverse(p, s);
float r = DisneyProfileCdfInverse(p, s);
filterKernelFarField[i].y = 1f / KernelPdf(r, s);
filterKernelFarField[i].y = 1f / DisneyProfilePdf(r, s);
}
maxRadius = filterKernelFarField[SssConstants.SSS_N_SAMPLES_FAR_FIELD - 1].x;

}
// <<< Old SSS Model
static float KernelVal(float r, float s)
static float DisneyProfile(float r, float s)
// Computes the value of the integrand over a disk: (2 * PI * r) * KernelVal().
static float KernelValCircle(float r, float s)
{
return 0.25f * s * (Mathf.Exp(-r * s) + Mathf.Exp(-r * s * (1.0f / 3.0f)));
}
static float KernelPdf(float r, float s)
static float DisneyProfilePdf(float r, float s)
return KernelValCircle(r, s);
return r * DisneyProfile(r, s);
static float KernelCdf(float r, float s)
static float DisneyProfileCdf(float r, float s)
static float KernelCdfDerivative1(float r, float s)
static float DisneyProfileCdfDerivative1(float r, float s)
static float KernelCdfDerivative2(float r, float s)
static float DisneyProfileCdfDerivative2(float r, float s)
{
return (-1.0f / 12.0f) * s * s * Mathf.Exp(-r * s) * (3.0f + Mathf.Exp(r * s * (2.0f / 3.0f)));
}

static float KernelCdfInverse(float p, float s)
static float DisneyProfileCdfInverse(float p, float s)
{
// Supply the initial guess.
float r = (Mathf.Pow(10f, p) - 1f) / s;

{
float f0 = KernelCdf(r, s) - p;
float f1 = KernelCdfDerivative1(r, s);
float f2 = KernelCdfDerivative2(r, s);
float f0 = DisneyProfileCdf(r, s) - p;
float f1 = DisneyProfileCdfDerivative1(r, s);
float f2 = DisneyProfileCdfDerivative2(r, s);
float dr = f0 / (f1 * (1f - f0 * f2 / (2f * f1 * f1)));
if (Mathf.Abs(dr) < t)

void OnEnable()
{
if (profiles != null && profiles.Length != SssConstants.SSS_NEUTRAL_PROFILE_ID)
Array.Resize(ref profiles, SssConstants.SSS_NEUTRAL_PROFILE_ID);
// The neutral profile is not a part of the array.
int profileArraySize = SssConstants.SSS_N_PROFILES - 1;
if (profiles != null && profiles.Length != profileArraySize)
Array.Resize(ref profiles, profileArraySize);
profiles = new SubsurfaceScatteringProfile[SssConstants.SSS_NEUTRAL_PROFILE_ID];
profiles = new SubsurfaceScatteringProfile[profileArraySize];
for (int i = 0; i < SssConstants.SSS_NEUTRAL_PROFILE_ID; i++)
for (int i = 0; i < profileArraySize; i++)
profiles[i] = new SubsurfaceScatteringProfile("Profile " + i);
profiles[i] = new SubsurfaceScatteringProfile("Profile " + (i + 1));
profiles[i].Validate();
}

ValidateArray(ref halfRcpVariancesAndWeights, SssConstants.SSS_N_PROFILES * 2);
ValidateArray(ref filterKernelsBasic, SssConstants.SSS_N_PROFILES * SssConstants.SSS_BASIC_N_SAMPLES);
Debug.Assert(SssConstants.SSS_NEUTRAL_PROFILE_ID < 16, "Transmission flags (32-bit integer) cannot support more than 16 profiles.");
Debug.Assert(SssConstants.SSS_NEUTRAL_PROFILE_ID < 16, "Transmission flags (32-bit integer) cannot support more than 16 profiles (2 bits per profile).");
UpdateCache();
}

// <<< Old SSS Model
}
public void UpdateCache(int i)
public void UpdateCache(int p)
// 'p' is the profile array index. 'i' is the index in the shader (accounting for the neutral profile).
int i = p + 1;
// Erase previous value (This need to be done here individually as in the SSS editor we edit individual component)
int mask = 1 << i;
texturingModeFlags &= ~mask;

texturingModeFlags |= (int)profiles[i].texturingMode << i;
transmissionFlags |= (int)profiles[i].transmissionMode << i * 2;
texturingModeFlags |= (int)profiles[p].texturingMode << i;
transmissionFlags |= (int)profiles[p].transmissionMode << i * 2;
thicknessRemaps[i] = new Vector4(profiles[i].thicknessRemap.x, profiles[i].thicknessRemap.y - profiles[i].thicknessRemap.x, 0f, 0f);
worldScales[i] = new Vector4(profiles[i].worldScale, 0f, 0f, 0f);
shapeParams[i] = profiles[i].shapeParam;
shapeParams[i].w = profiles[i].maxRadius;
transmissionTints[i] = profiles[i].transmissionTint * 0.25f; // Premultiplied
thicknessRemaps[i] = new Vector4(profiles[p].thicknessRemap.x, profiles[p].thicknessRemap.y - profiles[p].thicknessRemap.x, 0f, 0f);
worldScales[i] = new Vector4(profiles[p].worldScale, 0f, 0f, 0f);
shapeParams[i] = profiles[p].shapeParam;
shapeParams[i].w = profiles[p].maxRadius;
transmissionTints[i] = profiles[p].transmissionTint * 0.25f; // Premultiplied
filterKernels[n * i + j].x = profiles[i].filterKernelNearField[j].x;
filterKernels[n * i + j].y = profiles[i].filterKernelNearField[j].y;
filterKernels[n * i + j].x = profiles[p].filterKernelNearField[j].x;
filterKernels[n * i + j].y = profiles[p].filterKernelNearField[j].y;
filterKernels[n * i + j].z = profiles[i].filterKernelFarField[j].x;
filterKernels[n * i + j].w = profiles[i].filterKernelFarField[j].y;
filterKernels[n * i + j].z = profiles[p].filterKernelFarField[j].x;
filterKernels[n * i + j].w = profiles[p].filterKernelFarField[j].y;
halfRcpWeightedVariances[i] = profiles[i].halfRcpWeightedVariances;
halfRcpWeightedVariances[i] = profiles[p].halfRcpWeightedVariances;
var stdDev1 = ((1f / 3f) * SssConstants.SSS_BASIC_DISTANCE_SCALE) * (Vector4)profiles[i].scatterDistance1;
var stdDev2 = ((1f / 3f) * SssConstants.SSS_BASIC_DISTANCE_SCALE) * (Vector4)profiles[i].scatterDistance2;
var stdDev1 = ((1f / 3f) * SssConstants.SSS_BASIC_DISTANCE_SCALE) * (Vector4)profiles[p].scatterDistance1;
var stdDev2 = ((1f / 3f) * SssConstants.SSS_BASIC_DISTANCE_SCALE) * (Vector4)profiles[p].scatterDistance2;
halfRcpVariancesAndWeights[2 * i + 0] = new Vector4(a * a * 0.5f / (stdDev1.x * stdDev1.x), a * a * 0.5f / (stdDev1.y * stdDev1.y), a * a * 0.5f / (stdDev1.z * stdDev1.z), 4f * (1f - profiles[i].lerpWeight));
halfRcpVariancesAndWeights[2 * i + 1] = new Vector4(a * a * 0.5f / (stdDev2.x * stdDev2.x), a * a * 0.5f / (stdDev2.y * stdDev2.y), a * a * 0.5f / (stdDev2.z * stdDev2.z), 4f * profiles[i].lerpWeight);
halfRcpVariancesAndWeights[2 * i + 0] = new Vector4(a * a * 0.5f / (stdDev1.x * stdDev1.x), a * a * 0.5f / (stdDev1.y * stdDev1.y), a * a * 0.5f / (stdDev1.z * stdDev1.z), 4f * (1f - profiles[p].lerpWeight));
halfRcpVariancesAndWeights[2 * i + 1] = new Vector4(a * a * 0.5f / (stdDev2.x * stdDev2.x), a * a * 0.5f / (stdDev2.y * stdDev2.y), a * a * 0.5f / (stdDev2.z * stdDev2.z), 4f * profiles[p].lerpWeight);
filterKernelsBasic[n * i + j] = profiles[i].filterKernelBasic[j];
filterKernelsBasic[n * i + j] = profiles[p].filterKernelBasic[j];
}
// <<< Old SSS Model
}

2
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs.hlsl


// UnityEngine.Experimental.Rendering.HDPipeline.SssConstants: static fields
//
#define SSS_N_PROFILES (16)
#define SSS_NEUTRAL_PROFILE_ID (15)
#define SSS_NEUTRAL_PROFILE_ID (0)
#define SSS_N_SAMPLES_NEAR_FIELD (55)
#define SSS_N_SAMPLES_FAR_FIELD (21)
#define SSS_LOD_THRESHOLD (4)

125
ScriptableRenderPipeline/HDRenderPipeline/Material/Material.hlsl


return result;
}
//-----------------------------------------------------------------------------
// Alpha test replacement
//-----------------------------------------------------------------------------
// This function must be use instead of clip instruction. It allow to manage in which case the clip is perform
void DoAlphaTest(float alpha, float alphaCutoff)
{
// For Deferred:
// If we have a prepass, we need to remove the clip from the GBuffer pass (otherwise HiZ does not work on PS4) - SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
// For Forward (Lit or Unlit)
// Opaque geometry always has a depth pre-pass so we never want to do the clip here. For transparent we perform the clip as usual.
// Also no alpha test for light transport
#if !(SHADERPASS == SHADERPASS_FORWARD && !defined(_SURFACE_TYPE_TRANSPARENT)) && !(SHADERPASS == SHADERPASS_FORWARD_UNLIT && !defined(_SURFACE_TYPE_TRANSPARENT)) && !defined(SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST) && !(SHADERPASS == SHADERPASS_LIGHT_TRANSPORT)
clip(alpha - alphaCutoff);
#endif
}
//-----------------------------------------------------------------------------
// Reflection / Refraction hierarchy handling
//-----------------------------------------------------------------------------
// This function is use with reflection and refraction hierarchy of LightLoop
// It will add weight to hierarchyWeight but ensure that hierarchyWeight is not more than one
// by updating the weight value. Returned weight value must be apply on current lighting
// Example: Total hierarchyWeight is 0.8 and weight is 0.4. Function return hierarchyWeight of 1.0 and weight of 0.2
// hierarchyWeight and weight must be positive and between 0 and 1
void UpdateLightingHierarchyWeights(inout float hierarchyWeight, inout float weight)
{
float accumulatedWeight = hierarchyWeight + weight;
hierarchyWeight = saturate(accumulatedWeight);
weight -= saturate(accumulatedWeight - hierarchyWeight);
}
//-----------------------------------------------------------------------------
// BuiltinData

#define DECODE_FROM_GBUFFER(NAME, FEATURE_FLAGS, BSDF_DATA, BAKE_DIFFUSE_LIGHTING) DecodeFromGBuffer(MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), FEATURE_FLAGS, BSDF_DATA, BAKE_DIFFUSE_LIGHTING)
#define MATERIAL_FEATURE_FLAGS_FROM_GBUFFER(NAME) MaterialFeatureFlagsFromGBuffer(MERGE_NAME(NAME,0), MERGE_NAME(NAME,1))
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target2
#ifdef SHADOWS_SHADOWMASK
#define OUTPUT_GBUFFER_SHADOWMASK(NAME) ,out float4 NAME : SV_Target2
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target3
#endif
#else
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target2
#endif
#endif
#elif GBUFFERMATERIAL_COUNT == 3

#define DECODE_FROM_GBUFFER(NAME, FEATURE_FLAGS, BSDF_DATA, BAKE_DIFFUSE_LIGHTING) DecodeFromGBuffer(MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2), FEATURE_FLAGS, BSDF_DATA, BAKE_DIFFUSE_LIGHTING)
#define MATERIAL_FEATURE_FLAGS_FROM_GBUFFER(NAME) MaterialFeatureFlagsFromGBuffer(MERGE_NAME(NAME,0), MERGE_NAME(NAME,1), MERGE_NAME(NAME,2))
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target3
#ifdef SHADOWS_SHADOWMASK
#define OUTPUT_GBUFFER_SHADOWMASK(NAME) ,out float4 NAME : SV_Target3
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target4
#endif
#else
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target3
#endif
#endif
#elif GBUFFERMATERIAL_COUNT == 4

#define DECODE_FROM_GBUFFER(NAME, FEATURE_FLAGS, BSDF_DATA, BAKE_DIFFUSE_LIGHTING) DecodeFromGBuffer(MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3), FEATURE_FLAGS, BSDF_DATA, BAKE_DIFFUSE_LIGHTING)
#define MATERIAL_FEATURE_FLAGS_FROM_GBUFFER(NAME) MaterialFeatureFlagsFromGBuffer(MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3))
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target4
#ifdef SHADOWS_SHADOWMASK
#define OUTPUT_GBUFFER_SHADOWMASK(NAME) ,out float4 NAME : SV_Target4
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target5
#endif
#else
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target4
#endif
#endif
#elif GBUFFERMATERIAL_COUNT == 5

#define DECODE_FROM_GBUFFER(NAME, FEATURE_FLAGS, BSDF_DATA, BAKE_DIFFUSE_LIGHTING) DecodeFromGBuffer(MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3), MERGE_NAME(NAME, 4), FEATURE_FLAGS, BSDF_DATA, BAKE_DIFFUSE_LIGHTING)
#define MATERIAL_FEATURE_FLAGS_FROM_GBUFFER(NAME) MaterialFeatureFlagsFromGBuffer(MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3), MERGE_NAME(NAME, 4))
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target5
#ifdef SHADOWS_SHADOWMASK
#define OUTPUT_GBUFFER_SHADOWMASK(NAME) ,out float4 NAME : SV_Target5
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target6
#endif
#else
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target5
#endif
#elif GBUFFERMATERIAL_COUNT == 6
#define OUTPUT_GBUFFER(NAME) \
out GBufferType0 MERGE_NAME(NAME, 0) : SV_Target0, \
out GBufferType1 MERGE_NAME(NAME, 1) : SV_Target1, \
out GBufferType2 MERGE_NAME(NAME, 2) : SV_Target2, \
out GBufferType3 MERGE_NAME(NAME, 3) : SV_Target3, \
out GBufferType4 MERGE_NAME(NAME, 4) : SV_Target4, \
out GBufferType5 MERGE_NAME(NAME, 5) : SV_Target5
#define DECLARE_GBUFFER_TEXTURE(NAME) \
TEXTURE2D(MERGE_NAME(NAME, 0)); \
TEXTURE2D(MERGE_NAME(NAME, 1)); \
TEXTURE2D(MERGE_NAME(NAME, 2)); \
TEXTURE2D(MERGE_NAME(NAME, 3)); \
TEXTURE2D(MERGE_NAME(NAME, 4)); \
TEXTURE2D(MERGE_NAME(NAME, 5));
#define FETCH_GBUFFER(NAME, TEX, unCoord2) \
GBufferType0 MERGE_NAME(NAME, 0) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 0), unCoord2); \
GBufferType1 MERGE_NAME(NAME, 1) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 1), unCoord2); \
GBufferType2 MERGE_NAME(NAME, 2) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 2), unCoord2); \
GBufferType3 MERGE_NAME(NAME, 3) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 3), unCoord2); \
GBufferType4 MERGE_NAME(NAME, 4) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 4), unCoord2); \
GBufferType5 MERGE_NAME(NAME, 5) = LOAD_TEXTURE2D(MERGE_NAME(TEX, 5), unCoord2);
#define ENCODE_INTO_GBUFFER(SURFACE_DATA, BAKE_DIFFUSE_LIGHTING, NAME) EncodeIntoGBuffer(SURFACE_DATA, BAKE_DIFFUSE_LIGHTING, MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3), MERGE_NAME(NAME, 4), MERGE_NAME(NAME, 5))
#define DECODE_FROM_GBUFFER(NAME, FEATURE_FLAGS, BSDF_DATA, BAKE_DIFFUSE_LIGHTING) DecodeFromGBuffer(MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3), MERGE_NAME(NAME, 4), MERGE_NAME(NAME, 5), FEATURE_FLAGS, BSDF_DATA, BAKE_DIFFUSE_LIGHTING)
#define MATERIAL_FEATURE_FLAGS_FROM_GBUFFER(NAME) MaterialFeatureFlagsFromGBuffer(MERGE_NAME(NAME, 0), MERGE_NAME(NAME, 1), MERGE_NAME(NAME, 2), MERGE_NAME(NAME, 3), MERGE_NAME(NAME, 4), MERGE_NAME(NAME, 5))
#ifdef SHADOWS_SHADOWMASK
#define OUTPUT_GBUFFER_SHADOWMASK(NAME) ,out float4 NAME : SV_Target6
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target7
#endif
#else
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER
#define OUTPUT_GBUFFER_VELOCITY(NAME) ,out float4 NAME : SV_Target6
#endif
#endif
#endif
#ifdef SHADOWS_SHADOWMASK
#define ENCODE_SHADOWMASK_INTO_GBUFFER(SHADOWMASK, NAME) EncodeShadowMask(SHADOWMASK, NAME)
#else
#define OUTPUT_GBUFFER_SHADOWMASK(NAME)
#define ENCODE_SHADOWMASK_INTO_GBUFFER(SHADOWMASK, NAME)
#endif
#if SHADEROPTIONS_VELOCITY_IN_GBUFFER

28
ScriptableRenderPipeline/HDRenderPipeline/Material/MaterialUtilities.hlsl


#endif
}
// This function must be use instead of clip instruction. It allow to manage in which case the clip is perform
void DoAlphaTest(float alpha, float alphaCutoff)
float4 SampleShadowMask(float3 positionWS, float2 uvStaticLightmap) // normalWS not use for now
// For Deferred:
// If we have a prepass, we need to remove the clip from the GBuffer pass (otherwise HiZ does not work on PS4) - SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
// For Forward (Lit or Unlit)
// Opaque geometry always has a depth pre-pass so we never want to do the clip here. For transparent we perform the clip as usual.
// Also no alpha test for light transport
#if !(SHADERPASS == SHADERPASS_FORWARD && !defined(_SURFACE_TYPE_TRANSPARENT)) && !(SHADERPASS == SHADERPASS_FORWARD_UNLIT && !defined(_SURFACE_TYPE_TRANSPARENT)) && !defined(SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST) && !(SHADERPASS == SHADERPASS_LIGHT_TRANSPORT)
clip(alpha - alphaCutoff);
#if defined(LIGHTMAP_ON)
float2 uv = uvStaticLightmap * unity_LightmapST.xy + unity_LightmapST.zw;
float4 rawOcclusionMask = SAMPLE_TEXTURE2D(unity_ShadowMask, samplerunity_Lightmap, uv); // Reuse sampler from Lightmap
#else
float4 rawOcclusionMask;
if (unity_ProbeVolumeParams.x == 1.0)
{
// TODO: We use GetAbsolutePositionWS(positionWS) to handle the camera relative case here but this should be part of the unity_ProbeVolumeWorldToObject matrix on C++ side (sadly we can't modify it for HDRenderPipeline...)
rawOcclusionMask = SampleProbeOcclusion(TEXTURE3D_PARAM(unity_ProbeVolumeSH, samplerunity_ProbeVolumeSH), GetAbsolutePositionWS(positionWS), unity_ProbeVolumeWorldToObject,
unity_ProbeVolumeParams.y, unity_ProbeVolumeParams.z, unity_ProbeVolumeMin, unity_ProbeVolumeSizeInv);
}
else
{
// Note: Default value when the feature is not enabled is float(1.0, 1.0, 1.0, 1.0) in C++
rawOcclusionMask = unity_ProbesOcclusion;
}
return rawOcclusionMask;
}
float2 CalculateVelocity(float4 positionCS, float4 previousPositionCS)

28
ScriptableRenderPipeline/HDRenderPipeline/Material/RenderPipelineMaterial.cs


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

public static List<RenderPipelineMaterial> GetRenderPipelineMaterialList()
{
var baseType = typeof(RenderPipelineMaterial);
var assembly = baseType.Assembly;
var types = assembly.GetTypes()
.Where(t => t.IsSubclassOf(baseType))
.Select(Activator.CreateInstance)
.Cast<RenderPipelineMaterial>()
.ToList();
// Note: If there is a need for an optimization in the future of this function, user can
// simply fill the materialList manually by commenting the code abode and returning a
// custom list of materials they use in their game.
//
// return new List<RenderPipelineMaterial>
// {
// new Lit(),
// new Unlit(),
// ...
// };
return types;
}
// GBuffer management
public virtual int GetMaterialGBufferCount() { return 0; }
public virtual void GetMaterialGBufferDescription(out RenderTextureFormat[] RTFormat, out RenderTextureReadWrite[] RTReadWrite)

27
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/BaseUnlitUI.cs


// The fixup routine makes sure that the material is in the correct state if/when changes are made to the mode or color.
MaterialEditor.FixupEmissiveFlag(material);
// Commented out for now because unfortunately we used the hard coded property names used by the GI system for our own parameters
// So we need a way to work around that before we activate this.
SetupMainTexForAlphaTestGI("_EmissiveColorMap", "_EmissiveColor", material);
}
// This is a hack for GI. PVR looks in the shader for a texture named "_MainTex" to extract the opacity of the material for baking. In the same manner, "_Cutoff" and "_Color" are also necessary.
// Since we don't have those parameters in our shaders we need to provide a "fake" useless version of them with the right values for the GI to work.
protected static void SetupMainTexForAlphaTestGI(string colorMapPropertyName, string colorPropertyName, Material material)
{
if (material.HasProperty(colorMapPropertyName))
{
var mainTex = material.GetTexture(colorMapPropertyName);
material.SetTexture("_MainTex", mainTex);
}
if (material.HasProperty(colorPropertyName))
{
var color = material.GetColor(colorPropertyName);
material.SetColor("_Color", color);
}
if (material.HasProperty("_AlphaCutoff")) // Same for all our materials
{
var cutoff = material.GetFloat("_AlphaCutoff");
material.SetFloat("_Cutoff", cutoff);
}
}
static public void SetupBaseUnlitMaterialPass(Material material)

5
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/UnlitUI.cs


}
protected MaterialProperty color = null;
protected const string kColor = "_Color";
protected const string kColor = "_UnlitColor";
protected const string kColorMap = "_ColorMap";
protected const string kColorMap = "_UnlitColorMap";
protected MaterialProperty emissiveColor = null;
protected const string kEmissiveColor = "_EmissiveColor";
protected MaterialProperty emissiveColorMap = null;

m_MaterialEditor.TexturePropertySingleLine(Styles.colorText, colorMap, color);
m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveText, emissiveColorMap, emissiveColor);
m_MaterialEditor.TextureScaleOffsetProperty(emissiveColorMap);
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
var surfaceTypeValue = (SurfaceType)surfaceType.floatValue;

6
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/ShaderPass/UnlitSharePass.hlsl


#define ATTRIBUTES_NEED_TEXCOORD0
#if defined(DEBUG_DISPLAY) || (SHADERPASS == SHADERPASS_LIGHT_TRANSPORT)
// For the meta pass with emissive we require UV1 and/or UV2
#define ATTRIBUTES_NEED_TEXCOORD1
#define ATTRIBUTES_NEED_TEXCOORD2
#endif
#if defined(_ENABLE_FOG_ON_TRANSPARENT)
#define VARYINGS_NEED_POSITION_WS
#endif

16
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.shader


{
Properties
{
_Color("Color", Color) = (1,1,1,1)
_ColorMap("ColorMap", 2D) = "white" {}
// Be careful, do not change the name here to _Color. It will conflict with the "fake" parameters (see end of properties) required for GI.
_UnlitColor("Color", Color) = (1,1,1,1)
_UnlitColorMap("ColorMap", 2D) = "white" {}
_EmissiveColor("EmissiveColor", Color) = (0, 0, 0)
_EmissiveColor("EmissiveColor", Color) = (1, 1, 1)
_EmissiveColorMap("EmissiveColorMap", 2D) = "white" {}
_EmissiveIntensity("EmissiveIntensity", Float) = 0

// In our case we don't use such a mechanism but need to keep the code quiet. We declare the value and always enable it.
// TODO: Fix the code in legacy unity so we can customize the beahvior for GI
_EmissionColor("Color", Color) = (1, 1, 1)
// HACK: GI Baking system relies on some properties existing in the shader ("_MainTex", "_Cutoff" and "_Color") for opacity handling, so we need to store our version of those parameters in the hard-coded name the GI baking system recognizes.
_MainTex("Albedo", 2D) = "white" {}
_Color("Color", Color) = (1,1,1,1)
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
//#pragma enable_d3d11_debug_symbols
//-------------------------------------------------------------------------------------

#define SHADERPASS SHADERPASS_LIGHT_TRANSPORT
#include "../../Material/Material.hlsl"
#include "ShaderPass/UnlitMetaPass.hlsl"
#include "ShaderPass/UnlitSharePass.hlsl"
#include "UnlitData.hlsl"
#include "../../ShaderPass/ShaderPassLightTransport.hlsl"

15
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/UnlitData.hlsl


#include "../MaterialUtilities.hlsl"
//-------------------------------------------------------------------------------------
// Fill SurfaceData/Builtin data function
//-------------------------------------------------------------------------------------

surfaceData.color = SAMPLE_TEXTURE2D(_ColorMap, sampler_ColorMap, input.texCoord0).rgb * _Color.rgb;
float alpha = SAMPLE_TEXTURE2D(_ColorMap, sampler_ColorMap, input.texCoord0).a * _Color.a;
surfaceData.color = SAMPLE_TEXTURE2D(_UnlitColorMap, sampler_UnlitColorMap, input.texCoord0).rgb * _UnlitColor.rgb;
float alpha = SAMPLE_TEXTURE2D(_UnlitColorMap, sampler_UnlitColorMap, input.texCoord0).a * _UnlitColor.a;
#ifdef _ALPHATEST_ON
DoAlphaTest(alpha, _AlphaCutoff);

builtinData.emissiveIntensity = _EmissiveIntensity;
#ifdef _EMISSIVE_COLOR_MAP
builtinData.emissiveColor = SAMPLE_TEXTURE2D(_EmissiveColorMap, sampler_EmissiveColorMap, input.texCoord0).rgb * _EmissiveColor * builtinData.emissiveIntensity;
builtinData.emissiveColor = SAMPLE_TEXTURE2D(_EmissiveColorMap, sampler_EmissiveColorMap, TRANSFORM_TEX(input.texCoord0, _EmissiveColorMap)).rgb * _EmissiveColor * builtinData.emissiveIntensity;
#else
builtinData.emissiveColor = _EmissiveColor * builtinData.emissiveIntensity;
#endif

builtinData.shadowMask0 = 0.0;
builtinData.shadowMask1 = 0.0;
builtinData.shadowMask2 = 0.0;
builtinData.shadowMask3 = 0.0;
float3 distortion = SAMPLE_TEXTURE2D(_DistortionVectorMap, sampler_DistortionVectorMap, input.texCoord0).rgb;
float3 distortion = SAMPLE_TEXTURE2D(_DistortionVectorMap, sampler_DistortionVectorMap, input.texCoord0).rgb * 2.0 - 1.0;
builtinData.distortion = distortion.rg * _DistortionScale;
builtinData.distortionBlur = clamp(distortion.b * _DistortionBlurScale, 0.0, 1.0) * (_DistortionBlurRemapMax - _DistortionBlurRemapMin) + _DistortionBlurRemapMin;
#else

8
ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/UnlitProperties.hlsl


float4 _Color;
TEXTURE2D(_ColorMap);
SAMPLER2D(sampler_ColorMap);
float4 _UnlitColor;
TEXTURE2D(_UnlitColorMap);
SAMPLER2D(sampler_UnlitColorMap);
TEXTURE2D(_DistortionVectorMap);
SAMPLER2D(sampler_DistortionVectorMap);

SAMPLER2D(sampler_EmissiveColorMap);
float4 _EmissiveColorMap_ST;
float _EmissiveIntensity;
float _AlphaCutoff;

2
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawSssProfile.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

4
ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

if (_UseDisneySSS)
{
T = ComputeTransmittance(_ShapeParam.rgb, float3(0.25, 0.25, 0.25), d, 1);
T = ComputeTransmittanceDisney(_ShapeParam.rgb, float3(0.25, 0.25, 0.25), d, 1);
}
else
{

15
ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassForward.hlsl


if (_DebugLightingMode != DEBUGLIGHTINGMODE_NONE)
#endif
{
uint featureFlags = 0xFFFFFFFF;
#ifdef _SURFACE_TYPE_TRANSPARENT
uint featureFlags = LIGHT_FEATURE_MASK_FLAGS_TRANSPARENT;
#else
uint featureFlags = LIGHT_FEATURE_MASK_FLAGS_OPAQUE;
#endif
float3 bakeDiffuseLighting = GetBakedDiffuseLigthing(surfaceData, builtinData, bsdfData, preLightData);
LightLoop(V, posInput, preLightData, bsdfData, bakeDiffuseLighting, featureFlags, diffuseLighting, specularLighting);
BakeLightingData bakeLightingData;
bakeLightingData.bakeDiffuseLighting = GetBakedDiffuseLigthing(surfaceData, builtinData, bsdfData, preLightData);
#ifdef SHADOWS_SHADOWMASK
bakeLightingData.bakeShadowMask = float4(builtinData.shadowMask0, builtinData.shadowMask1, builtinData.shadowMask2, builtinData.shadowMask3);
#endif
LightLoop(V, posInput, preLightData, bsdfData, bakeLightingData, featureFlags, diffuseLighting, specularLighting);
outColor = ApplyBlendMode(diffuseLighting, specularLighting, builtinData.opacity);
outColor = EvaluateAtmosphericScattering(posInput, outColor);
}

2
ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassGBuffer.hlsl


void Frag( PackedVaryingsToPS packedInput,
OUTPUT_GBUFFER(outGBuffer)
OUTPUT_GBUFFER_SHADOWMASK(outShadowMaskBuffer)
OUTPUT_GBUFFER_VELOCITY(outVelocityBuffer)
#ifdef _DEPTHOFFSET_ON
, out float outputDepth : SV_Depth

float3 bakeDiffuseLighting = GetBakedDiffuseLigthing(surfaceData, builtinData, bsdfData, preLightData);
ENCODE_INTO_GBUFFER(surfaceData, bakeDiffuseLighting, outGBuffer);
ENCODE_SHADOWMASK_INTO_GBUFFER(float4(builtinData.shadowMask0, builtinData.shadowMask1, builtinData.shadowMask2, builtinData.shadowMask3), outShadowMaskBuffer);
ENCODE_VELOCITY_INTO_GBUFFER(builtinData.velocity, outVelocityBuffer);
#ifdef _DEPTHOFFSET_ON

24
ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl


// OpenGL right now needs to actually use the incoming vertex position
// so we create a fake dependency on it here that haven't any impact.
output.vmesh.positionCS = float4(uv * 2.0 - 1.0, inputMesh.positionOS.z > 0 ? 1.0e-4 : 0.0, 1.0);
output.vmesh.texCoord0 = inputMesh.uv0;
output.vmesh.texCoord1 = inputMesh.uv1;
#if defined(VARYINGS_NEED_COLOR)
#ifdef VARYINGS_NEED_POSITION_WS
float3 positionWS = GetCameraRelativePositionWS(TransformObjectToWorld(inputMesh.positionOS));
output.vmesh.positionWS = positionWS;
#endif
#ifdef VARYINGS_NEED_TEXCOORD0
output.vmesh.texCoord0 = inputMesh.uv0;
#endif
#ifdef VARYINGS_NEED_TEXCOORD1
output.vmesh.texCoord1 = inputMesh.uv1;
#endif
#ifdef VARYINGS_NEED_TEXCOORD2
output.vmesh.texCoord2 = inputMesh.uv2;
#endif
#ifdef VARYINGS_NEED_TEXCOORD3
output.vmesh.texCoord3 = inputMesh.uv3;
#endif
#ifdef VARYINGS_NEED_COLOR
output.vmesh.color = inputMesh.color;
#endif

// input.unPositionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.unPositionSS.xy, _ScreenSize.zw);
UpdatePositionInput(input.unPositionSS.z, input.unPositionSS.w, input.positionWS, posInput);
// No position and depth in case of light transport
float3 V = float3(0.0, 0.0, 1.0); // No vector view in case of light transport

{
// Apply diffuseColor Boost from LightmapSettings.
// put abs here to silent a warning, no cost, no impact as color is assume to be positive.
res.rgb = Clamp(pow(abs(lightTransportData.diffuseColor), saturate(unity_OneOverOutputBoost)), 0, unity_MaxOutputValue);
res.rgb = clamp(pow(abs(lightTransportData.diffuseColor), saturate(unity_OneOverOutputBoost)), 0, unity_MaxOutputValue);
}
if (unity_MetaFragmentControl.y)

16
ScriptableRenderPipeline/HDRenderPipeline/ShaderVariables.hlsl


float3 unity_ProbeVolumeSizeInv;
float3 unity_ProbeVolumeMin;
// This contain occlusion factor from 0 to 1 for dynamic objects (no SH here)
float4 unity_ProbesOcclusion;
CBUFFER_END
#if defined(USING_STEREO_MATRICES)

TEXTURE2D(unity_DynamicDirectionality);
// We can have shadowMask only if we have lightmap, so no sampler
TEXTURE2D(unity_ShadowMask);
// TODO: Change code here so probe volume use only one transform instead of all this parameters!
TEXTURE3D_FLOAT(unity_ProbeVolumeSH);
SAMPLER3D(samplerunity_ProbeVolumeSH);

float4 _InvProjParam;
float4 _ScreenSize; // (w, h, 1/w, 1/h)
float4 _FrustumPlanes[6]; // (N, -dot(N, P))
// Volumetric lighting. Should be a struct in 'UnityPerFrame'.
// Unfortunately, we cannot modify the layout of 'UnityPerFrame',
// and structures inside constant buffers are not supported by Unity.
float3 _GlobalFog_Scattering;
float _GlobalFog_Extinction;
float _GlobalFog_Asymmetry;
float _GlobalFog_Align16_0;
float _GlobalFog_Align16_1;
float _GlobalFog_Align16_2;
CBUFFER_END
#ifdef USE_LEGACY_UNITY_MATRIX_VARIABLES

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/BlacksmithlSky/Resources/SkyBlacksmith.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/GGXConvolve.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma multi_compile _ USE_MIS

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/HDRISky/Resources/SkyHDRI.shader


#pragma fragment Frag
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#include "../../../../Core/ShaderLibrary/Color.hlsl"
#include "../../../../Core/ShaderLibrary/Common.hlsl"

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/OpaqueAtmosphericScattering.shader


HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma vertex Vert
#pragma fragment Frag

2
ScriptableRenderPipeline/HDRenderPipeline/Sky/ProceduralSky/Resources/ProceduralSky.shader


#pragma fragment Frag
#pragma target 4.5
#pragma only_renderers d3d11 ps4 metal // TEMP: until we go further in dev
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
#pragma multi_compile _ _ENABLE_SUN_DISK

2
TestbedPipelines/Fptl/FPTLRenderPipeline.asset


type: 3}
buildPerVoxelLightListShader: {fileID: 7200000, guid: 4c2d6eb0553e2514bba3ea9a85d8c53c,
type: 3}
enableClustered: 0
enableClustered: 1
disableFptlWhenClustered: 0
enableBigTilePrepass: 1
enableDrawLightBoundsDebug: 0

39
TestbedPipelines/Fptl/FptlLighting.cs


private static ComputeBuffer s_AABBBoundsBuffer;
private static ComputeBuffer s_LightList;
private static ComputeBuffer s_DirLightList;
private static ComputeBuffer s_LightIndices;
private static ComputeBuffer s_BigTileLightList; // used for pre-pass coarse culling on 64x64 tiles
private static int s_GenListPerBigTileKernel;

s_AABBBoundsBuffer.Release();
s_ConvexBoundsBuffer.Release();
s_LightDataBuffer.Release();
s_LightIndices.Release();
ReleaseResolutionDependentBuffers();
s_DirLightList.Release();

if (s_LightDataBuffer != null)
s_LightDataBuffer.Release();
if (s_LightIndices != null)
s_LightIndices.Release();
ReleaseResolutionDependentBuffers();

s_ConvexBoundsBuffer = new ComputeBuffer(MaxNumLights, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SFiniteLightBound)));
s_LightDataBuffer = new ComputeBuffer(MaxNumLights, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SFiniteLightData)));
s_DirLightList = new ComputeBuffer(MaxNumDirLights, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DirectionalLight)));
s_LightIndices = null; // only used in traditional forward, will be created on demand
buildScreenAABBShader.SetBuffer(s_GenAABBKernel, "g_data", s_ConvexBoundsBuffer);
//m_BuildScreenAABBShader.SetBuffer(kGenAABBKernel, "g_vBoundsBuffer", m_aabbBoundsBuffer);

{
sorting = { flags = SortFlags.CommonOpaque },
//@TODO: need to get light probes + LPPV too?
rendererConfiguration = RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe
rendererConfiguration = RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe | RendererConfiguration.ProvideLightIndices | RendererConfiguration.ProvideReflectionProbeIndices
};
var filterSettings = new FilterRenderersSettings(true){renderQueueRange = RenderQueueRange.opaque};
loop.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);

bool haveTiledSolution = opaquesOnly || enableClustered;
cmd.EnableShaderKeyword(haveTiledSolution ? "TILED_FORWARD" : "REGULAR_FORWARD");
cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix);
cmd.SetGlobalBuffer("g_vLightListMeshInst", s_LightIndices);
loop.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);

var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("ForwardSinglePass"))
{
sorting = { flags = SortFlags.CommonOpaque },
rendererConfiguration = RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe
sorting = { flags = opaquesOnly ? SortFlags.CommonOpaque : SortFlags.CommonTransparent },
rendererConfiguration = RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe | RendererConfiguration.ProvideLightIndices | RendererConfiguration.ProvideReflectionProbeIndices
};
var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = opaquesOnly ? RenderQueueRange.opaque : RenderQueueRange.transparent };

var boundData = new SFiniteLightBound[numVolumes];
var worldToView = WorldToCamera(camera);
var lightIndexMap = inputs.GetLightIndexMap();
for (int i = 0; i < lightIndexMap.Length; i++)
{
lightIndexMap[i] = -1;
}
int lightIndexCount = inputs.GetLightIndicesCount();
if (s_LightIndices == null || lightIndexCount > s_LightIndices.count)
{
// The light indices buffer is too small, resize
if (s_LightIndices != null)
s_LightIndices.Release();
s_LightIndices = new ComputeBuffer(lightIndexCount, System.Runtime.InteropServices.Marshal.SizeOf(typeof(int)));
}
uint lightIndex = 0;
foreach (var cl in inputs.visibleLights)
{
var range = cl.range;

{
boundData[idxOut] = bound;
lightData[idxOut] = light;
lightIndexMap[lightIndex] = idxOut;
lightIndex++;
}
int numLightsOut = 0;
for(int v=0; v<numVolTypes; v++) numLightsOut += numEntries[LightDefinitions.DIRECT_LIGHT, v];

idxOut = numEntries2nd[i, j] + offsets[i, j]; ++numEntries2nd[i, j];
boundData[idxOut] = bndData;
lightData[idxOut] = lgtData;
lightIndexMap[lightIndex] = idxOut;
lightIndex++;
inputs.SetLightIndexMap(lightIndexMap);
int numProbesOut = 0;
for(int v=0; v<numVolTypes; v++) numProbesOut += numEntries[LightDefinitions.REFLECTION_LIGHT, v];

s_ConvexBoundsBuffer.SetData(boundData);
s_LightDataBuffer.SetData(lightData);
inputs.FillLightIndices(s_LightIndices);
return numLightsOut + numProbesOut;
}

{
VoxelLightListGeneration(cmd, camera, numLights, projscr, invProjscr);
}
}
void PushGlobalParams(Camera camera, ScriptableRenderContext loop, Matrix4x4 viewToWorld, Matrix4x4 scrProj, Matrix4x4 incScrProj, int numDirLights)

8
TestbedPipelines/Fptl/RegularForwardLightingUtils.hlsl


StructuredBuffer<SFiniteLightData> g_vLightData;
StructuredBuffer<uint> g_vLightListMeshInst; // build on CPU if in use. direct lights first, then reflection probes. (don't support Buffer yet in unity, so using structured)
uniform int g_numLights;
uniform int g_numReflectionProbes;
uniform uint4 unity_LightIndicesOffsetAndCount;
uniform uint4 unity_ReflectionProbeIndicesOffsetAndCount;
start = model==REFLECTION_LIGHT ? g_numLights : 0; // offset by numLights entries
nrLights = model==REFLECTION_LIGHT ? g_numReflectionProbes : g_numLights;
start = model==REFLECTION_LIGHT ? unity_ReflectionProbeIndicesOffsetAndCount.x : unity_LightIndicesOffsetAndCount.x;
nrLights = model==REFLECTION_LIGHT ? unity_ReflectionProbeIndicesOffsetAndCount.y : unity_LightIndicesOffsetAndCount.y;
}
uint FetchIndex(const uint start, const uint l)

5
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes.meta


fileFormatVersion: 2
guid: 642eb9f65f77a9d47b5cfb977aaee96f
guid: da5a3f10e37fea74c8fb43737fbb9100
timeCreated: 1495194790
timeCreated: 1508423723
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

5
package.json


{
"name": "com.unity.render-pipelines",
"version": "0.1.0",
"unity": "2017.3",
"version": "0.1.6",
"unity": "2018.1",
"com.unity.postprocessing": "0.1.2"
}
}

17
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/BlackRGBA64x64.tga.meta


fileFormatVersion: 2
guid: 524019d263762af4caa9ace94c74c38e
timeCreated: 1497039348
licenseType: Pro
timeCreated: 18446744011573954816
externalObjects: {}
sRGBTexture: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0

crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []

17
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/MidGreyRGBA64x64.tga.meta


fileFormatVersion: 2
guid: bf7ad3b25a0b12d4ebe4f64c2054b38b
timeCreated: 1497039348
licenseType: Pro
timeCreated: 18446744011573954816
externalObjects: {}
sRGBTexture: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0

crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []

17
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/WhiteRGBA64x64.tga.meta


fileFormatVersion: 2
guid: ddccffa3f2572ce408af53c7f903f841
timeCreated: 1497039348
licenseType: Pro
timeCreated: 18446744011573954816
externalObjects: {}
sRGBTexture: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0

crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []

17
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/Black-WhiteRGBA64x64.tga.meta


fileFormatVersion: 2
guid: 3bc698316c6d71040a8a5be738601d45
timeCreated: 1497043838
licenseType: Pro
timeCreated: 18446744011573954816
externalObjects: {}
sRGBTexture: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0

crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []

8
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/HDRI/KirbyCoveWhiteBalancedNoSun.exr.meta


fileFormatVersion: 2
guid: 5613e937b42b0294c8bcf543109dfe11
guid: 5fb993a599e7e9b4b825e1a28e6d2c07
timeCreated: 1508426924
licenseType: Pro
TextureImporter:
fileIDToRecycleName:
8900000: generatedCubemap

mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
enableMipMap: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0

14
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Textures/uvGrid.tga.meta


fileFormatVersion: 2
guid: 0361211e0d3ff044f80391eb793ead6b
guid: b23bea53bdbdb5a4aaacf12522910599
timeCreated: 1508430343
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

textureFormatSet: 0
platformSettings:
- buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1

20
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/HDRP_Test_Camera.prefab


- component: {fileID: 4209882255362944}
- component: {fileID: 20109210616973140}
- component: {fileID: 114270329781043846}
- component: {fileID: 114110876577682668}
m_Layer: 0
m_Name: HDRP_Test_Camera
m_TagString: MainCamera

m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1132393308280272}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalPosition: {x: 0, y: 0, z: -10}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}

m_OcclusionCulling: 1
m_StereoConvergence: 10
m_StereoSeparation: 0.022
--- !u!114 &114110876577682668
MonoBehaviour:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 1132393308280272}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 0e34c98127e05d340ba44a1d4a734454, type: 3}
m_Name:
m_EditorClassIdentifier:
m_CommonSettings: {fileID: 0}
m_SkySettings: {fileID: 11400000, guid: 55214718938e62442b0f5673994ee7b7, type: 2}
--- !u!114 &114270329781043846
MonoBehaviour:
m_ObjectHideFlags: 1

cameraToUse: {fileID: 20109210616973140}
hdr: 1
msaaSamples: 1
width: 1280
height: 720
width: 1920
height: 1080

20
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Materials/HDRP_Default_Material.mat


m_PrefabInternal: {fileID: 0}
m_Name: HDRP_Default_Material
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _NORMALMAP_TANGENT_SPACE
m_ShaderKeywords: _BLENDMODE_ALPHA _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _ENABLE_FOG_ON_TRANSPARENT
_MAPPING_PLANAR _NORMALMAP_TANGENT_SPACE _SURFACE_TYPE_TRANSPARENT
m_CustomRenderQueue: -1
stringTagMap: {}
m_CustomRenderQueue: 3000
stringTagMap:
RenderType: Transparent
disabledShaderPasses:
- DistortionVectors
m_SavedProperties:

- _DoubleSidedEnable: 0
- _DoubleSidedNormalMode: 1
- _Drag: 1
- _DstBlend: 0
- _DstBlend: 10
- _EmissiveColorMode: 1
- _EmissiveIntensity: 0
- _EnableBlendModePreserveSpecularLighting: 1

- _Stiffness: 1
- _SubsurfaceProfile: 0
- _SubsurfaceRadius: 1
- _SurfaceType: 0
- _SurfaceType: 1
- _UVBase: 0
- _UVBase: 4
- _ZWrite: 1
- _ZWrite: 0
- _BaseColor: {r: 1, g: 1, b: 1, a: 1}
- _BaseColor: {r: 0.7294118, g: 0.7294118, b: 0.7294118, a: 1}
- _DoubleSidedConstants: {r: 1, g: 1, b: -1, a: 0}
- _EmissionColor: {r: 1, g: 1, b: 1, a: 1}
- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}

- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 0, g: 0, b: 0, a: 0}

10
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials.meta


fileFormatVersion: 2
guid: 423cb1bfe2cc81e43879ddfa7458a9de
folderAsset: yes
timeCreated: 1509010375
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

241
SampleScenes/HDTest/LayeredLitTest/Material/Lit_UVChart_Planar_Detail.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lit_UVChart_Planar_Detail
m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
m_ShaderKeywords: _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _DETAIL_MAP _MAPPING_PLANAR
_NORMALMAP _NORMALMAP_TANGENT_SPACE
m_LightmapFlags: 1
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses:
- DistortionVectors
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _AnisotropyMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BaseColorMap:
m_Texture: {fileID: 2800000, guid: 0e413f4460470044d93a7c42e4275b09, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BentNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BentNormalMapOS:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMap:
m_Texture: {fileID: 2800000, guid: 21bed8c058c65f84e92fd4e28dd6ec51, type: 3}
m_Scale: {x: 2, y: 2}
m_Offset: {x: 0.25, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DistortionVectorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissiveColorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _HeightMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: 0e413f4460470044d93a7c42e4275b09, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MaskMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _NormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _NormalMapOS:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecularColorMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecularOcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SubSurfaceRadiusMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SubsurfaceRadiusMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TangentMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _TangentMapOS:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ThicknessMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _ATDistance: 1
- _AlbedoAffectEmissive: 0
- _AlphaCutoff: 0.5
- _AlphaCutoffEnable: 0
- _Anisotropy: 0
- _BlendMode: 0
- _BumpScale: 1
- _CoatCoverage: 1
- _CoatIOR: 0.5
- _CullMode: 2
- _Cutoff: 0.5
- _DepthOffsetEnable: 0
- _DetailAOScale: 1
- _DetailAlbedoScale: 0.426
- _DetailHeightScale: 1
- _DetailMapMode: 0
- _DetailNormalMapScale: 1
- _DetailNormalScale: 1
- _DetailSmoothnessScale: 1
- _DisplacementLockObjectScale: 1
- _DisplacementLockTilingScale: 1
- _DisplacementMode: 0
- _DistortionBlendMode: 0
- _DistortionBlurBlendMode: 0
- _DistortionBlurDstBlend: 1
- _DistortionBlurRemapMax: 1
- _DistortionBlurRemapMin: 0
- _DistortionBlurScale: 1
- _DistortionBlurSrcBlend: 1
- _DistortionDepthTest: 0
- _DistortionDstBlend: 1
- _DistortionEnable: 0
- _DistortionOnly: 0
- _DistortionScale: 1
- _DistortionSrcBlend: 1
- _DoubleSidedEnable: 0
- _DoubleSidedMirrorEnable: 1
- _DoubleSidedMode: 0
- _DoubleSidedNormalMode: 1
- _Drag: 1
- _DstBlend: 0
- _EmissiveColorMode: 1
- _EmissiveIntensity: 0
- _EnableBlendModePreserveSpecularLighting: 1
- _EnableFogOnTransparent: 1
- _EnablePerPixelDisplacement: 0
- _EnableSpecularOcclusion: 0
- _EnableWind: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _HeightAmplitude: 0.01
- _HeightBias: 0
- _HeightCenter: 0.5
- _HeightMapMode: 0
- _HeightMax: 1
- _HeightMin: -1
- _HeightScale: 1
- _HorizonFade: 1
- _IOR: 1
- _InitialBend: 1
- _InvTilingScale: 5
- _LinkDetailsWithBase: 1
- _MaterialID: 1
- _Metallic: 0
- _Mode: 0
- _NormalMapSpace: 0
- _NormalScale: 1
- _OcclusionStrength: 1
- _PPDLodThreshold: 5
- _PPDMaxSamples: 15
- _PPDMinSamples: 5
- _PPDPrimitiveLength: 1
- _PPDPrimitiveWidth: 1
- _Parallax: 0.02
- _PreRefractionPass: 0
- _RefractionMode: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2
- _Smoothness: 0.5
- _SmoothnessRemapMax: 1
- _SmoothnessRemapMin: 0
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _StencilRef: 2
- _Stiffness: 1
- _SubsurfaceProfile: 0
- _SubsurfaceRadius: 1
- _SurfaceType: 0
- _TexWorldScale: 0.2
- _Thickness: 1
- _ThicknessMultiplier: 1
- _UVBase: 4
- _UVDetail: 0
- _UVSec: 0
- _ZTestMode: 8
- _ZWrite: 1
m_Colors:
- _BaseColor: {r: 1, g: 1, b: 1, a: 1}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _DoubleSidedConstants: {r: 1, g: 1, b: -1, a: 0}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
- _InvPrimScale: {r: 1, g: 1, b: 0, a: 0}
- _SpecularColor: {r: 1, g: 1, b: 1, a: 1}
- _ThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
- _TransmittanceColor: {r: 1, g: 1, b: 1, a: 1}
- _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
- _UVMappingMask: {r: 0, g: 0, b: 0, a: 0}

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

正在加载...
取消
保存