浏览代码

Merge branch 'Unity-2017.3' of https://github.com/Unity-Technologies/ScriptableRenderLoop into prototype/decals

# Conflicts:
#	ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
#	ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl
/Add-support-for-light-specular-color-tint
Paul Melamed 7 年前
当前提交
d31d3ab4
共有 1528 个文件被更改,包括 5822 次插入7974 次删除
  1. 999
      ImageTemplates/LightweightPipeline/Scenes/005_LitBakedEmission.unity.png
  2. 2
      ImageTemplates/LightweightPipeline/Scenes/005_LitBakedEmission.unity.png.meta
  3. 999
      ImageTemplates/LightweightPipeline/Scenes/006_LitShaderLightProbes.unity.png
  4. 2
      ImageTemplates/LightweightPipeline/Scenes/006_LitShaderLightProbes.unity.png.meta
  5. 999
      ImageTemplates/LightweightPipeline/Scenes/010_MultiplePointLights.unity.png
  6. 999
      ImageTemplates/LightweightPipeline/Scenes/018_Lighting_Scene_DirectionalBakedIndirect.unity.png
  7. 2
      ImageTemplates/LightweightPipeline/Scenes/018_Lighting_Scene_DirectionalBakedIndirect.unity.png.meta
  8. 999
      ImageTemplates/LightweightPipeline/Scenes/019_Lighting_Scene_PointLights.unity.png
  9. 2
      ImageTemplates/LightweightPipeline/Scenes/019_Lighting_Scene_PointLights.unity.png.meta
  10. 999
      ImageTemplates/LightweightPipeline/Scenes/026_Shader_PBRscene.unity.png
  11. 2
      ImageTemplates/LightweightPipeline/Scenes/026_Shader_PBRscene.unity.png.meta
  12. 999
      ImageTemplates/LightweightPipeline/Scenes/027_PostProcessing.unity.png
  13. 2
      ImageTemplates/LightweightPipeline/Scenes/027_PostProcessing.unity.png.meta
  14. 32
      README.md
  15. 10
      SampleScenes/HDTest/GraphicTest/Common/CustomTexture/DistortionMap.shader
  16. 56
      SampleScenes/HDTest/GraphicTest/LayeredTessellation/Material/Layer-2-woord-rock.mat
  17. 1
      SampleScenes/HDTest/GraphicTest/LayeredTessellation/Material/Layer-2-woord-rock.mat.meta
  18. 9
      SampleScenes/HDTest/GraphicTest/SSS/Materials/SSSHead.mat
  19. 13
      SampleScenes/HDTest/GraphicTest/Two Sided/Material/GroundLeaf_DoubleSided.mat
  20. 11
      SampleScenes/HDTest/GraphicTest/Two Sided/Material/GroundLeaf_DoubleSidedFlipSSS.mat
  21. 11
      SampleScenes/HDTest/GraphicTest/Unlit/Material/TestUnlit Mask.mat
  22. 9
      SampleScenes/HDTest/GraphicTest/Unlit/Material/TestUnlit Transparent.mat
  23. 7
      SampleScenes/HDTest/GraphicTest/Unlit/Material/TestUnlit.mat
  24. 803
      SampleScenes/HDTest/LayeredLitTest.unity
  25. 38
      ScriptableRenderPipeline/Core/CoreUtils.cs
  26. 3
      ScriptableRenderPipeline/Core/ShaderLibrary/API/PSSL.hlsl
  27. 33
      ScriptableRenderPipeline/Core/ShaderLibrary/Common.hlsl
  28. 51
      ScriptableRenderPipeline/Core/ShaderLibrary/CommonLighting.hlsl
  29. 27
      ScriptableRenderPipeline/Core/ShaderLibrary/CommonMaterial.hlsl
  30. 22
      ScriptableRenderPipeline/Core/ShaderLibrary/EntityLighting.hlsl
  31. 74
      ScriptableRenderPipeline/Core/ShaderLibrary/GeometricTools.hlsl
  32. 8
      ScriptableRenderPipeline/Core/ShaderLibrary/ImageBasedLighting.hlsl
  33. 256
      ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/Resources/ShadowBlurMoments.compute
  34. 2
      ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/ShadowMoments.hlsl
  35. 74
      ScriptableRenderPipeline/Core/ShaderLibrary/Tessellation.hlsl
  36. 7
      ScriptableRenderPipeline/Core/ShaderLibrary/VolumeRendering.hlsl
  37. 32
      ScriptableRenderPipeline/Core/Shadow/Shadow.cs
  38. 10
      ScriptableRenderPipeline/HDRenderPipeline/Camera/HDCamera.cs
  39. 17
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs
  40. 22
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs.hlsl
  41. 32
      ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewMaterialGBuffer.shader
  42. 88
      ScriptableRenderPipeline/HDRenderPipeline/Editor/HDRenderPipelineMenuItems.cs
  43. 251
      ScriptableRenderPipeline/HDRenderPipeline/HDRenderPipeline.cs
  44. 21
      ScriptableRenderPipeline/HDRenderPipeline/HDStringConstants.cs
  45. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDUtils.cs
  46. 23
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Deferred.shader
  47. 3
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.Styles.cs
  48. 6
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.cs
  49. 24
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/HDAdditionalLightData.cs
  50. 18
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs
  51. 37
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/LightDefinition.cs.hlsl
  52. 119
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/Deferred.compute
  53. 4
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/ShadowDispatch.hlsl
  54. 535
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs
  55. 19
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs.hlsl
  56. 18
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.hlsl
  57. 151
      ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePassLoop.hlsl
  58. 21
      ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs
  59. 32
      ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.cs.hlsl
  60. 25
      ScriptableRenderPipeline/HDRenderPipeline/Material/Builtin/BuiltinData.hlsl
  61. 16
      ScriptableRenderPipeline/HDRenderPipeline/Material/Decal/Decal.cs
  62. 3
      ScriptableRenderPipeline/HDRenderPipeline/Material/Decal/DecalData.hlsl
  63. 79
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader
  64. 83
      ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLitTessellation.shader
  65. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/BaseLitUI.cs
  66. 57
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/LitUI.cs
  67. 6
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/SubsurfaceScatteringSettingsEditor.Styles.cs
  68. 22
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.cs
  69. 692
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
  70. 58
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader
  71. 954
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl
  72. 13
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitProperties.hlsl
  73. 19
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitReference.hlsl
  74. 59
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitTessellation.shader
  75. 998
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.DisneyDiffuse.cs
  76. 106
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.compute
  77. 14
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Resources/SubsurfaceScattering.shader
  78. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/ShaderPass/LitSharePass.hlsl
  79. 111
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs
  80. 2
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/SubsurfaceScatteringSettings.cs.hlsl
  81. 54
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataMeshModification.hlsl
  82. 13
      ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataIndividualLayer.hlsl
  83. 125
      ScriptableRenderPipeline/HDRenderPipeline/Material/Material.hlsl
  84. 23
      ScriptableRenderPipeline/HDRenderPipeline/Material/MaterialUtilities.hlsl
  85. 51
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/BaseUnlitUI.cs
  86. 6
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Editor/UnlitUI.cs
  87. 6
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/ShaderPass/UnlitSharePass.hlsl
  88. 18
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/Unlit.shader
  89. 22
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/UnlitData.hlsl
  90. 13
      ScriptableRenderPipeline/HDRenderPipeline/Material/Unlit/UnlitProperties.hlsl
  91. 4
      ScriptableRenderPipeline/HDRenderPipeline/SceneSettings/Resources/DrawTransmittanceGraph.shader
  92. 15
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassForward.hlsl
  93. 2
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassGBuffer.hlsl
  94. 24
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl
  95. 2
      ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/TessellationShare.hlsl
  96. 36
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariables.hlsl
  97. 11
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesFunctions.hlsl
  98. 2
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesMatrixDefsHDCamera.hlsl
  99. 2
      ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesMatrixDefsLegacyUnity.hlsl

999
ImageTemplates/LightweightPipeline/Scenes/005_LitBakedEmission.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/005_LitBakedEmission.unity.png.meta


fileFormatVersion: 2
guid: f8a5ea9c8121c5b45826dc4c99918223
timeCreated: 1504173061
timeCreated: 1509370030
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

999
ImageTemplates/LightweightPipeline/Scenes/006_LitShaderLightProbes.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/006_LitShaderLightProbes.unity.png.meta


fileFormatVersion: 2
guid: f803aab2456d7844fbd67d66f4c1afe8
timeCreated: 1504173061
timeCreated: 1509370329
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

999
ImageTemplates/LightweightPipeline/Scenes/010_MultiplePointLights.unity.png
文件差异内容过多而无法显示
查看文件

999
ImageTemplates/LightweightPipeline/Scenes/018_Lighting_Scene_DirectionalBakedIndirect.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/018_Lighting_Scene_DirectionalBakedIndirect.unity.png.meta


fileFormatVersion: 2
guid: 89ed8247fbdb545f58bf8e0c6cf53d00
timeCreated: 1504695587
timeCreated: 1509372551
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

999
ImageTemplates/LightweightPipeline/Scenes/019_Lighting_Scene_PointLights.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/019_Lighting_Scene_PointLights.unity.png.meta


fileFormatVersion: 2
guid: 17ad6947534f84588abd730750168c53
timeCreated: 1504695587
timeCreated: 1509374529
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

999
ImageTemplates/LightweightPipeline/Scenes/026_Shader_PBRscene.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/026_Shader_PBRscene.unity.png.meta


fileFormatVersion: 2
guid: bf08da8c044d748a6b54f9ad754b2773
timeCreated: 1505223637
timeCreated: 1509377198
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

999
ImageTemplates/LightweightPipeline/Scenes/027_PostProcessing.unity.png
文件差异内容过多而无法显示
查看文件

2
ImageTemplates/LightweightPipeline/Scenes/027_PostProcessing.unity.png.meta


fileFormatVersion: 2
guid: c40bd57fb760b4839a1ef80428356062
timeCreated: 1507026380
timeCreated: 1509377483
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}

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

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);
}
}

56
SampleScenes/HDTest/GraphicTest/LayeredTessellation/Material/Layer-2-woord-rock.mat


m_PrefabInternal: {fileID: 0}
m_Name: Layer-2-woord-rock
m_Shader: {fileID: 4800000, guid: eab0538d9d5746246806a9611c04ac4d, type: 3}
m_ShaderKeywords: _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _HEIGHTMAP0 _HEIGHTMAP1
_NORMALMAP0 _NORMALMAP1 _NORMALMAP_TANGENT_SPACE0 _NORMALMAP_TANGENT_SPACE1 _NORMALMAP_TANGENT_SPACE2
_NORMALMAP_TANGENT_SPACE3 _TESSELLATION_PHONG
m_ShaderKeywords: _BLENDMODE_PRESERVE_SPECULAR_LIGHTING _DISPLACEMENT_LOCK_TILING_SCALE
_HEIGHTMAP0 _HEIGHTMAP1 _NORMALMAP0 _NORMALMAP1 _NORMALMAP_TANGENT_SPACE0 _NORMALMAP_TANGENT_SPACE1
_NORMALMAP_TANGENT_SPACE2 _NORMALMAP_TANGENT_SPACE3 _TESSELLATION_DISPLACEMENT
_TESSELLATION_PHONG _VERTEX_DISPLACEMENT_LOCK_OBJECT_SCALE
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0

m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SubsurfaceRadiusMap0:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SubsurfaceRadiusMap1:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SubsurfaceRadiusMap2:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SubsurfaceRadiusMap3:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ThicknessMap0:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ThicknessMap1:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ThicknessMap2:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ThicknessMap3:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AlbedoAffectEmissive: 0
- _AlphaCutoff: 0.5

- _DetailSmoothnessScale3: 1
- _DisplacementLockObjectScale: 1
- _DisplacementLockTilingScale: 1
- _DisplacementMode: 0
- _DisplacementMode: 3
- _DistortionDepthTest: 0
- _DistortionEnable: 0
- _DistortionOnly: 0

- _LinkDetailsWithBase1: 1
- _LinkDetailsWithBase2: 1
- _LinkDetailsWithBase3: 1
- _MaterialID: 1
- _Metallic: 0
- _Metallic0: 0
- _Metallic1: 0

- _PreRefractionPass: 0
- _ShiverDirectionality: 0.5
- _ShiverDrag: 0.2
- _ShowLayer0: 0
- _ShowLayer0: 1
- _ShowLayer1: 0
- _ShowLayer2: 0
- _ShowLayer3: 0

- _SrcBlend: 1
- _StencilRef: 2
- _Stiffness: 1
- _SubsurfaceProfile0: 0
- _SubsurfaceProfile1: 0
- _SubsurfaceProfile2: 0
- _SubsurfaceProfile3: 0
- _SubsurfaceRadius0: 1
- _SubsurfaceRadius1: 1
- _SubsurfaceRadius2: 1
- _SubsurfaceRadius3: 1
- _SurfaceType: 0
- _TessellationBackFaceCullEpsilon: -0.25
- _TessellationFactor: 4

- _TexWorldScale2: 1
- _TexWorldScale3: 1
- _TexWorldScaleBlendMask: 1
- _Thickness0: 1
- _Thickness1: 1
- _Thickness2: 1
- _Thickness3: 1
- _UVBase0: 0
- _UVBase1: 0
- _UVBase2: 0

1
SampleScenes/HDTest/GraphicTest/LayeredTessellation/Material/Layer-2-woord-rock.mat.meta


timeCreated: 1487270827
licenseType: Pro
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData: '{"GUIDArray":["e6f68673cc8e7c347a989ffe33cb21b4","f6dfdaa6d241dc94bb8816edbe111721","",""]}'
assetBundleName:

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
文件差异内容过多而无法显示
查看文件

38
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); } }
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, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
cmd.SetRenderTarget(buffer, miplevel, cubemapFace);
cmd.SetRenderTarget(buffer, miplevel, cubemapFace, depthSlice);
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier buffer, ClearFlag clearFlag = ClearFlag.None, 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, int depthSlice = 0)
SetRenderTarget(cmd, buffer, clearFlag, Color.black, miplevel, cubemapFace);
SetRenderTarget(cmd, buffer, clearFlag, clearColorAllBlack, miplevel, cubemapFace, depthSlice);
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
SetRenderTarget(cmd, colorBuffer, depthBuffer, ClearFlag.None, Color.black, miplevel, cubemapFace);
SetRenderTarget(cmd, colorBuffer, depthBuffer, ClearFlag.None, clearColorAllBlack, miplevel, cubemapFace, depthSlice);
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown)
public static void SetRenderTarget(CommandBuffer cmd, RenderTargetIdentifier colorBuffer, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
SetRenderTarget(cmd, colorBuffer, depthBuffer, clearFlag, Color.black, miplevel, cubemapFace);
SetRenderTarget(cmd, colorBuffer, depthBuffer, clearFlag, clearColorAllBlack, miplevel, cubemapFace, depthSlice);
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 colorBuffer, RenderTargetIdentifier depthBuffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = 0)
cmd.SetRenderTarget(colorBuffer, depthBuffer, miplevel, cubemapFace);
cmd.SetRenderTarget(colorBuffer, depthBuffer, miplevel, cubemapFace, depthSlice);
if (clearFlag != ClearFlag.None)
cmd.ClearRenderTarget((clearFlag & ClearFlag.Depth) != 0, (clearFlag & ClearFlag.Color) != 0, clearColor);

{
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

33
ScriptableRenderPipeline/Core/ShaderLibrary/Common.hlsl


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)

}
#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 FLT_SMALL 0.0001
#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

return saturate(x * FLT_MAX) * 2.0 - 1.0;
}
// Orthonormalize the basis vectors using the Gram-Schmidt process.
// We assume that the length of the surface normal is sufficiently close to 1.
// return orthonormalize tangent
// Orthonormalizes the tangent frame using the Gram-Schmidt process.
// We assume that both the tangent and the normal are normalized.
// Returns the new tangent (the normal is unaffected).
float3 Orthonormalize(float3 tangent, float3 normal)
{
return normalize(tangent - dot(tangent, normal) * normal);

positionSS.y = 1.0 - positionSS.y;
#endif
return positionSS;
}
float2 ComputeScreenSpacePosition(float3 positionWS, float4x4 viewProjectionMatrix)
{
float4 positionCS = mul(viewProjectionMatrix, float4(positionWS, 1.0));
return ComputeScreenSpacePosition(positionCS);
}
float3 ComputeViewSpacePosition(float2 positionSS, float depthRaw, float4x4 invProjMatrix)

51
ScriptableRenderPipeline/Core/ShaderLibrary/CommonLighting.hlsl


// Helper functions
//-----------------------------------------------------------------------------
// 'NdotV' can become negative for visible pixels due to the perspective projection, normal mapping and decals.
// This can produce visible artifacts under specular lighting, both direct (overly dark/bright pixels) and indirect (incorrect cubemap direction).
// One way of avoiding these artifacts is to limit the value of 'NdotV' to a small positive number,
// and calculate the reflection vector for the cubemap fetch using a normal shifted into view.
float3 GetViewShiftedNormal(float3 N, float3 V, float NdotV, float minNdotV)
// Inputs: normalized normal and view vectors.
// Outputs: front-facing normal, and the new non-negative value of the cosine of the view angle.
// Important: call Orthonormalize() on the tangent and recompute the bitangent afterwards.
float3 GetViewReflectedNormal(float3 N, float3 V, out float NdotV)
if (NdotV < minNdotV)
{
// We do not renormalize the normal to save a few clock cycles.
// The magnitude difference is typically negligible, and the normal is only used to compute
// the reflection vector for the IBL cube map fetch (which does not depend on the magnitude).
N += (-NdotV + minNdotV) * V;
}
// Fragments of front-facing geometry can have back-facing normals due to interpolation,
// normal mapping and decals. This can cause visible artifacts from both direct (negative or
// extremely high values) and indirect (incorrect lookup direction) lighting.
// There are several ways to avoid this problem. To list a few:
//
// 1. Setting { NdotV = max(<N,V>, SMALL_VALUE) }. This effectively removes normal mapping
// from the affected fragments, making the surface appear flat.
//
// 2. Setting { NdotV = abs(<N,V>) }. This effectively reverses the convexity of the surface.
// It also reduces light leaking from non-shadow-casting lights. Note that 'NdotV' can still
// be 0 in this case.
//
// It's important to understand that simply changing the value of the cosine is insufficient.
// For one, it does not solve the incorrect lookup direction problem, since the normal itself
// is not modified. There is a more insidious issue, however. 'NdotV' is a constituent element
// of the mathematical system describing the relationships between different vectors - and
// not just normal and view vectors, but also light vectors, half vectors, tangent vectors, etc.
// Changing only one angle (or its cosine) leaves the system in an inconsistent state, where
// certain relationships can take on different values depending on whether 'NdotV' is used
// in the calculation or not. Therefore, it is important to change the normal (or another
// vector) in order to leave the system in a consistent state.
//
// We choose to follow the conceptual approach (2) by reflecting the normal around the
// (<N,V> = 0) boundary if necessary, as it allows us to preserve some normal mapping details.
NdotV = dot(N, V);
N = (NdotV >= 0) ? N : (N - 2 * NdotV * V);
NdotV = abs(NdotV);
return N;
}

float3 localY = float3(b, y * ya - sz, y);
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

74
ScriptableRenderPipeline/Core/ShaderLibrary/GeometricTools.hlsl


}
//-----------------------------------------------------------------------------
// Distance functions
// Miscellaneous functions
//-----------------------------------------------------------------------------
// Box is AABB

}
float3 ProjectPointOnPlane(float3 position, float3 planePosition, float3 planeNormal)
{
return position - (dot(position - planePosition, planeNormal) * planeNormal);
}
// Plane equation: {(a, b, c) = N, d = -dot(N, P)}.
// Returns the distance from the plane to the point 'p' along the normal.
// Positive -> in front (above), negative -> behind (below).
float DistanceFromPlane(float3 p, float4 plane)
{
return dot(float4(p, 1.0), plane);
}
// Returns 'true' if the triangle is outside of the frustum.
// 'epsilon' is the (negative) distance to (outside of) the frustum below which we cull the triangle.
bool CullTriangleFrustum(float3 p0, float3 p1, float3 p2, float epsilon, float4 frustumPlanes[6], int numPlanes)
{
bool outside = false;
for (int i = 0; i < numPlanes; i++)
{
// If all 3 points are behind any of the planes, we cull.
outside = outside || Max3(DistanceFromPlane(p0, frustumPlanes[i]),
DistanceFromPlane(p1, frustumPlanes[i]),
DistanceFromPlane(p2, frustumPlanes[i])) < epsilon;
}
return outside;
}
// Returns 'true' if the edge of the triangle is outside of the frustum.
// The edges are defined s.t. they are on the opposite side of the point with the given index.
// 'epsilon' is the (negative) distance to (outside of) the frustum below which we cull the triangle.
bool3 CullTriangleEdgesFrustum(float3 p0, float3 p1, float3 p2, float epsilon, float4 frustumPlanes[6], int numPlanes)
{
bool3 edgesOutside = false;
for (int i = 0; i < numPlanes; i++)
{
bool3 pointsOutside = bool3(DistanceFromPlane(p0, frustumPlanes[i]) < epsilon,
DistanceFromPlane(p1, frustumPlanes[i]) < epsilon,
DistanceFromPlane(p2, frustumPlanes[i]) < epsilon);
// If both points of the edge are behind any of the planes, we cull.
edgesOutside.x = edgesOutside.x || (pointsOutside.y && pointsOutside.z);
edgesOutside.y = edgesOutside.y || (pointsOutside.x && pointsOutside.z);
edgesOutside.z = edgesOutside.z || (pointsOutside.x && pointsOutside.y);
}
return edgesOutside;
}
// Returns 'true' if a triangle defined by 3 vertices is back-facing.
// 'epsilon' is the (negative) value of dot(N, V) below which we cull the triangle.
// 'winding' can be used to change the order: pass 1 for (p0 -> p1 -> p2), or -1 for (p0 -> p2 -> p1).
bool CullTriangleBackFace(float3 p0, float3 p1, float3 p2, float epsilon, float3 viewPos, float winding)
{
float3 edge1 = p1 - p0;
float3 edge2 = p2 - p0;
float3 N = cross(edge1, edge2);
float3 V = viewPos - p0;
float NdotV = dot(N, V) * winding;
// Optimize:
// NdotV / (length(N) * length(V)) < Epsilon
// NdotV < Epsilon * length(N) * length(V)
// NdotV < Epsilon * sqrt(dot(N, N)) * sqrt(dot(V, V))
// NdotV < Epsilon * sqrt(dot(N, N) * dot(V, V))
return NdotV < epsilon * sqrt(dot(N, N) * dot(V, V));
}
#endif // UNITY_GEOMETRICTOOLS_INCLUDED

8
ScriptableRenderPipeline/Core/ShaderLibrary/ImageBasedLighting.hlsl


}
}
// Remap from [0, 1.5] to [0, 1] range.
acc.z /= 1.5;
acc /= sampleCount;
return acc / sampleCount;
// Remap from the [0.5, 1.5] to the [0, 1] range.
acc.z -= 0.5;
return acc;
}
uint GetIBLRuntimeFilterSampleCount(uint mipLevel)

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


#define EVSM_4 2
#define MSM 3
#define THREADS 16
#define MAX_BLUR_SIZE 17
#define MAX_BLUR_SIZE (THREADS+1)
#pragma kernel main_VSM_3 KERNEL_MAIN=main_VSM_3 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=3
#pragma kernel main_VSM_5 KERNEL_MAIN=main_VSM_5 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=1 BLUR_SIZE=5

#pragma kernel main_MSM_15 KERNEL_MAIN=main_MSM_15 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=15
#pragma kernel main_MSM_17 KERNEL_MAIN=main_MSM_17 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=1 BLUR_SIZE=17
#pragma kernel main_MSAA_VSM_3 KERNEL_MAIN=main_MSAA_VSM_3 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_VSM_5 KERNEL_MAIN=main_MSAA_VSM_5 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_VSM_7 KERNEL_MAIN=main_MSAA_VSM_7 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_VSM_9 KERNEL_MAIN=main_MSAA_VSM_9 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_VSM_11 KERNEL_MAIN=main_MSAA_VSM_11 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_VSM_13 KERNEL_MAIN=main_MSAA_VSM_13 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_VSM_15 KERNEL_MAIN=main_MSAA_VSM_15 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_VSM_17 KERNEL_MAIN=main_MSAA_VSM_17 SHADOW_MOMENT_ALGORITHM=VSM MAX_MSAA=8 BLUR_SIZE=17
#pragma kernel main_MSAA_EVSM_2_3 KERNEL_MAIN=main_MSAA_EVSM_2_3 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_EVSM_2_5 KERNEL_MAIN=main_MSAA_EVSM_2_5 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_EVSM_2_7 KERNEL_MAIN=main_MSAA_EVSM_2_7 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_EVSM_2_9 KERNEL_MAIN=main_MSAA_EVSM_2_9 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_EVSM_2_11 KERNEL_MAIN=main_MSAA_EVSM_2_11 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_EVSM_2_13 KERNEL_MAIN=main_MSAA_EVSM_2_13 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_EVSM_2_15 KERNEL_MAIN=main_MSAA_EVSM_2_15 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_EVSM_2_17 KERNEL_MAIN=main_MSAA_EVSM_2_17 SHADOW_MOMENT_ALGORITHM=EVSM_2 MAX_MSAA=8 BLUR_SIZE=17
#pragma kernel main_MSAA_EVSM_4_3 KERNEL_MAIN=main_MSAA_EVSM_4_3 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_EVSM_4_5 KERNEL_MAIN=main_MSAA_EVSM_4_5 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_EVSM_4_7 KERNEL_MAIN=main_MSAA_EVSM_4_7 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_EVSM_4_9 KERNEL_MAIN=main_MSAA_EVSM_4_9 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_EVSM_4_11 KERNEL_MAIN=main_MSAA_EVSM_4_11 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_EVSM_4_13 KERNEL_MAIN=main_MSAA_EVSM_4_13 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_EVSM_4_15 KERNEL_MAIN=main_MSAA_EVSM_4_15 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_EVSM_4_17 KERNEL_MAIN=main_MSAA_EVSM_4_17 SHADOW_MOMENT_ALGORITHM=EVSM_4 MAX_MSAA=8 BLUR_SIZE=17
#pragma kernel main_MSAA_MSM_3 KERNEL_MAIN=main_MSAA_MSM_3 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=3
#pragma kernel main_MSAA_MSM_5 KERNEL_MAIN=main_MSAA_MSM_5 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=5
#pragma kernel main_MSAA_MSM_7 KERNEL_MAIN=main_MSAA_MSM_7 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=7
#pragma kernel main_MSAA_MSM_9 KERNEL_MAIN=main_MSAA_MSM_9 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=9
#pragma kernel main_MSAA_MSM_11 KERNEL_MAIN=main_MSAA_MSM_11 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=11
#pragma kernel main_MSAA_MSM_13 KERNEL_MAIN=main_MSAA_MSM_13 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=13
#pragma kernel main_MSAA_MSM_15 KERNEL_MAIN=main_MSAA_MSM_15 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=15
#pragma kernel main_MSAA_MSM_17 KERNEL_MAIN=main_MSAA_MSM_17 SHADOW_MOMENT_ALGORITHM=MSM MAX_MSAA=8 BLUR_SIZE=17
#define BLUR_BORDER (BLUR_SIZE / 2)
#define LDS_SIZE (THREADS + BLUR_BORDER + BLUR_BORDER)
#if MAX_MSAA == 1
Texture2D<float> depthTex;
#if MAX_MSAA > 1
Texture2DMS<float> depthTex;
Texture2DMS<float> depthTex;
Texture2D<float> depthTex;
uniform uint4 srcRect; // .xy = offset, .zw = width/height
uniform uint4 dstRect; // .xy = offset, .z = array slice , .w = Flags: 1 := 16bpp, 2 := 2 channels pp, 4:= reversed z
uniform uint4 srcRect; // .xy = offset, .zw = width/height
uniform uint4 dstRect; // .xy = offset, .z = array slice , .w = Flags: 1 := 16bpp, 2 := 2 channels pp, 4:= reversed z
uniform float4 blurWeightsStorage[3]; // Unity expects float arrays to be tightly packed
static float blurWeights[12] = (float[12])blurWeightsStorage;
uniform float4 blurWeightsStorage[3]; // Unity expects float arrays to be tightly packed
static float blurWeights[12] = (float[12])blurWeightsStorage;
static const int kBits_16 = 1; // 16 bits per channel
static const int kChannels_2 = 2; // 2 channels per pixel

# define SHADOW_MOMENTS 2
float2 DepthToMoments( float depth )
{
return float2( depth, depth * depth );

float2 moments = ShadowMoments_WarpDepth( depth, evsmExponents );
return float4( moments.xy, moments.xy * moments.xy );
}
[branch]
return ShadowMoments_Encode16MSM( depth );
return ShadowMoments_Encode16MSM( depth );
else
{
float dsq = depth * depth;

#endif
#define moment_t MERGE_NAME( float, SHADOW_MOMENTS )
#define BLUR_BORDER (BLUR_SIZE / 2)
#define LDS_STRIDE (THREADS + BLUR_BORDER + BLUR_BORDER)
#define moment_t MERGE_NAME( float, SHADOW_MOMENTS )
groupshared moment_t moments[LDS_SIZE][LDS_SIZE];
groupshared float moments1[THREADS * LDS_STRIDE]; // contains the blurred first moment
groupshared float moments2[THREADS * LDS_STRIDE]; // contains the blurred second moment
groupshared float moments3[THREADS * LDS_STRIDE]; // contains the blurred third moment
groupshared float moments4[THREADS * LDS_STRIDE]; // contains the blurred fourth moment
groupshared float sampleWeights[MAX_MSAA];
groupshared float sumWeights;
[numthreads( THREADS, THREADS, 1 )]
void KERNEL_MAIN(uint3 dispatchId : SV_DispatchThreadID, uint3 groupThreadId : SV_GroupThreadID)
int getLDSIdx( int2 pos, int stride )
uint i, j; // because the compiler scopes like its 1999.
// interleave two consecutive rows to avoid bank conflicts
return (pos.y >> 1) * (stride << 1) + (pos.x << 1) + (pos.y & 1);
}
void writeToShared( moment_t val, int2 pos, int stride )
{
int idx = getLDSIdx( pos, stride );
moments1[idx] = val.x;
moments2[idx] = val.y;
#if SHADOW_MOMENTS == 4
moments3[idx] = val.z;
moments4[idx] = val.w;
#endif
}
moment_t readFromShared( int2 pos, int stride )
{
int idx = getLDSIdx( pos, stride );
moment_t res;
res.x = moments1[idx];
res.y = moments2[idx];
#if SHADOW_MOMENTS == 4
res.z = moments3[idx];
res.w = moments4[idx];
#endif
return res;
}
[numthreads( THREADS, THREADS, 1 )]
void KERNEL_MAIN( uint3 dispatchId : SV_DispatchThreadID, uint3 groupThreadId : SV_GroupThreadID )
{
depthTex.GetDimensions(width, height, sampleCnt);
sampleCnt = Clamp(0, MAX_MSAA, sampleCnt);
depthTex.GetDimensions( width, height, sampleCnt );
sampleCnt = clamp( sampleCnt, 2, MAX_MSAA );
float sumWeights = 0;
float sampleWeights[MAX_MSAA];
for (i = 0; i < sampleCnt; i++)
if( groupThreadId.x < sampleCnt )
float2 spos = depthTex.GetSamplePosition( i );
sampleWeights[i] = sampleCntRcp; // TODO: find a better weight filter
sumWeights += sampleWeights[i];
float2 spos = depthTex.GetSamplePosition( groupThreadId.x );
sampleWeights[groupThreadId.x] = sampleCntRcp;
sumWeights = 1.0 / sumWeights;
if( groupThreadId.x == 0 )
{
float sum = 0.0;
for( uint i = 0; i < sampleCnt; i++ )
sum += sampleWeights[i];
sumWeights = 1.0 / sum;
}
#endif
// load moments into LDS

// the data in 4 blocks.
const bool reverse_z = (dstRect.w & kReversed_z) != 0;
const int2 ldsSize = int2( LDS_SIZE, LDS_SIZE );
const int2 threadsCnt = int2( THREADS, THREADS );
const int4 validSrc = int4( srcRect.xy, srcRect.xy + srcRect.zw - 1 );
int2 srcIdx = ((int2) dispatchId.xy) - blurBorder.xx + srcRect.xy;
int2 ldsIdx = groupThreadId.xy;
const bool reverse_z = (dstRect.w & kReversed_z) != 0;
const int2 validSrc = (int2) (srcRect.xy + srcRect.zw - 1);
// calculate an average moment over all samples for a given pixel and load the result into LDS
uint iw, ih, is;
int2 srcIdx = ((int2) dispatchId.xy) - blurBorder.xx + (int2) srcRect.xy;
int2 ldsIdx = (int2) groupThreadId.xy;
moment_t hblurredMoments[2];
for( ih = 0; ih < 2; ih++ )
for( int ih = 0; ih < 2; ih++ )
[branch]
if (ldsIdx.y >= ldsSize.y)
continue;
for( iw = 0; iw < 2; iw++ )
for( int iw = 0; iw < 2; iw++ )
[branch]
if (ldsIdx.x >= ldsSize.x)
continue;
moment_t avgMoments = 0.0;
#if MAX_MSAA > 1
for( is = 0; is < sampleCnt; is++ )
if( ldsIdx.x < LDS_STRIDE )
float depth = depthTex.Load( int3( Clamp( srcIdx, validSrc.xy, validSrc.zw ), is ) ).x;
depth = reverse_z ? (1.0 - depth) : depth;
moment_t moments = DepthToMoments( depth );
avgMoments += sampleWeights[is] * moments;
}
avgMoments *= sumWeights;
#if MAX_MSAA > 1
moment_t avgMoments = 0.0;
[loop]
for( uint is = 0; is < sampleCnt; is++ )
{
float depth = depthTex.Load( min( srcIdx, validSrc ), is ).x;
depth = reverse_z ? (1.0 - depth) : depth;
# if SHADOW_MOMENT_ALGORITHM == MSM
// 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 );
# endif
avgMoments += sampleWeights[is] * DepthToMoments( depth );
}
avgMoments *= sumWeights;
writeToShared( avgMoments, int2( ldsIdx.x, groupThreadId.y ), LDS_STRIDE );
float depth = depthTex.Load( int3( Clamp( srcIdx, validSrc.xy, validSrc.zw ), 0 ) ).x;
avgMoments = DepthToMoments( reverse_z ? (1.0-depth) : depth );
float depth = depthTex.Load( int3( min( srcIdx, validSrc ), 0 ) ).x;
depth = reverse_z ? (1.0 - depth) : depth;
# if SHADOW_MOMENT_ALGORITHM == MSM
// 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 );
# endif
writeToShared( DepthToMoments( depth ), int2( ldsIdx.x, groupThreadId.y ), LDS_STRIDE );
moments[ldsIdx.y][ldsIdx.x] = avgMoments;
ldsIdx.x += threadsCnt.x;
srcIdx.x += threadsCnt.x;
ldsIdx.x += THREADS;
srcIdx.x += THREADS;
}
ldsIdx.x = groupThreadId.x;
srcIdx.x = (int) dispatchId.x - blurBorder + srcRect.x;
ldsIdx.y += threadsCnt.y;
srcIdx.y += threadsCnt.y;
}
// sync across all threads so LDS contains the moments for each pixel that we need for the blur
GroupMemoryBarrierWithGroupSync();
GroupMemoryBarrierWithGroupSync();
// first pass blurs horizontally
ldsIdx = groupThreadId.xy + int2( blurBorder, 0 );
moment_t hblurredMoment = 0.0, hblurredMoment2 = 0.0;
int blurOffset;
for( blurOffset = -blurBorder; blurOffset <= blurBorder; blurOffset++ )
{
hblurredMoment += moments[ldsIdx.y][ldsIdx.x + blurOffset] * blurWeights[abs( blurOffset )];
}
ldsIdx.y += threadsCnt.y;
[branch]
if( ldsIdx.y < ldsSize.y )
{
for( blurOffset = -blurBorder; blurOffset <= blurBorder; blurOffset++ )
hblurredMoments[ih] = 0;
int2 idx = { groupThreadId.x + blurBorder, groupThreadId.y };
[loop]
for( int blurOffset = -blurBorder; blurOffset <= blurBorder; blurOffset++ )
hblurredMoment2 += moments[ldsIdx.y][ldsIdx.x + blurOffset] * blurWeights[abs(blurOffset)];
hblurredMoments[ih] += readFromShared( int2( idx.x + blurOffset, idx.y ), LDS_STRIDE ) * blurWeights[abs( blurOffset )];
GroupMemoryBarrierWithGroupSync();
ldsIdx.x = groupThreadId.x;
srcIdx.x = (int) dispatchId.x - blurBorder + srcRect.x;
srcIdx.y += THREADS;
// make sure all reads/writes are done
GroupMemoryBarrierWithGroupSync();
// replace LDS values with the horizontally blurred values
moments[groupThreadId.y][ldsIdx.x] = hblurredMoment;
[branch]
if( ldsIdx.y < ldsSize.y )
moments[ldsIdx.y][ldsIdx.x] = hblurredMoment2;
GroupMemoryBarrierWithGroupSync();
// update LDS with horizontally blurred values
writeToShared( hblurredMoments[0], (int2) groupThreadId.xy, THREADS );
if( (groupThreadId.y + THREADS) < LDS_STRIDE )
writeToShared( hblurredMoments[1], int2( groupThreadId.x, groupThreadId.y + THREADS ), THREADS );
// sync threads
GroupMemoryBarrierWithGroupSync();
ldsIdx = groupThreadId.xy + blurBorder.xx;
ldsIdx = (int2) groupThreadId.xy + int2( 0, blurBorder );
for( blurOffset = -blurBorder; blurOffset <= blurBorder; blurOffset++ )
[unroll]
for( int blurOffset = -blurBorder; blurOffset <= blurBorder; blurOffset++ )
vblurredMoment += moments[ldsIdx.y + blurOffset][ldsIdx.x] * blurWeights[abs( blurOffset )];
vblurredMoment += readFromShared( int2( ldsIdx.x, ldsIdx.y + blurOffset ), THREADS ) * blurWeights[abs(blurOffset)];
dispatchId.z = dstRect.z;
dispatchId.z = dstRect.z;
outputTex[dispatchId] = vblurredMoment;
}
}

2
ScriptableRenderPipeline/Core/ShaderLibrary/Shadow/ShadowMoments.hlsl


return mul( moments, mat );
}
// Note: Don't call this with all moments being equal or 0.0, otherwise this code degenerates into lots of +/-inf calculations
// which don't behave quite the same on all hardware.
void ShadowMoments_SolveMSM( float4 moments, float depth, float momentBias, out float3 z, out float4 b )
{
// Bias input data to avoid artifacts

74
ScriptableRenderPipeline/Core/ShaderLibrary/Tessellation.hlsl


#define TESSELLATION_INTERPOLATE_BARY(name, bary) ouput.name = input0.name * bary.x + input1.name * bary.y + input2.name * bary.z
// TODO: Move in geomtry.hlsl
float3 ProjectPointOnPlane(float3 position, float3 planePosition, float3 planeNormal)
{
return position - (dot(position - planePosition, planeNormal) * planeNormal);
}
// p0, p1, p2 triangle world position
// p0, p1, p2 triangle world vertex normal
float3 PhongTessellation(float3 positionWS, float3 p0, float3 p1, float3 p2, float3 n0, float3 n1, float3 n2, float3 baryCoords, float shape)

// Reference: http://twvideo01.ubm-us.net/o1/vault/gdc10/slides/Bilodeau_Bill_Direct3D11TutorialTessellation.pdf
// Return true if the triangle must be culled
// backFaceCullEpsilon is the threshold of the dot product between view and normal ( < 0 mean we cull)
bool BackFaceCullTriangle(float3 p0, float3 p1, float3 p2, float backFaceCullEpsilon, float3 cameraPosWS)
{
float3 edge0 = p1 - p0;
float3 edge2 = p2 - p0;
float3 N = normalize(cross(edge0, edge2));
float3 midpoint = (p0 + p1 + p2) / 3.0;
float3 V = normalize(cameraPosWS - midpoint);
return (dot(V, N) < backFaceCullEpsilon) ? true : false;
}
float2 GetScreenSpacePosition(float3 positionWS, float4x4 viewProjectionMatrix, float4 screenSize)
{
float4 positionCS = mul(viewProjectionMatrix, float4(positionWS, 1.0));
float2 positionSS = positionCS.xy / positionCS.w;
// TODO: Check if we need to invert y
return (positionSS * 0.5 + 0.5) * float2(screenSize.x, -screenSize.y);
}
float2 edgeScreenPosition0 = GetScreenSpacePosition(p0, viewProjectionMatrix, screenSize);
float2 edgeScreenPosition1 = GetScreenSpacePosition(p1, viewProjectionMatrix, screenSize);
float2 edgeScreenPosition2 = GetScreenSpacePosition(p2, viewProjectionMatrix, screenSize);
float2 edgeScreenPosition0 = ComputeScreenSpacePosition(p0, viewProjectionMatrix) * screenSize;
float2 edgeScreenPosition1 = ComputeScreenSpacePosition(p1, viewProjectionMatrix) * screenSize;
float2 edgeScreenPosition2 = ComputeScreenSpacePosition(p2, viewProjectionMatrix) * screenSize;
float EdgeScale = 1.0 / triangleSize; // Edge size in reality, but name is simpler
float3 tessFactor;

float3 edgePosition1 = 0.5 * (p0 + p2);
float3 edgePosition2 = 0.5 * (p0 + p1);
// TODO: Move to camera relative and change distance to length
// In case camera-relative rendering is enabled, 'cameraPosWS' is statically known to be 0,
// so the compiler will be able to optimize distance() to length().
float dist0 = distance(edgePosition0, cameraPosWS);
float dist1 = distance(edgePosition1, cameraPosWS);
float dist2 = distance(edgePosition2, cameraPosWS);

return tessFactor;
}
float4 CalcTriEdgeTessFactors(float3 triVertexFactors)
float4 CalcTriTessFactorsFromEdgeTessFactors(float3 triVertexFactors)
{
float4 tess;
tess.x = triVertexFactors.x;

return tess;
}
// TODO: Move in geomtry.hlsl
float DistanceFromPlane(float3 pos, float4 plane)
{
float d = dot(float4(pos, 1.0), plane);
return d;
}
// Returns true if triangle with given 3 world positions is outside of camera's view frustum.
// cullEps is distance outside of frustum that is still considered to be inside (i.e. max displacement)
bool WorldViewFrustumCull(float3 p0, float3 p1, float3 p2, float cullEps, float4 cameraWorldClipPlanes[4])
{
float4 planeTest;
// left
planeTest.x = ((DistanceFromPlane(p0, cameraWorldClipPlanes[0]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p1, cameraWorldClipPlanes[0]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p2, cameraWorldClipPlanes[0]) > -cullEps) ? 1.0 : 0.0);
// right
planeTest.y = ((DistanceFromPlane(p0, cameraWorldClipPlanes[1]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p1, cameraWorldClipPlanes[1]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p2, cameraWorldClipPlanes[1]) > -cullEps) ? 1.0 : 0.0);
// top
planeTest.z = ((DistanceFromPlane(p0, cameraWorldClipPlanes[2]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p1, cameraWorldClipPlanes[2]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p2, cameraWorldClipPlanes[2]) > -cullEps) ? 1.0 : 0.0);
// bottom
planeTest.w = ((DistanceFromPlane(p0, cameraWorldClipPlanes[3]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p1, cameraWorldClipPlanes[3]) > -cullEps) ? 1.0 : 0.0) +
((DistanceFromPlane(p2, cameraWorldClipPlanes[3]) > -cullEps) ? 1.0 : 0.0);
// has to pass all 4 plane tests to be visible
return !all(planeTest);
}

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

32
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();

protected const int k_BlurKernelDefSize = (7 - k_BlurKernelMinSize) / 2;
protected const int k_BlurKernelMaxSize = 17;
protected const int k_BlurKernelCount = k_BlurKernelMaxSize / 2;
protected const int k_MaxSampleCount = 8;
protected ComputeShader m_MomentBlurCS;
protected int[] m_KernelVSM = new int[k_BlurKernelCount];
protected int[] m_KernelEVSM_2 = new int[k_BlurKernelCount];

return use_2_Channels ? RenderTextureFormat.RGFloat : RenderTextureFormat.ARGBFloat;
}
}
public ShadowVariance( ref AtlasInit init ) : base( ref init )
public ShadowVariance( ref AtlasInit init, int sampleCount ) : base( ref init )
m_SampleCount = 1; // TODO: Unity can't bind msaa rts as textures, yet, so this has to remain 1 for now
m_SampleCount = sampleCount <= 0 ? 1 : (sampleCount > k_MaxSampleCount ? k_MaxSampleCount : sampleCount);
m_MomentBlurCS = Resources.Load<ComputeShader>( "ShadowBlurMoments" );
if( m_MomentBlurCS )

m_KernelVSM[i] = m_MomentBlurCS.FindKernel( "main_VSM_" + blurSize );
m_KernelEVSM_2[i] = m_MomentBlurCS.FindKernel( "main_EVSM_2_" + blurSize );
m_KernelEVSM_4[i] = m_MomentBlurCS.FindKernel( "main_EVSM_4_" + blurSize );
m_KernelMSM[i] = m_MomentBlurCS.FindKernel( "main_MSM_" + blurSize );
m_KernelVSM[i] = m_MomentBlurCS.FindKernel( "main" + (m_SampleCount > 1 ? "_MSAA_" : "_") + "VSM_" + blurSize );
m_KernelEVSM_2[i] = m_MomentBlurCS.FindKernel( "main" + (m_SampleCount > 1 ? "_MSAA_" : "_") + "EVSM_2_" + blurSize );
m_KernelEVSM_4[i] = m_MomentBlurCS.FindKernel( "main" + (m_SampleCount > 1 ? "_MSAA_" : "_") + "EVSM_4_" + blurSize );
m_KernelMSM[i] = m_MomentBlurCS.FindKernel( "main" + (m_SampleCount > 1 ? "_MSAA_" : "_") + "MSM_" + blurSize );
m_BlurWeights[i] = new float[2+i];
FillBlurWeights( i );

m_BlurWeights[i][j] *= weightSum;
}
}
public ShadowVariance( ref AtlasInit init ) : this( ref init, 1 ) {}
override protected void CreateShadowmap( RenderTexture shadowmap )
{

override protected void PreUpdate( FrameId frameId, CommandBuffer cb, uint rendertargetSlice )
{
cb.SetRenderTarget( m_ShadowmapId, 0, (CubemapFace) 0, (int) rendertargetSlice );
cb.GetTemporaryRT( m_TempDepthId, (int) m_Width, (int) m_Height, (int) m_ShadowmapBits, FilterMode.Bilinear, RenderTextureFormat.Shadowmap, RenderTextureReadWrite.Default, m_SampleCount );
RenderTextureDescriptor desc = new RenderTextureDescriptor( (int) m_Width, (int) m_Height, RenderTextureFormat.Shadowmap, (int) m_ShadowmapBits );
desc.autoGenerateMips = false;
desc.enableRandomWrite = false;
desc.msaaSamples = m_SampleCount;
desc.shadowSamplingMode = ShadowSamplingMode.RawDepth;
desc.useMipMap = false;
desc.bindMS = true;
cb.GetTemporaryRT( m_TempDepthId, desc );
cb.SetRenderTarget( new RenderTargetIdentifier( m_TempDepthId ) );
cb.ClearRenderTarget( true, true, m_ClearColor );
}

10
ScriptableRenderPipeline/HDRenderPipeline/Camera/HDCamera.cs


var gpuNonJitteredProj = GL.GetGPUProjectionMatrix(nonJitteredCameraProj, true);
var pos = camera.transform.position;
var relPos = pos; // World-origin-relative
relPos = Vector3.zero; // Camera-relative
}
var gpuVP = gpuNonJitteredProj * gpuView;

cameraPos = pos;
screenSize = new Vector4(camera.pixelWidth, camera.pixelHeight, 1.0f / camera.pixelWidth, 1.0f / camera.pixelHeight);
// Warning: near and far planes appear to be broken.
for (int i = 0; i < 6; i++)
for (int i = 0; i < 4; i++)
// Left, right, top, bottom.
// Near, far.
frustumPlaneEquations[4] = new Vector4( camera.transform.forward.x, camera.transform.forward.y, camera.transform.forward.z, -Vector3.Dot(camera.transform.forward, relPos) - camera.nearClipPlane);
frustumPlaneEquations[5] = new Vector4(-camera.transform.forward.x, -camera.transform.forward.y, -camera.transform.forward.z, Vector3.Dot(camera.transform.forward, relPos) + camera.farClipPlane);
m_LastFrameActive = Time.frameCount;
}

17
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugDisplay.cs


None,
DiffuseLighting,
SpecularLighting,
VisualizeCascade
VisualizeCascade,
IndirectDiffuseOcclusionFromSsao,
IndirectDiffuseGtaoFromSsao,
IndirectSpecularOcclusionFromSsao,
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,
BakeShadowMask0,
BakeShadowMask1,
BakeShadowMask2,
BakeShadowMask3,
Last,
}
// Number must be contiguous

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

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


#define DEBUGLIGHTINGMODE_DIFFUSE_LIGHTING (1)
#define DEBUGLIGHTINGMODE_SPECULAR_LIGHTING (2)
#define DEBUGLIGHTINGMODE_VISUALIZE_CASCADE (3)
#define DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_OCCLUSION_FROM_SSAO (4)
#define DEBUGLIGHTINGMODE_INDIRECT_DIFFUSE_GTAO_FROM_SSAO (5)
#define DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_OCCLUSION_FROM_SSAO (6)
#define DEBUGLIGHTINGMODE_INDIRECT_SPECULAR_GTAO_FROM_SSAO (7)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Attributes.DebugViewVarying: static fields

#define DEBUGVIEWVARYING_VERTEX_NORMAL_WS (7)
#define DEBUGVIEWVARYING_VERTEX_COLOR (8)
#define DEBUGVIEWVARYING_VERTEX_COLOR_ALPHA (9)
#define DEBUGVIEWVARYING_LAST (10)
//
// UnityEngine.Experimental.Rendering.HDPipeline.Attributes.DebugViewGbuffer: static fields

#define DEBUGVIEWGBUFFER_BAKE_DIFFUSE_LIGHTING_WITH_ALBEDO_PLUS_EMISSIVE (11)
#define DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK0 (12)
#define DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK1 (13)
#define DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK2 (14)
#define DEBUGVIEWGBUFFER_BAKE_SHADOW_MASK3 (15)
#define DEBUGVIEWGBUFFER_LAST (16)
#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 (16)
#define DEBUGVIEWPROPERTIES_PIXEL_DISPLACEMENT (17)
#define DEBUGVIEWPROPERTIES_VERTEX_DISPLACEMENT (18)
#define DEBUGVIEWPROPERTIES_TESSELLATION_DISPLACEMENT (19)
#define DEBUGVIEWPROPERTIES_DEPTH_OFFSET (20)
#define DEBUGVIEWPROPERTIES_LIGHTMAP (21)
//
// UnityEngine.Experimental.Rendering.HDPipeline.FullScreenDebugMode: static fields

32
ScriptableRenderPipeline/HDRenderPipeline/Debug/DebugViewMaterialGBuffer.shader


#pragma vertex Vert
#pragma fragment Frag
#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);

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)]

251
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);
public void InitGBuffers(int width, int height, CommandBuffer cmd)
{
for (int index = 0; index < gbufferCount; index++)
for (int gbufferIndex = 0; gbufferIndex < gbufferCount; ++gbufferIndex)
cmd.GetTemporaryRT(m_IDs[index], width, height, 0, FilterMode.Point, m_Formats[index], m_sRGBWrites[index]);
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);
}
if (ShaderConfig.s_VelocityInGbuffer == 1)
{
// 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];

}
}
public class DBufferManager
{
public const int k_MaxDbuffer = 4;
public int dbufferCount { get; set; }
RenderTargetIdentifier[] m_ColorMRTs;
RenderTargetIdentifier[] m_RTIDs = new RenderTargetIdentifier[k_MaxDbuffer];
public void InitDBuffers(int width, int height, CommandBuffer cmd)
{
dbufferCount = Decal.GetMaterialDBufferCount();
RenderTextureFormat[] rtFormat;
RenderTextureReadWrite[] rtReadWrite;
Decal.GetMaterialDBufferDescription(out rtFormat, out rtReadWrite);
for (int dbufferIndex = 0; dbufferIndex < dbufferCount; ++dbufferIndex)
{
cmd.GetTemporaryRT(HDShaderIDs._DBufferTexture[dbufferIndex], width, height, 0, FilterMode.Point, rtFormat[dbufferIndex], rtReadWrite[dbufferIndex]);
m_RTIDs[dbufferIndex] = new RenderTargetIdentifier(HDShaderIDs._DBufferTexture[dbufferIndex]);
}
}
public RenderTargetIdentifier[] GetDBuffers()
{
if (m_ColorMRTs == null || m_ColorMRTs.Length != dbufferCount)
m_ColorMRTs = new RenderTargetIdentifier[dbufferCount];
for (int index = 0; index < dbufferCount; index++)
{
m_ColorMRTs[index] = m_RTIDs[index];
}
return m_ColorMRTs;
}
}
public partial class HDRenderPipeline : RenderPipeline
{

readonly List<RenderPipelineMaterial> m_MaterialList = new List<RenderPipelineMaterial>();
readonly GBufferManager m_GbufferManager = new GBufferManager();
readonly GBufferManager m_DbufferManager = new GBufferManager();
readonly DBufferManager m_DbufferManager = new DBufferManager();
// 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]);
}
m_DbufferManager.gbufferCount = 2;
m_DbufferManager.SetBufferDescription(0, "_DBufferTexture0", RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
m_DbufferManager.SetBufferDescription(1, "_DBufferTexture1", RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default);
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);

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);
RenderDBuffer(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, "Decals"))
{
CoreUtils.SetRenderTarget(cmd, m_DbufferManager.GetGBuffers(), m_CameraDepthStencilBufferRT);
CoreUtils.SetRenderTarget(cmd, m_DbufferManager.GetDBuffers(), m_CameraDepthStencilBufferRT);
cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, GetDepthTexture());
DecalSystem.instance.Render(renderContext, camera, cmd);
}

{
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);
if (NeedTemporarySubsurfaceBuffer())
{
cmd.SetComputeTextureParam(m_SubsurfaceScatteringCS, m_SubsurfaceScatteringKernel, HDShaderIDs._CameraFilteringBuffer, m_CameraFilteringBufferRT);
// 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);
// 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
cmd.SetGlobalTexture(HDShaderIDs._IrradianceSource, m_CameraFilteringBufferRT); // Cannot set a RT on a material
// 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);
// Combine diffuse and specular lighting into 'm_CameraColorBufferRT'.
CoreUtils.DrawFullScreen(cmd, m_CombineLightingPass, m_CameraColorBufferRT, m_CameraDepthStencilBufferRT);
// 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);
m_DbufferManager.InitGBuffers(w, h, cmd);
m_DbufferManager.InitDBuffers(w, h, 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

21
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[] _DBufferTexture =
{
Shader.PropertyToID("_DBufferTexture0"),
Shader.PropertyToID("_DBufferTexture1"),
Shader.PropertyToID("_DBufferTexture2"),
Shader.PropertyToID("_DBufferTexture3")
};
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()
{

23
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Deferred.shader


// 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

3
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.Styles.cs


public readonly GUIContent shapeLengthLine = new GUIContent("Length", "Length of the line light");
public readonly GUIContent shapeLengthRect = new GUIContent("Size X", "SizeX of the rectangle light");
public readonly GUIContent shapeWidthRect = new GUIContent("Size Y", "SizeY of the rectangle light");
public readonly GUIContent shapeLengthPyramid = new GUIContent("Size X", "");
public readonly GUIContent shapeWidthPyramid = new GUIContent("Size Y", "");
public readonly GUIContent aspectRatioPyramid = new GUIContent("Aspect ratio", "");
public readonly GUIContent shapeLengthBox = new GUIContent("Size X", "");
public readonly GUIContent shapeWidthBox = new GUIContent("Size Y", "");
public readonly GUIContent applyRangeAttenuation = new GUIContent("Apply Range Attenuation", "Allows disabling range attenuation. This is useful indoor (like a room) to avoid having to setup a large range for a light to get correct inverse square attenuation that may leak out of the indoor");

6
ScriptableRenderPipeline/HDRenderPipeline/Lighting/Editor/HDLightEditor.cs


public SerializedProperty spotLightShape;
public SerializedProperty shapeLength;
public SerializedProperty shapeWidth;
public SerializedProperty aspectRatio;
public SerializedProperty shapeRadius;
public SerializedProperty maxSmoothness;
public SerializedProperty applyRangeAttenuation;

spotLightShape = o.Find(x => x.spotLightShape),
shapeLength = o.Find(x => x.shapeLength),
shapeWidth = o.Find(x => x.shapeWidth),
aspectRatio = o.Find(x => x.aspectRatio),
shapeRadius = o.Find(x => x.shapeRadius),
maxSmoothness = o.Find(x => x.maxSmoothness),
applyRangeAttenuation = o.Find(x => x.applyRangeAttenuation),

// TODO : replace with angle and ratio
else if (spotLightShape == SpotLightShape.Pyramid)
{
EditorGUILayout.Slider(m_AdditionalLightData.shapeLength, 0.01f, 10f, s_Styles.shapeLengthPyramid);
EditorGUILayout.Slider(m_AdditionalLightData.shapeWidth, 0.01f, 10f, s_Styles.shapeWidthPyramid);
EditorGUILayout.Slider(m_BaseData.spotAngle, 0f, 179.9f, s_Styles.spotAngle);
EditorGUILayout.Slider(m_AdditionalLightData.aspectRatio, 0.05f, 20.0f, s_Styles.aspectRatioPyramid);
}
else if (spotLightShape == SpotLightShape.Box)
{

24
ScriptableRenderPipeline/HDRenderPipeline/Lighting/HDAdditionalLightData.cs


#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Experimental.Rendering.HDPipeline;
#endif
using UnityEngine.Serialization;

// Only for Spotlight, should be hide for other light
public SpotLightShape spotLightShape = SpotLightShape.Cone;
// Only for Rectangle/Line/projector lights
// Only for Rectangle/Line/box projector lights
// Only for Rectangle/projector lights
// Only for Rectangle/box projector lights
// Only for pyramid projector
public float aspectRatio = 1.0f;
// Only for Sphere/Disc
public float shapeRadius = 0.0f;

switch (light.type)
{
case LightType.Directional:
EditorLightUtilities.DrawDirectionalLightGizmo(light);
HDLightEditorUtilities.DrawDirectionalLightGizmo(light);
EditorLightUtilities.DrawPointlightGizmo(light, selected);
HDLightEditorUtilities.DrawPointlightGizmo(light, selected);
EditorLightUtilities.DrawSpotlightGizmo(light, selected);
HDLightEditorUtilities.DrawSpotlightGizmo(light, selected);
EditorLightUtilities.DrawFrustumlightGizmo(light);
else if (spotLightShape == SpotLightShape.Box) // TODO
EditorLightUtilities.DrawFrustumlightGizmo(light);
HDLightEditorUtilities.DrawFrustumlightGizmo(light);
else if (spotLightShape == SpotLightShape.Box)
HDLightEditorUtilities.DrawFrustumlightGizmo(light);
break;
}
}

{
case LightTypeExtent.Rectangle:
EditorLightUtilities.DrawArealightGizmo(light);
HDLightEditorUtilities.DrawArealightGizmo(light);
EditorLightUtilities.DrawArealightGizmo(light);
HDLightEditorUtilities.DrawArealightGizmo(light);
break;
}
}

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
{

4
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/ShadowDispatch.hlsl


//#define SHADOW_DISPATCH_USE_SEPARATE_PUNC_ALGOS // enables separate resources and algorithms for spot and point lights
// directional
#define SHADOW_DISPATCH_DIR_TEX 3
#define SHADOW_DISPATCH_DIR_SMP 0
#define SHADOW_DISPATCH_DIR_TEX 3
#define SHADOW_DISPATCH_DIR_SMP 0
#define SHADOW_DISPATCH_DIR_ALG GPUSHADOWALGORITHM_PCF_TENT_5X5 // all cascades
#define SHADOW_DISPATCH_DIR_ALG_0 GPUSHADOWALGORITHM_PCF_TENT_7X7 // 1st cascade
#define SHADOW_DISPATCH_DIR_ALG_1 GPUSHADOWALGORITHM_PCF_TENT_5X5 // 2nd cascade

535
ScriptableRenderPipeline/HDRenderPipeline/Lighting/TilePass/TilePass.cs


bool useGlobalOverrides = true;
m_ShadowMgr.SetGlobalShadowOverride( GPUShadowType.Point , ShadowAlgorithm.PCF, ShadowVariant.V4, ShadowPrecision.High, useGlobalOverrides );
m_ShadowMgr.SetGlobalShadowOverride( GPUShadowType.Spot , ShadowAlgorithm.PCF, ShadowVariant.V4, ShadowPrecision.High, useGlobalOverrides );
m_ShadowMgr.SetGlobalShadowOverride( GPUShadowType.Directional , ShadowAlgorithm.PCF, ShadowVariant.V4, ShadowPrecision.High, useGlobalOverrides );
m_ShadowMgr.SetGlobalShadowOverride( GPUShadowType.Directional , ShadowAlgorithm.PCF, ShadowVariant.V3, ShadowPrecision.High, useGlobalOverrides );
m_ShadowMgr.SetShadowLightTypeDelegate(HDShadowLightType);

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)

lightData.size = new Vector2(additionalLightData.shapeLength, additionalLightData.shapeWidth);
if (lightData.lightType == GPULightType.ProjectorBox || lightData.lightType == GPULightType.ProjectorPyramid)
if (lightData.lightType == GPULightType.ProjectorBox)
{
// Rescale for cookies and windowing.
lightData.right *= 2.0f / additionalLightData.shapeLength;
lightData.up *= 2.0f / additionalLightData.shapeWidth;
}
else if (lightData.lightType == GPULightType.ProjectorPyramid)
// Get width and height for the current frustum
var spotAngle = light.spotAngle;
float frustumHeight;
float frustumWidth;
if (additionalLightData.aspectRatio >= 1.0f)
{
frustumHeight = 2.0f * Mathf.Tan(spotAngle * 0.5f * Mathf.Deg2Rad);
frustumWidth = frustumHeight * additionalLightData.aspectRatio;
}
else
{
frustumWidth = 2.0f * Mathf.Tan(spotAngle * 0.5f * Mathf.Deg2Rad);
frustumHeight = frustumWidth / additionalLightData.aspectRatio;
}
lightData.size = new Vector2(frustumWidth, frustumHeight);
lightData.right *= 2 / additionalLightData.shapeLength;
lightData.up *= 2 / additionalLightData.shapeWidth;
lightData.right *= 2.0f / frustumWidth;
lightData.up *= 2.0f / frustumHeight;
}
if (lightData.lightType == GPULightType.Spot)

// 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);
return true;

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;
// Note: Light with null intensity/Color are culled by the C++, no need to test it here
if (cullResults.visibleLights.Count != 0 || cullResults.visibleReflectionProbes.Count != 0)
{
// 0. deal with shadows

// 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++)
if (enableFeatureVariants)
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];
}
// 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;

16
ScriptableRenderPipeline/HDRenderPipeline/Material/Decal/Decal.cs


// Note: This count doesn't include the velocity buffer. On shader and csharp side the velocity buffer will be added by the framework
Count = 2
};
//-----------------------------------------------------------------------------
// DBuffer management
//-----------------------------------------------------------------------------
static public int GetMaterialDBufferCount() { return (int)DBufferMaterial.Count; }
static RenderTextureFormat[] m_RTFormat = { RenderTextureFormat.ARGB32, RenderTextureFormat.ARGB32};
static RenderTextureReadWrite[] m_RTReadWrite = { RenderTextureReadWrite.sRGB, RenderTextureReadWrite.Linear};
static public void GetMaterialDBufferDescription(out RenderTextureFormat[] RTFormat, out RenderTextureReadWrite[] RTReadWrite)
{
RTFormat = m_RTFormat;
RTReadWrite = m_RTReadWrite;
}
}
}

3
ScriptableRenderPipeline/HDRenderPipeline/Material/Decal/DecalData.hlsl


//-------------------------------------------------------------------------------------
#include "../../../Core/ShaderLibrary/Packing.hlsl"
#include "../../../Core/ShaderLibrary/SampleUVMapping.hlsl"
#include "../../../Core/ShaderLibrary/EntityLighting.hlsl"
#include "../MaterialUtilities.hlsl"
void GetSurfaceData(float2 texCoordDS, out DecalSurfaceData surfaceData)
{

79
ScriptableRenderPipeline/HDRenderPipeline/Material/LayeredLit/LayeredLit.shader


_SmoothnessRemapMax2("SmoothnessRemapMax2", Range(0.0, 1.0)) = 1.0
_SmoothnessRemapMax3("SmoothnessRemapMax3", Range(0.0, 1.0)) = 1.0
_AORemapMin0("AORemapMin0", Range(0.0, 1.0)) = 0.0
_AORemapMin1("AORemapMin1", Range(0.0, 1.0)) = 0.0
_AORemapMin2("AORemapMin2", Range(0.0, 1.0)) = 0.0
_AORemapMin3("AORemapMin3", Range(0.0, 1.0)) = 0.0
_AORemapMax0("AORemapMax0", Range(0.0, 1.0)) = 1.0
_AORemapMax1("AORemapMax1", Range(0.0, 1.0)) = 1.0
_AORemapMax2("AORemapMax2", Range(0.0, 1.0)) = 1.0
_AORemapMax3("AORemapMax3", Range(0.0, 1.0)) = 1.0
_MaskMap0("MaskMap0", 2D) = "white" {}
_MaskMap1("MaskMap1", 2D) = "white" {}
_MaskMap2("MaskMap2", 2D) = "white" {}

_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
}
HLSLINCLUDE

// 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
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL

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 _BYPASS_ALPHA_TEST
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL

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"

#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL

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

#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitVelocityPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassVelocity.hlsl"
ENDHLSL

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

#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitDepthPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitDepthPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

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 "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassForward.hlsl"
ENDHLSL

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
#include "../../ShaderVariables.hlsl"

#include "../../Lighting/Lighting.hlsl"
#include "../Lit/ShaderPass/LitSharePass.hlsl"
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassForward.hlsl"
ENDHLSL

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


_SmoothnessRemapMax2("SmoothnessRemapMax2", Range(0.0, 1.0)) = 1.0
_SmoothnessRemapMax3("SmoothnessRemapMax3", Range(0.0, 1.0)) = 1.0
_AORemapMin0("AORemapMin0", Range(0.0, 1.0)) = 0.0
_AORemapMin1("AORemapMin1", Range(0.0, 1.0)) = 0.0
_AORemapMin2("AORemapMin2", Range(0.0, 1.0)) = 0.0
_AORemapMin3("AORemapMin3", Range(0.0, 1.0)) = 0.0
_AORemapMax0("AORemapMax0", Range(0.0, 1.0)) = 1.0
_AORemapMax1("AORemapMax1", Range(0.0, 1.0)) = 1.0
_AORemapMax2("AORemapMax2", Range(0.0, 1.0)) = 1.0
_AORemapMax3("AORemapMax3", Range(0.0, 1.0)) = 1.0
_MaskMap0("MaskMap0", 2D) = "white" {}
_MaskMap1("MaskMap1", 2D) = "white" {}
_MaskMap2("MaskMap2", 2D) = "white" {}

_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
}
HLSLINCLUDE

// 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 ?

#include "../../../Core/ShaderLibrary/common.hlsl"
#include "../../../Core/ShaderLibrary/Wind.hlsl"
#include "../../../Core/ShaderLibrary/GeometricTools.hlsl"
#include "../../../Core/ShaderLibrary/tessellation.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.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
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL

#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 _BYPASS_ALPHA_TEST
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL

#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"

#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassGBuffer.hlsl"
ENDHLSL

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

#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitVelocityPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassVelocity.hlsl"
ENDHLSL

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

#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitDepthPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "../Lit/ShaderPass/LitDepthPass.hlsl"
#include "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassDepthOnly.hlsl"
ENDHLSL

#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 "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassForward.hlsl"
ENDHLSL

#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 "../Lit/LitData.hlsl"
#include "LayeredLitData.hlsl"
#include "../../ShaderPass/ShaderPassForward.hlsl"
ENDHLSL

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)

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


public static GUIContent metallicText = new GUIContent("Metallic", "Metallic scale factor");
public static GUIContent smoothnessText = new GUIContent("Smoothness", "Smoothness scale factor");
public static GUIContent smoothnessRemappingText = new GUIContent("Smoothness Remapping", "Smoothness remapping");
public static GUIContent aoRemappingText = new GUIContent("AmbientOcclusion Remapping", "AmbientOcclusion remapping");
public static GUIContent maskMapSText = new GUIContent("Mask Map - M(R), AO(G), D(B), S(A)", "Mask map");
public static GUIContent maskMapSpecularText = new GUIContent("Mask Map - AO(G), D(B), S(A)", "Mask map");

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 kSmoothnessRemapMin = "_SmoothnessRemapMin";
protected MaterialProperty[] smoothnessRemapMax = new MaterialProperty[kMaxLayerCount];
protected const string kSmoothnessRemapMax = "_SmoothnessRemapMax";
protected MaterialProperty[] aoRemapMin = new MaterialProperty[kMaxLayerCount];
protected const string kAORemapMin = "_AORemapMin";
protected MaterialProperty[] aoRemapMax = new MaterialProperty[kMaxLayerCount];
protected const string kAORemapMax = "_AORemapMax";
protected MaterialProperty[] maskMap = new MaterialProperty[kMaxLayerCount];
protected const string kMaskMap = "_MaskMap";
protected MaterialProperty[] normalScale = new MaterialProperty[kMaxLayerCount];

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;

smoothness[i] = FindProperty(string.Format("{0}{1}", kSmoothness, m_PropertySuffixes[i]), props);
smoothnessRemapMin[i] = FindProperty(string.Format("{0}{1}", kSmoothnessRemapMin, m_PropertySuffixes[i]), props);
smoothnessRemapMax[i] = FindProperty(string.Format("{0}{1}", kSmoothnessRemapMax, m_PropertySuffixes[i]), props);
aoRemapMin[i] = FindProperty(string.Format("{0}{1}", kAORemapMin, m_PropertySuffixes[i]), props);
aoRemapMax[i] = FindProperty(string.Format("{0}{1}", kAORemapMax, m_PropertySuffixes[i]), props);
maskMap[i] = FindProperty(string.Format("{0}{1}", kMaskMap, m_PropertySuffixes[i]), props);
normalMap[i] = FindProperty(string.Format("{0}{1}", kNormalMap, m_PropertySuffixes[i]), props);
normalMapOS[i] = FindProperty(string.Format("{0}{1}", kNormalMapOS, m_PropertySuffixes[i]), props);

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()

smoothnessRemapMin[layerIndex].floatValue = remapMin;
smoothnessRemapMax[layerIndex].floatValue = remapMax;
}
float aoMin = aoRemapMin[layerIndex].floatValue;
float aoMax = aoRemapMax[layerIndex].floatValue;
EditorGUI.BeginChangeCheck();
EditorGUILayout.MinMaxSlider(Styles.aoRemappingText, ref aoMin, ref aoMax, 0.0f, 1.0f);
if (EditorGUI.EndChangeCheck())
{
aoRemapMin[layerIndex].floatValue = aoMin;
aoRemapMax[layerIndex].floatValue = aoMax;
}
}
m_MaterialEditor.TexturePropertySingleLine(((Lit.MaterialId)materialID.floatValue == Lit.MaterialId.LitSpecular) ? Styles.maskMapSpecularText : Styles.maskMapSText, maskMap[layerIndex]);

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

6
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Editor/SubsurfaceScatteringSettingsEditor.Styles.cs


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

new GUIContent("Thin Object", "Choose this mode for thin objects, such as paper or leaves. Transmitted light reuses the shadowing state of the surface."),
new GUIContent("Regular", "Choose this mode for moderately thick objects. For performance reasons, transmitted light ignores occlusion (shadows).")
};
public readonly GUIContent profileMinMaxThickness = new GUIContent("Min-Max Thickness", "Shows the values of the thickness remap below (in millimeters).");
public readonly GUIContent profileThicknessRemap = new GUIContent("Thickness Remap", "Remaps the thickness parameter from [0, 1] to the desired range (in millimeters).");
public readonly GUIContent profileMinMaxThickness = new GUIContent("Min-Max Thickness (mm)", "Shows the values of the thickness remap below (in millimeters).");
public readonly GUIContent profileThicknessRemap = new GUIContent("Thickness Remap (mm)", "Remaps the thickness parameter from [0, 1] to the desired range (in millimeters).");
public readonly GUIContent profileWorldScale = new GUIContent("World Scale", "Size of the world unit in meters.");
// Old SSS Model >>>
public readonly GUIContent profileScatterDistance1 = new GUIContent("Scattering Distance #1", "The radius (in centimeters) of the 1st Gaussian filter, one per color channel. Alpha is ignored. The blur is energy-preserving, so a wide filter results in a large area with small contributions of individual samples. Smaller values increase the sharpness.");

22
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;
}
}

{
m_InitPreFGD = CoreUtils.CreateEngineMaterial("Hidden/HDRenderPipeline/PreIntegratedFGD");
// For DisneyDiffuse integration values goes from (0.5 to 1.53125). GGX need 0 to 1. Use float format.
m_PreIntegratedFGD = new RenderTexture(128, 128, 0, RenderTextureFormat.ARGB2101010, RenderTextureReadWrite.Linear);
m_PreIntegratedFGD.filterMode = FilterMode.Bilinear;
m_PreIntegratedFGD.wrapMode = TextureWrapMode.Clamp;

692
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.hlsl
文件差异内容过多而无法显示
查看文件

58
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/Lit.shader


_MaskMap("MaskMap", 2D) = "white" {}
_SmoothnessRemapMin("SmoothnessRemapMin", Float) = 0.0
_SmoothnessRemapMax("SmoothnessRemapMax", Float) = 1.0
_AORemapMin("AORemapMin", Float) = 0.0
_AORemapMax("AORemapMax", Float) = 1.0
_NormalMap("NormalMap", 2D) = "bump" {} // Tangent space normal map
_NormalMapOS("NormalMapOS", 2D) = "white" {} // Object space normal map - no good default value

_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

[ToggleOff] _DistortionDepthTest("Distortion Depth Test Enable", Float) = 0.0
[ToggleOff] _DistortionDepthTest("Distortion Depth Test Enable", Float) = 1.0
[Enum(Add, 0, Multiply, 1)] _DistortionBlendMode("Distortion Blend Mode", Int) = 0
[HideInInspector] _DistortionSrcBlend("Distortion Blend Src", Int) = 0
[HideInInspector] _DistortionDstBlend("Distortion Blend Dst", Int) = 0

_DistortionScale("Distortion Scale", Float) = 1
_DistortionVectorScale("Distortion Vector Scale", Float) = 2
_DistortionVectorBias("Distortion Vector Bias", Float) = -1
_DistortionBlurScale("Distortion Blur Scale", Float) = 1
_DistortionBlurRemapMin("DistortionBlurRemapMin", Float) = 0.0
_DistortionBlurRemapMax("DistortionBlurRemapMax", Float) = 1.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
}
HLSLINCLUDE

#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"
#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 _BYPASS_ALPHA_TEST
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/LitSharePass.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"

954
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitData.hlsl
文件差异内容过多而无法显示
查看文件

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


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

float _AlphaCutoff;
float4 _DoubleSidedConstants;
float _DistortionScale;
float _DistortionVectorScale;
float _DistortionVectorBias;
float _DistortionBlurScale;
float _DistortionBlurRemapMin;
float _DistortionBlurRemapMax;

// 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

float _Smoothness;
float _SmoothnessRemapMin;
float _SmoothnessRemapMax;
float _AORemapMin;
float _AORemapMax;
float _NormalScale;

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

PROP_DECL(float, _Smoothness);
PROP_DECL(float, _SmoothnessRemapMin);
PROP_DECL(float, _SmoothnessRemapMax);
PROP_DECL(float, _AORemapMin);
PROP_DECL(float, _AORemapMax);
PROP_DECL(float, _NormalScale);
float4 _NormalMap0_TexelSize; // Unity facility. This will provide the size of the base normal to the shader

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

19
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;
}
}

uint sampleCount = 4096)
{
float3x3 localToWorld = float3x3(bsdfData.tangentWS, bsdfData.bitangentWS, bsdfData.normalWS);
float NdotV = max(preLightData.NdotV, MIN_N_DOT_V);
float NdotV = preLightData.NdotV;
float3 acc = float3(0.0, 0.0, 0.0);
// Add some jittering on Hammersley2d

if (NdotL > 0.0)
{
float3 H = normalize(L + V);
float LdotH = dot(L, H);
float LdotV = dot(L, V);
float disneyDiffuse = DisneyDiffuse(NdotV, NdotL, LdotH, bsdfData.perceptualRoughness);
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;
}
}

localToWorld = GetLocalFrame(bsdfData.normalWS);
}
float NdotV = max(preLightData.NdotV, MIN_N_DOT_V);
float3 acc = float3(0.0, 0.0, 0.0);
float NdotV = preLightData.NdotV;
float3 acc = float3(0.0, 0.0, 0.0);
// Add some jittering on Hammersley2d
float2 randNum = InitRandom(V.xy * 0.5 + 0.5);

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


_MaskMap("MaskMap", 2D) = "white" {}
_SmoothnessRemapMin("SmoothnessRemapMin", Float) = 0.0
_SmoothnessRemapMax("SmoothnessRemapMax", Float) = 1.0
_AORemapMin("AORemapMin", Float) = 0.0
_AORemapMax("AORemapMax", Float) = 1.0
_NormalMap("NormalMap", 2D) = "bump" {} // Tangent space normal map
_NormalMapOS("NormalMapOS", 2D) = "white" {} // Object space normal map - no good default value

_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

[ToggleOff] _DistortionOnly("Distortion Only", Float) = 0.0
[ToggleOff] _DistortionDepthTest("Distortion Depth Test Enable", Float) = 0.0
[ToggleOff] _DistortionDepthTest("Distortion Depth Test Enable", Float) = 1.0
[Enum(Add, 0, Multiply, 1)] _DistortionBlendMode("Distortion Blend Mode", Int) = 0
[HideInInspector] _DistortionSrcBlend("Distortion Blend Src", Int) = 0
[HideInInspector] _DistortionDstBlend("Distortion Blend Dst", Int) = 0

_DistortionScale("Distortion Scale", Float) = 1
_DistortionVectorScale("Distortion Vector Scale", Float) = 2
_DistortionVectorBias("Distortion Vector Bias", Float) = -1
_DistortionBlurScale("Distortion Blur Scale", Float) = 1
_DistortionBlurRemapMin("DistortionBlurRemapMin", Float) = 0.0
_DistortionBlurRemapMax("DistortionBlurRemapMax", Float) = 1.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
}
HLSLINCLUDE

#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 ?

#include "../../../Core/ShaderLibrary/common.hlsl"
#include "../../../Core/ShaderLibrary/Wind.hlsl"
#include "../../../Core/ShaderLibrary/GeometricTools.hlsl"
#include "../../../Core/ShaderLibrary/tessellation.hlsl"
#include "../../ShaderPass/FragInputs.hlsl"
#include "../../ShaderPass/ShaderPass.cs.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
#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 _BYPASS_ALPHA_TEST
#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
#include "../../ShaderVariables.hlsl"
#include "../../Material/Material.hlsl"
#include "ShaderPass/LitSharePass.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"

998
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LtcData.DisneyDiffuse.cs
文件差异内容过多而无法显示
查看文件

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);
}

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


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)

111
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;

weightedStdDev.w = Mathf.Lerp(maxStdDev1, maxStdDev2, lerpWeight);
// Store (1 / (2 * WeightedVariance)) per color channel.
halfRcpWeightedVariances.Set(
0.5f / (weightedStdDev.x * weightedStdDev.x),
0.5f / (weightedStdDev.y * weightedStdDev.y),
0.5f / (weightedStdDev.z * weightedStdDev.z),
0.5f / (weightedStdDev.w * weightedStdDev.w)
);
// Warning: do not use halfRcpWeightedVariances.Set(). It will not work.
halfRcpWeightedVariances = new Vector4(0.5f / (weightedStdDev.x * weightedStdDev.x),
0.5f / (weightedStdDev.y * weightedStdDev.y),
0.5f / (weightedStdDev.z * weightedStdDev.z),
0.5f / (weightedStdDev.w * weightedStdDev.w));
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)
static float DisneyProfilePdf(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)
{
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)

54
ScriptableRenderPipeline/HDRenderPipeline/Material/Lit/LitDataMeshModification.hlsl


{
float maxDisplacement = GetMaxDisplacement();
float frustumEps = -maxDisplacement;
bool3 frustumCullEdgesMainView = CullTriangleEdgesFrustum(p0, p1, p2, frustumEps, _FrustumPlanes, 5); // Do not test the far plane
bool frustumCulledCurrentView = WorldViewFrustumCull(p0, p1, p2, maxDisplacement, (float4[4])_FrustumPlanes); // _FrustumPlanes are primary camera planes
bool frustumCulledMainView = false;
bool frustumCullCurrView = all(frustumCullEdgesMainView);
bool frustumCulledCurrentView = WorldViewFrustumCull(p0, p1, p2, maxDisplacement, (float4[4])unity_CameraWorldClipPlanes); // unity_CameraWorldClipPlanes is set by legacy Unity in case of shadow and contain shadow view plan
// In the case of shadow, we don't want to tessellate anything that is not seen by the main view frustum. It can result in minor popping of tessellation into a shadow but we can't afford it anyway.
bool frustumCulledMainView = WorldViewFrustumCull(p0, p1, p2, maxDisplacement, (float4[4])_FrustumPlanes);
// 'unity_CameraWorldClipPlanes' are camera-relative rendering aware.
bool frustumCullCurrView = CullTriangleFrustum(p0, p1, p2, frustumEps, unity_CameraWorldClipPlanes, 4); // Do not test near/far planes
if (_TessellationBackFaceCullEpsilon > -0.99) // Is backface culling enabled ?
if (_TessellationBackFaceCullEpsilon > -1.0) // Is back-face culling enabled ?
// Caution: don't change p1/p2 directly as it is use later
float3 backfaceP1 = unity_WorldTransformParams.w < 0.0 ? p2 : p1;
float3 backfaceP2 = unity_WorldTransformParams.w < 0.0 ? p1 : p2;
faceCull = BackFaceCullTriangle(p0, backfaceP1, backfaceP2, _TessellationBackFaceCullEpsilon, GetCurrentViewPosition()); // Use shadow view
float winding = unity_WorldTransformParams.w;
faceCull = CullTriangleBackFace(p0, p1, p2, _TessellationBackFaceCullEpsilon, GetCurrentViewPosition(), winding); // Use shadow view
if (frustumCulledCurrentView || faceCull)
if (frustumCullCurrView || faceCull)
return float4(0.0, 0.0, 0.0, 0.0);
}
// See comment above:
// During shadow passes, we decide that anything outside the main view frustum should not be tessellated.
if (frustumCulledMainView)
{
return float4(1.0, 1.0, 1.0, 1.0);
return 0;
// We use the parameters of the primary (scene view) camera in order
// to have identical tessellation levels for both the scene view and
// shadow views. Otherwise, depth comparisons become meaningless!
float3 tessFactor = float3(1.0, 1.0, 1.0);
// For performance reasons, we choose not to tessellate outside of the main camera view
// (we perform this test both during the regular scene rendering and the shadow pass).
// For edges not visible from the main view, our goal is to set the tessellation factor to 1.
// In this case, we set the tessellation factor to 0 here.
// That way, all scaling of this tessellation factor will still result in 0.
// Before we call CalcTriTessFactorsFromEdgeTessFactors(), all factors are clamped by max(f, 1),
// which achieves the desired effect.
float3 edgeTessFactors = float3(frustumCullEdgesMainView.x ? 0 : 1, frustumCullEdgesMainView.y ? 0 : 1, frustumCullEdgesMainView.z ? 0 : 1);
tessFactor *= GetScreenSpaceTessFactor( p0, p1, p2, _ViewProjMatrix, _ScreenSize, _TessellationFactorTriangleSize); // Use primary camera view
edgeTessFactors *= GetScreenSpaceTessFactor( p0, p1, p2, _ViewProjMatrix, _ScreenSize, _TessellationFactorTriangleSize); // Use primary camera view
}
// Distance based tessellation

// We square the disance factor as it allow a better percptual descrease of vertex density.
tessFactor *= distFactor * distFactor;
edgeTessFactors *= distFactor * distFactor;
tessFactor *= _TessellationFactor;
edgeTessFactors *= _TessellationFactor;
tessFactor.xyz = float3(max(1.0, tessFactor.x), max(1.0, tessFactor.y), max(1.0, tessFactor.z));
edgeTessFactors = max(edgeTessFactors, float3(1.0, 1.0, 1.0));
return CalcTriEdgeTessFactors(tessFactor);
return CalcTriTessFactorsFromEdgeTessFactors(edgeTessFactors);
}
// tessellationFactors

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


surfaceData.perceptualSmoothness = lerp(surfaceData.perceptualSmoothness, saturate(smoothnessOverlay), detailMask);
#endif
// MaskMap is RGBA: Metallic, Ambient Occlusion (Optional), emissive Mask (Optional), Smoothness
// MaskMap is RGBA: Metallic, Ambient Occlusion (Optional), detail Mask (Optional), Smoothness
surfaceData.ambientOcclusion = lerp(ADD_IDX(_AORemapMin), ADD_IDX(_AORemapMax), surfaceData.ambientOcclusion);
#else
surfaceData.metallic = 1.0;
surfaceData.ambientOcclusion = 1.0;

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;

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

23
ScriptableRenderPipeline/HDRenderPipeline/Material/MaterialUtilities.hlsl


#endif
}
float4 SampleShadowMask(float3 positionWS, float2 uvStaticLightmap) // normalWS not use for now
{
#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;
}
#endif
return rawOcclusionMask;
}
float2 CalculateVelocity(float4 positionCS, float4 previousPositionCS)
{
// This test on define is required to remove warning of divide by 0 when initializing empty struct

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


protected const string kDistortionBlendMode = "_DistortionBlendMode";
protected MaterialProperty distortionScale = null;
protected const string kDistortionScale = "_DistortionScale";
protected MaterialProperty distortionVectorScale = null;
protected const string kDistortionVectorScale = "_DistortionVectorScale";
protected MaterialProperty distortionVectorBias = null;
protected const string kDistortionVectorBias = "_DistortionVectorBias";
protected MaterialProperty distortionBlurScale = null;
protected const string kDistortionBlurScale = "_DistortionBlurScale";
protected MaterialProperty distortionBlurRemapMin = null;

distortionVectorMap = FindProperty(kDistortionVectorMap, props, false);
distortionBlendMode = FindProperty(kDistortionBlendMode, props, false);
distortionScale = FindProperty(kDistortionScale, props, false);
distortionVectorScale = FindProperty(kDistortionVectorScale, props, false);
distortionVectorBias = FindProperty(kDistortionVectorBias, props, false);
distortionBlurScale = FindProperty(kDistortionBlurScale, props, false);
distortionBlurRemapMin = FindProperty(kDistortionBlurRemapMin, props, false);
distortionBlurRemapMax = FindProperty(kDistortionBlurRemapMax, props, false);

m_MaterialEditor.ShaderProperty(distortionDepthTest, StylesBaseUnlit.distortionDepthTestText);
EditorGUI.indentLevel++;
m_MaterialEditor.TexturePropertySingleLine(StylesBaseUnlit.distortionVectorMapText, distortionVectorMap);
m_MaterialEditor.TexturePropertySingleLine(StylesBaseUnlit.distortionVectorMapText, distortionVectorMap, distortionVectorScale, distortionVectorBias);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(distortionScale, StylesBaseUnlit.distortionScaleText);
m_MaterialEditor.ShaderProperty(distortionBlurScale, StylesBaseUnlit.distortionBlurScaleText);

// or is enabled and may be modified at runtime. This state depends on the values of the current flag and emissive color.
// 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);
// DoubleSidedGI has to be synced with our double sided toggle
var serializedObject = new SerializedObject(material);
var doubleSidedGIppt = serializedObject.FindProperty("m_DoubleSidedGI");
doubleSidedGIppt.boolValue = doubleSidedEnable;
serializedObject.ApplyModifiedProperties();
}
// 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)

bool distortionEnable = material.GetFloat(kDistortionEnable) > 0.0f;
bool distortionEnable = material.GetFloat(kDistortionEnable) > 0.0f && ((SurfaceType)material.GetFloat(kSurfaceType) == SurfaceType.Transparent);
bool distortionOnly = false;
if (material.HasProperty(kDistortionOnly))

// NB RenderQueue editor is not shown on purpose: we want to override it based on blend mode
EditorGUI.indentLevel++;
m_MaterialEditor.EnableInstancingField();
m_MaterialEditor.DoubleSidedGIField();
EditorGUI.indentLevel--;
}

SetupMaterialKeywordsAndPassInternal((Material)obj);
}
}
public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
{
base.AssignNewShaderToMaterial(material, oldShader, newShader);
SetupMaterialKeywordsAndPassInternal(material);
}
// This is call by the inspector

6
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;

EditorGUILayout.LabelField(Styles.InputsText, EditorStyles.boldLabel);
m_MaterialEditor.TexturePropertySingleLine(Styles.colorText, colorMap, color);
m_MaterialEditor.TextureScaleOffsetProperty(colorMap);
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

18
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

[ToggleOff] _DistortionDepthTest("Distortion Depth Test Enable", Float) = 0.0
[ToggleOff] _DistortionDepthTest("Distortion Depth Test Enable", Float) = 1.0
[Enum(Add, 0, Multiply, 1)] _DistortionBlendMode("Distortion Blend Mode", Int) = 0
[HideInInspector] _DistortionSrcBlend("Distortion Blend Src", Int) = 0
[HideInInspector] _DistortionDstBlend("Distortion Blend Dst", Int) = 0

_DistortionScale("Distortion Scale", Float) = 1
_DistortionVectorScale("Distortion Vector Scale", Float) = 2
_DistortionVectorBias("Distortion Vector Bias", Float) = -1
_DistortionBlurScale("Distortion Blur Scale", Float) = 1
_DistortionBlurRemapMin("DistortionBlurRemapMin", Float) = 0.0
_DistortionBlurRemapMax("DistortionBlurRemapMax", Float) = 1.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
}
HLSLINCLUDE

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

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


void DoAlphaTest(float alpha, float alphaCutoff)
{
// Don't do the clip when rendering forward opaque (unlit). Forward opaque always have a prepass (with depth test on)
#if !(SHADERPASS == SHADERPASS_FORWARD_UNLIT && !defined(_SURFACE_TYPE_TRANSPARENT))
clip(alpha - alphaCutoff);
#endif
}
surfaceData.color = SAMPLE_TEXTURE2D(_ColorMap, sampler_ColorMap, input.texCoord0).rgb * _Color.rgb;
float alpha = SAMPLE_TEXTURE2D(_ColorMap, sampler_ColorMap, input.texCoord0).a * _Color.a;
float2 unlitColorMapUv = TRANSFORM_TEX(input.texCoord0, _UnlitColorMap);
surfaceData.color = SAMPLE_TEXTURE2D(_UnlitColorMap, sampler_UnlitColorMap, unlitColorMapUv).rgb * _UnlitColor.rgb;
float alpha = SAMPLE_TEXTURE2D(_UnlitColorMap, sampler_UnlitColorMap, unlitColorMapUv).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;
distortion.rg = distortion.rg * _DistortionVectorScale.xx + _DistortionVectorBias.xx;
builtinData.distortion = distortion.rg * _DistortionScale;
builtinData.distortionBlur = clamp(distortion.b * _DistortionBlurScale, 0.0, 1.0) * (_DistortionBlurRemapMax - _DistortionBlurRemapMin) + _DistortionBlurRemapMin;
#else

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


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

SAMPLER2D(sampler_EmissiveColorMap);
float4 _EmissiveColorMap_ST;
float _DistortionVectorScale;
float _DistortionVectorBias;
float _DistortionBlurScale;
float _DistortionBlurRemapMin;
float _DistortionBlurRemapMax;

// 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
// TODO: Fix the code in legacy unity so we can customize the behavior for GI
float3 _EmissionColor;

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


// Include
//-------------------------------------------------------------------------------------
#include "../../../Core/ShaderLibrary/CommonMaterial.hlsl"
#include "../../../Core/ShaderLibrary/CommonMaterial.hlsl"
#define USE_LEGACY_UNITY_MATRIX_VARIABLES
#include "../../ShaderVariables.hlsl"

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)

2
ScriptableRenderPipeline/HDRenderPipeline/ShaderPass/TessellationShare.hlsl


output.edge[0] = min(tf.x, MAX_TESSELLATION_FACTORS);
output.edge[1] = min(tf.y, MAX_TESSELLATION_FACTORS);
output.edge[2] = min(tf.z, MAX_TESSELLATION_FACTORS);
output.inside = min(tf.w, MAX_TESSELLATION_FACTORS);
output.inside = min(tf.w, MAX_TESSELLATION_FACTORS);
return output;
}

36
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);

// ----------------------------------------------------------------------------
// TODO: all affine matrices should be 3x4.
CBUFFER_START(UnityPerPass)
float4x4 _PrevViewProjMatrix;
float4x4 _ViewProjMatrix;

float4x4 _InvViewMatrix;
float4x4 _InvProjMatrix;
float4 _InvProjParam;
float4 _ScreenSize; // (w, h, 1/w, 1/h)
float4 _FrustumPlanes[6]; // (N, -dot(N, P))
float4 _ScreenSize; // {w, h, 1/w, 1/h}
float4 _FrustumPlanes[6]; // {(a, b, c) = N, d = -dot(N, P)} [L, R, T, B, N, F]
CBUFFER_END
// 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
float4x4 OptimizeProjectionMatrix(float4x4 M)
{
// Matrix format (x = non-constant value).
// Orthographic Perspective Combined(OR)
// | x 0 0 x | | x 0 x 0 | | x 0 x x |
// | 0 x 0 x | | 0 x x 0 | | 0 x x x |
// | x x x x | | x x x x | | x x x x | <- oblique projection row
// | 0 0 0 1 | | 0 0 x 0 | | 0 0 x x |
// Notice that some values are always 0.
// We can avoid loading and doing math with constants.
M._21_41 = 0;
M._12_42 = 0;
return M;
}
#ifdef USE_LEGACY_UNITY_MATRIX_VARIABLES
#include "ShaderVariablesMatrixDefsLegacyUnity.hlsl"

11
ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesFunctions.hlsl


// Note: '_WorldSpaceCameraPos' is set by the legacy Unity code.
float3 GetPrimaryCameraPosition()
{
return GetCameraRelativePositionWS(_WorldSpaceCameraPos);
#if (SHADEROPTIONS_CAMERA_RELATIVE_RENDERING != 0)
return float3(0, 0, 0);
#else
return _WorldSpaceCameraPos;
#endif
}
// Could be e.g. the position of a primary camera or a shadow-casting light.

return (unity_OrthoParams.w == 0);
#else
// TODO: set 'unity_OrthoParams' during the shadow pass.
return (GetWorldToHClipMatrix()[3].x != 0 ||
GetWorldToHClipMatrix()[3].y != 0 ||
GetWorldToHClipMatrix()[3].z != 0 ||
GetWorldToHClipMatrix()[3].w != 1);
return UNITY_MATRIX_P[3][3] == 0;
#endif
}

2
ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesMatrixDefsHDCamera.hlsl


#define UNITY_MATRIX_I_M unity_WorldToObject
#define UNITY_MATRIX_V _ViewMatrix
#define UNITY_MATRIX_I_V _InvViewMatrix
#define UNITY_MATRIX_P _ProjMatrix
#define UNITY_MATRIX_P OptimizeProjectionMatrix(_ProjMatrix)
#define UNITY_MATRIX_I_P _InvProjMatrix
#define UNITY_MATRIX_VP _ViewProjMatrix
#define UNITY_MATRIX_MVP mul(UNITY_MATRIX_VP, UNITY_MATRIX_M)

2
ScriptableRenderPipeline/HDRenderPipeline/ShaderVariablesMatrixDefsLegacyUnity.hlsl


#define UNITY_MATRIX_I_M unity_WorldToObject
#define UNITY_MATRIX_V unity_MatrixV
#define UNITY_MATRIX_I_V unity_MatrixInvV
#define UNITY_MATRIX_P glstate_matrix_projection
#define UNITY_MATRIX_P OptimizeProjectionMatrix(glstate_matrix_projection)
#define UNITY_MATRIX_I_P inverse_glstate_matrix_projection_is_not_defined
#define UNITY_MATRIX_VP unity_MatrixVP
#define UNITY_MATRIX_MVP mul(UNITY_MATRIX_VP, UNITY_MATRIX_M)

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

正在加载...
取消
保存