浏览代码

Merge branch 'master' into EmissiveMeshForAreaLight

/main
Sebastien Lagarde 7 年前
当前提交
5196e7ed
共有 124 个文件被更改,包括 21717 次插入18940 次删除
  1. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1102_Unlit_Distortion.png
  2. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1103_Unlit_Distortion_DepthTest.png
  3. 749
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1202_Lit_DoubleSideNormalMode.png
  4. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1204_Lit_Transparent_Fog.png
  5. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1208_Lit_Displacement_POM.png
  6. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1209_Lit_Displacement_Vertex.png
  7. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1210_Lit_BentNormal.png
  8. 790
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1212_Lit_Emission.png
  9. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1302_SSS_MaxRadius.png
  10. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1303_SSS_Pre-Post.png
  11. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2001_Dynamic_Directional.png
  12. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2002_Dynamic_Mix.png
  13. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2101_GI_Metapass.png
  14. 597
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2102_GI_Emission.png
  15. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2103_BakeMixed.png
  16. 965
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2201_ReflectionProbes_Priority.png
  17. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2202_ReflectionProbes_Volume.png
  18. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2203_PlanarProbes.png
  19. 999
      TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2401_Light_on_Tesselation.png
  20. 118
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0006_Std_Empty_Deferred_HDR.png
  21. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0100_Std_FXAA.png
  22. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0101_Std_FXAA_Fast.png
  23. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0102_Std_SMAA.png
  24. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0200_Std_Vignette.png
  25. 797
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0201_Std_LensDistort.png
  26. 764
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0202_Std_LensUnDistort.png
  27. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0203_Std_ChromaticAberration.png
  28. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0204_Std_ChromaticAberration_Fast.png
  29. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0205_Std_Grain.png
  30. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0206_Std_Grain_Colored.png
  31. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0207_Std_Bloom_HDR.png
  32. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0208_Std_Bloom_HDR_Fast.png
  33. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0209_Std_Bloom_LDR.png
  34. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0210_Std_Bloom_LDR_Fast.png
  35. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0211_Std_LensDirt.png
  36. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0212_Std_ColorGrading_HDR_Neutral.png
  37. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0213_Std_ColorGrading_LDR_Neutral.png
  38. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0214_Std_ColorGrading_HDR_Mix.png
  39. 999
      TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0215_Std_ColorGrading_LDR_Mix.png
  40. 3
      com.unity.render-pipelines.core/CHANGELOG.md
  41. 22
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/BSDF.hlsl
  42. 1
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl
  43. 17
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/ImageBasedLighting.hlsl
  44. 8
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Macros.hlsl
  45. 5
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Sampling/Sampling.hlsl
  46. 52
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Shadow/ShadowSampling.hlsl
  47. 13
      com.unity.render-pipelines.core/CoreRP/ShaderLibrary/UnityInstancing.hlsl
  48. 100
      com.unity.render-pipelines.core/CoreRP/Shadow/Shadow.cs
  49. 9
      com.unity.render-pipelines.core/CoreRP/Shadow/ShadowBase.cs
  50. 1
      com.unity.render-pipelines.core/CoreRP/Shadow/ShadowBase.cs.hlsl
  51. 7
      com.unity.render-pipelines.high-definition/CHANGELOG.md
  52. 1
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitUI.cs
  53. 4
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/StackLit/BaseMaterialUI.cs
  54. 127
      com.unity.render-pipelines.high-definition/HDRP/Editor/Material/StackLit/StackLitUI.cs
  55. 5
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/RenderPipelineSettingsUI.cs
  56. 7
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedShadowInitParameters.cs
  57. 24
      com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/ShadowInitParametersUI.cs
  58. 36
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDPBRPass.template
  59. 29
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDPBRSubShader.cs
  60. 18
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDSubShaderUtilities.cs
  61. 32
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDUnlitPassForward.template
  62. 9
      com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDUnlitSubShader.cs
  63. 4
      com.unity.render-pipelines.high-definition/HDRP/HDRenderPipelineAsset.asset
  64. 25
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightEvaluation.hlsl
  65. 8
      com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoop.cs
  66. 2
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumeTextureAtlas.cs
  67. 2
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumeVoxelization.compute
  68. 6
      com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumetricLighting.cs
  69. 15
      com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalUtilities.hlsl
  70. 22
      com.unity.render-pipelines.high-definition/HDRP/Material/LTCAreaLight/LTCAreaLight.cs
  71. 1
      com.unity.render-pipelines.high-definition/HDRP/Material/LTCAreaLight/LTCAreaLight.hlsl
  72. 998
      com.unity.render-pipelines.high-definition/HDRP/Material/LTCAreaLight/LtcData.DisneyDiffuse.cs
  73. 992
      com.unity.render-pipelines.high-definition/HDRP/Material/LTCAreaLight/LtcData.GGX.cs
  74. 2
      com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitData.hlsl
  75. 177
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.hlsl
  76. 8
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitBuiltinData.hlsl
  77. 11
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitData.hlsl
  78. 10
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitDataDisplacement.hlsl
  79. 4
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitDataIndividualLayer.hlsl
  80. 21
      com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitDataMeshModification.hlsl
  81. 16
      com.unity.render-pipelines.high-definition/HDRP/Material/MaterialUtilities.hlsl
  82. 3
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.cs
  83. 34
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.cs.hlsl
  84. 609
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.hlsl
  85. 125
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.shader
  86. 73
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLitData.hlsl
  87. 67
      com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLitProperties.hlsl
  88. 4
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/FragInputs.hlsl
  89. 11
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDBuffer.hlsl
  90. 4
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDepthOnly.hlsl
  91. 4
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDistortion.hlsl
  92. 4
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForward.hlsl
  93. 4
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForwardUnlit.hlsl
  94. 4
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassGBuffer.hlsl
  95. 7
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassLightTransport.hlsl
  96. 24
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassVelocity.hlsl
  97. 16
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/TessellationShare.hlsl
  98. 16
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/VaryingMesh.hlsl
  99. 20
      com.unity.render-pipelines.high-definition/HDRP/ShaderPass/VertMesh.hlsl
  100. 26
      com.unity.render-pipelines.high-definition/HDRP/ShaderVariables.hlsl

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1102_Unlit_Distortion.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1103_Unlit_Distortion_DepthTest.png
文件差异内容过多而无法显示
查看文件

749
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1202_Lit_DoubleSideNormalMode.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1204_Lit_Transparent_Fog.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1208_Lit_Displacement_POM.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1209_Lit_Displacement_Vertex.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1210_Lit_BentNormal.png
文件差异内容过多而无法显示
查看文件

790
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1212_Lit_Emission.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1302_SSS_MaxRadius.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/1303_SSS_Pre-Post.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2001_Dynamic_Directional.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2002_Dynamic_Mix.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2101_GI_Metapass.png
文件差异内容过多而无法显示
查看文件

597
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2102_GI_Emission.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2103_BakeMixed.png
文件差异内容过多而无法显示
查看文件

965
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2201_ReflectionProbes_Priority.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2202_ReflectionProbes_Volume.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2203_PlanarProbes.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/HDRP_Tests/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/2401_Light_on_Tesselation.png
文件差异内容过多而无法显示
查看文件

118
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0006_Std_Empty_Deferred_HDR.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0100_Std_FXAA.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0101_Std_FXAA_Fast.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0102_Std_SMAA.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0200_Std_Vignette.png
文件差异内容过多而无法显示
查看文件

797
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0201_Std_LensDistort.png
文件差异内容过多而无法显示
查看文件

764
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0202_Std_LensUnDistort.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0203_Std_ChromaticAberration.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0204_Std_ChromaticAberration_Fast.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0205_Std_Grain.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0206_Std_Grain_Colored.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0207_Std_Bloom_HDR.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0208_Std_Bloom_HDR_Fast.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0209_Std_Bloom_LDR.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0210_Std_Bloom_LDR_Fast.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0211_Std_LensDirt.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0212_Std_ColorGrading_HDR_Neutral.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0213_Std_ColorGrading_LDR_Neutral.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0214_Std_ColorGrading_HDR_Mix.png
文件差异内容过多而无法显示
查看文件

999
TestProjects/PostProcessing/Assets/ReferenceImages/Linear/WindowsEditor/Direct3D11/0215_Std_ColorGrading_LDR_Mix.png
文件差异内容过多而无法显示
查看文件

3
com.unity.render-pipelines.core/CHANGELOG.md


## [Unreleased]
### Added
- Add PCSS shadow filter
### Improvements
- Improved volume UI & styling

22
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/BSDF.hlsl


}
// Evaluate the reflectance for a thin-film layer on top of a dielectric medum.
real3 EvalIridescence(real eta_1, real cosTheta1, real iridescenceThickness, real3 baseLayerFresnel0)
real3 EvalIridescence(real eta_1, real cosTheta1, real iridescenceThickness, real3 baseLayerFresnel0, real iorOverBaseLayer = 0.0)
{
// iridescenceThickness unit is micrometer for this equation here. Mean 0.5 is 500nm.
real Dinc = 3.0 * iridescenceThickness;

// Force eta_2 -> eta_1 when Dinc -> 0.0
// real eta_2 = lerp(eta_1, eta_2, smoothstep(0.0, 0.03, Dinc));
// Evaluate the cosTheta on the base layer (Snell law)
real cosTheta2 = sqrt(1.0 - Sq(eta_1 / eta_2) * (1.0 - Sq(cosTheta1)));
real sinTheta2 = Sq(eta_1 / eta_2) * (1.0 - Sq(cosTheta1));
// Handle TIR
if (sinTheta2 > 1.0)
return real3(1.0, 1.0, 1.0);
//Or use this "artistic hack" to get more continuity even though wrong (test with dual normal maps to understand the difference)
//if( sinTheta2 > 1.0 ) { sinTheta2 = 2 - sinTheta2; }
real cosTheta2 = sqrt(1.0 - sinTheta2);
// First interface
real R0 = IorToFresnel0(eta_2, eta_1);

real phi21 = PI - phi12;
// Second interface
// The f0 or the base should account for the new computed eta_2 on top.
// This is optionally done if we are given the needed current ior over the base layer that is accounted for
// in the baseLayerFresnel0 parameter:
if (iorOverBaseLayer > 0.0)
{
// Fresnel0ToIor will give us a ratio of baseIor/topIor, hence we * iorOverBaseLayer to get the baseIor
real3 baseIor = iorOverBaseLayer * Fresnel0ToIor(baseLayerFresnel0 + 0.0001); // guard against 1.0
baseLayerFresnel0 = IorToFresnel0(baseIor, eta_2);
}
real3 R23 = F_Schlick(baseLayerFresnel0, cosTheta2);
real phi23 = 0.0;

1
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Common.hlsl


// space at the end of the variable name
// WS: world space
// RWS: Camera-Relative world space. A space where the translation of the camera have already been substract in order to improve precision
// VS: view space
// OS: object space
// CS: Homogenous clip spaces

17
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/ImageBasedLighting.hlsl


return normalize(lerp(N, grainNormal, anisotropy));
}
// For GGX aniso and IBL we have done an empirical (eye balled) approximation compare to the reference.
// We use a single fetch, and we stretch the normal to use based on various criteria.
// result are far away from the reference but better than nothing
// Anisotropic ratio (0->no isotropic; 1->full anisotropy in tangent direction) - positive use bitangentWS - negative use tangentWS
// Note: returned iblPerceptualRoughness shouldn't be use for sampling FGD texture in a pre-integration
void GetGGXAnisotropicModifiedNormalAndRoughness(real3 bitangentWS, real3 tangentWS, real3 N, real3 V, real anisotropy, real perceptualRoughness, out real3 iblN, out real iblPerceptualRoughness)
{
// For positive anisotropy values: tangent = highlight stretch (anisotropy) direction, bitangent = grain (brush) direction.
float3 grainDirWS = (anisotropy >= 0.0) ? bitangentWS : tangentWS;
// Reduce stretching for (perceptualRoughness < 0.2).
float stretch = abs(anisotropy) * saturate(5.0 * perceptualRoughness);
// NOTE: If we follow the theory we should use the modified normal for the different calculation implying a normal (like NdotV)
// However modified normal is just a hack. The goal is just to stretch a cubemap, no accuracy here. Let's save performance instead.
iblN = GetAnisotropicModifiedNormal(grainDirWS, N, V, stretch);
iblPerceptualRoughness = perceptualRoughness * saturate(1.2 - abs(anisotropy));
}
// Ref: "Moving Frostbite to PBR", p. 69.
real3 GetSpecularDominantDir(real3 N, real3 R, real perceptualRoughness, real NdotV)
{

8
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Macros.hlsl


#define TRANSFORM_TEX(tex, name) ((tex.xy) * name##_ST.xy + name##_ST.zw)
#define GET_TEXELSIZE_NAME(name) (name##_TexelSize)
#if UNITY_REVERSED_Z
# define COMPARE_DEVICE_DEPTH_CLOSER(shadowMapDepth, zDevice) (shadowMapDepth > zDevice)
# define COMPARE_DEVICE_DEPTH_CLOSEREQUAL(shadowMapDepth, zDevice) (shadowMapDepth >= zDevice)
#else
# define COMPARE_DEVICE_DEPTH_CLOSER(shadowMapDepth, zDevice) (shadowMapDepth < zDevice)
# define COMPARE_DEVICE_DEPTH_CLOSEREQUAL(shadowMapDepth, zDevice) (shadowMapDepth <= zDevice)
#endif
#endif // UNITY_MACROS_INCLUDED

5
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/Sampling/Sampling.hlsl


//-----------------------------------------------------------------------------
// Sampling function
// Reference : http://www.cs.virginia.edu/~jdl/bib/globillum/mis/shirley96.pdf + PBRT
// Caution: Our light point backward (-Z), these sampling function follow this convention
//-----------------------------------------------------------------------------
// Performs uniform sampling of the unit disk.

{
// Random point at rectangle surface
P = real3((u.x - 0.5) * width, (u.y - 0.5) * height, 0);
Ns = real3(0, 0, -1); // Light point backward (-Z)
Ns = real3(0, 0, -1); // Light down (-Z)
// Transform to world space
P = mul(real4(P, 1.0), localToWorld).xyz;

{
// Random point at disk surface
P = real3(radius * SampleDiskUniform(u.x, u.y), 0);
Ns = real3(0.0, 0.0, -1.0); // Light point backward (-Z)
Ns = real3(0.0, 0.0, -1.0); // Light down (-Z)
// Transform to world space
P = mul(real4(P, 1.0), localToWorld).xyz;

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


return (z[1] < 0.0 || z[2] > 1.0) ? ShadowMoments_SolveDelta4MSM( z, b, lightLeakBias ) : ShadowMoments_SolveDelta3MSM( z, b.xy, lightLeakBias );
}
#include "PCSS.hlsl"
real SampleShadow_PCSS( ShadowContext shadowContext, inout uint payloadOffset, real3 tcs, real4 scaleOffset, real2 sampleBias, float slice, uint texIdx, uint sampIdx )
{
real2 params = asfloat(shadowContext.payloads[payloadOffset].xy);
real shadowSoftnesss = params.x;
int sampleCount = params.y;
payloadOffset++;
real2 sampleJitter = real2(sin(GenerateHashedRandomFloat(tcs.x)),
cos(GenerateHashedRandomFloat(tcs.y)));
//1) Blocker Search
real averageBlockerDepth = 0.0;
real numBlockers = 0.0;
if (!BlockerSearch(averageBlockerDepth, numBlockers, shadowSoftnesss + 0.000001, tcs, sampleJitter, sampleBias, shadowContext, slice, texIdx, sampIdx, sampleCount))
return 1.0;
//2) Penumbra Estimation
real filterSize = shadowSoftnesss * PenumbraSize(tcs.z, averageBlockerDepth);
filterSize = max(filterSize, 0.000001);
//3) Filter
return PCSS(tcs, filterSize, scaleOffset, slice, sampleBias, sampleJitter, shadowContext, texIdx, sampIdx, sampleCount);
}
real SampleShadow_PCSS( ShadowContext shadowContext, inout uint payloadOffset, real3 tcs, real4 scaleOffset, real2 sampleBias, float slice, Texture2DArray tex, SamplerComparisonState compSamp, SamplerState samp )
{
real2 params = asfloat(shadowContext.payloads[payloadOffset].xy);
real shadowSoftnesss = params.x;
int sampleCount = params.y;
payloadOffset++;
real2 sampleJitter = real2(sin(GenerateHashedRandomFloat(tcs.x)),
cos(GenerateHashedRandomFloat(tcs.y)));
//1) Blocker Search
real averageBlockerDepth = 0.0;
real numBlockers = 0.0;
if (!BlockerSearch(averageBlockerDepth, numBlockers, shadowSoftnesss + 0.000001, tcs, slice, sampleJitter, sampleBias, tex, samp, sampleCount))
return 1.0;
//2) Penumbra Estimation
real filterSize = shadowSoftnesss * PenumbraSize(tcs.z, averageBlockerDepth);
filterSize = max(filterSize, 0.000001);
//3) Filter
return PCSS(tcs, filterSize, scaleOffset, slice, sampleBias, sampleJitter, tex, compSamp, sampleCount);
}
//-----------------------------------------------------------------------------------------------------
// helper function to dispatch a specific shadow algorithm
real SampleShadow_SelectAlgorithm( ShadowContext shadowContext, ShadowData shadowData, inout uint payloadOffset, real3 posTC, real2 sampleBias, uint algorithm, uint texIdx, uint sampIdx )

case GPUSHADOWALGORITHM_PCF_TENT_3X3 : return SampleShadow_PCF_Tent_3x3( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCF_TENT_5X5 : return SampleShadow_PCF_Tent_5x5( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCF_TENT_7X7 : return SampleShadow_PCF_Tent_7x7( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_PCSS : return SampleShadow_PCSS( shadowContext, payloadOffset, posTC, shadowData.scaleOffset, sampleBias, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_VSM : return SampleShadow_VSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx );
case GPUSHADOWALGORITHM_EVSM_2 : return SampleShadow_EVSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx, false );
case GPUSHADOWALGORITHM_EVSM_4 : return SampleShadow_EVSM_1tap( shadowContext, payloadOffset, posTC, shadowData.slice, texIdx, sampIdx, true );

case GPUSHADOWALGORITHM_PCF_TENT_3X3 : return SampleShadow_PCF_Tent_3x3( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCF_TENT_5X5 : return SampleShadow_PCF_Tent_5x5( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCF_TENT_7X7 : return SampleShadow_PCF_Tent_7x7( shadowContext, payloadOffset, shadowData.textureSize, shadowData.texelSizeRcp, posTC, sampleBias, shadowData.slice, tex, compSamp );
case GPUSHADOWALGORITHM_PCSS : return SampleShadow_PCSS( shadowContext, payloadOffset, posTC, shadowData.scaleOffset, sampleBias, shadowData.slice, tex, compSamp, s_point_clamp_sampler );
default: return 1.0;
}

13
com.unity.render-pipelines.core/CoreRP/ShaderLibrary/UnityInstancing.hlsl


#endif
UNITY_INSTANCING_BUFFER_END(unity_Builtins2)
#define UNITY_MATRIX_M UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, unity_ObjectToWorldArray)
#ifdef MODIFY_MATRIX_FOR_CAMERA_RELATIVE_RENDERING
#define UNITY_MATRIX_M ApplyCameraTranslationToMatrix(UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, unity_ObjectToWorldArray))
#else
#define UNITY_MATRIX_M UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, unity_ObjectToWorldArray)
#endif
#define UNITY_MATRIX_I_M UNITY_ACCESS_INSTANCED_PROP(MERGE_UNITY_BUILTINS_INDEX(UNITY_WORLDTOOBJECTARRAY_CB), unity_WorldToObjectArray)
#ifdef MODIFY_MATRIX_FOR_CAMERA_RELATIVE_RENDERING
#define UNITY_MATRIX_I_M ApplyCameraTranslationToInverseMatrix(UNITY_ACCESS_INSTANCED_PROP(MERGE_UNITY_BUILTINS_INDEX(UNITY_WORLDTOOBJECTARRAY_CB), unity_WorldToObjectArray))
#else
#define UNITY_MATRIX_I_M UNITY_ACCESS_INSTANCED_PROP(MERGE_UNITY_BUILTINS_INDEX(UNITY_WORLDTOOBJECTARRAY_CB), unity_WorldToObjectArray)
#endif
#else // UNITY_INSTANCING_ENABLED

100
com.unity.render-pipelines.core/CoreRP/Shadow/Shadow.cs


readonly ValRange m_DefPCF_DepthBias = new ValRange("Depth Bias", 0.0f, 0.0f, 1.0f, 000.1f);
readonly ValRange m_DefPCF_FilterSize = new ValRange("Filter Size", 1.0f, 1.0f, 10.0f, 1.0f);
readonly ValRange m_DefPCSS_ShadowSoftness = new ValRange("Shadow Softness", 0.0f, 0.5f, 1.0f, 0.01f);
readonly ValRange m_DefPCSS_SampleCount = new ValRange("Sample Count", 1, 32, 64, 1);
public ShadowAtlas(ref AtlasInit init) : base(ref init.baseInit)
{

override protected void Register(GPUShadowType type, ShadowRegistry registry)
{
ShadowPrecision precision = m_ShadowmapBits == 32 ? ShadowPrecision.High : ShadowPrecision.Low;
m_SupportedAlgorithms.Reserve(5);
m_SupportedAlgorithms.Reserve(6);
m_SupportedAlgorithms.AddUniqueUnchecked((int)ShadowUtils.Pack(ShadowAlgorithm.PCSS, ShadowVariant.V0, precision));
ShadowRegistry.VariantDelegate del = (Light l, ShadowAlgorithm dataAlgorithm, ShadowVariant dataVariant, ShadowPrecision dataPrecision, ref int[] dataBlock) =>
{

if (dataVariant == ShadowVariant.V1)
m_DefPCF_FilterSize.Slider(ref dataBlock[1]);
};
ShadowRegistry.VariantDelegate pcssDel = (Light l, ShadowAlgorithm dataAlgorithm, ShadowVariant dataVariant, ShadowPrecision dataPrecision, ref int[] dataBlock) =>
{
CheckDataIntegrity(dataAlgorithm, dataVariant, dataPrecision, ref dataBlock);
m_DefPCSS_ShadowSoftness.Slider(ref dataBlock[0]);
m_DefPCSS_SampleCount.Slider(ref dataBlock[1]);
dataBlock[1] = ShadowUtils.Asint(Mathf.RoundToInt(ShadowUtils.Asfloat(dataBlock[1])));
};
registry.Register(type, precision, ShadowAlgorithm.PCSS, "Percentage Closer Soft Shadows (PCSS)",
new ShadowVariant[] { ShadowVariant.V0 },
new string[] { "poisson 64" },
new ShadowRegistry.VariantDelegate[] { pcssDel });
if (algorithm != ShadowAlgorithm.PCF ||
if ((algorithm != ShadowAlgorithm.PCF && algorithm != ShadowAlgorithm.PCSS) ||
(variant != ShadowVariant.V0 &&
variant != ShadowVariant.V1 &&
variant != ShadowVariant.V2 &&

const int k_BlockSize = 2;
if (dataBlock == null || dataBlock.Length != k_BlockSize)
switch (algorithm)
// set defaults
dataBlock = new int[k_BlockSize];
dataBlock[0] = m_DefPCF_DepthBias.Default();
dataBlock[1] = m_DefPCF_FilterSize.Default();
return false;
case ShadowAlgorithm.PCF:
const int k_PcfBlockSize = 2;
if (dataBlock == null || dataBlock.Length != k_PcfBlockSize)
{
// set defaults
dataBlock = new int[k_PcfBlockSize];
dataBlock[0] = m_DefPCF_DepthBias.Default();
dataBlock[1] = m_DefPCF_FilterSize.Default();
return false;
}
break;
case ShadowAlgorithm.PCSS:
const int k_PcssBlockSize = 2;
if (dataBlock == null || dataBlock.Length != k_PcssBlockSize)
{
// set defaults
dataBlock = new int[k_PcssBlockSize];
dataBlock[0] = m_DefPCSS_ShadowSoftness.Default();
dataBlock[1] = m_DefPCSS_SampleCount.Default();
return false;
}
break;
}
return true;
}

virtual protected uint ReservePayload(ShadowRequest sr)
{
uint payloadSize = sr.shadowType == GPUShadowType.Directional ? (1 + k_MaxCascadesInShader + ((uint)m_TmpBorders.Length / 4)) : 0;
payloadSize += ShadowUtils.ExtractAlgorithm(sr.shadowAlgorithm) == ShadowAlgorithm.PCF ? 1u : 0;
switch (ShadowUtils.ExtractAlgorithm(sr.shadowAlgorithm))
{
case ShadowAlgorithm.PCF:
payloadSize += 1;
break;
case ShadowAlgorithm.PCSS:
payloadSize += 1;
break;
default:
break;
}
return payloadSize;
}

}
ShadowAlgorithm algo; ShadowVariant vari; ShadowPrecision prec;
ShadowUtils.Unpack(sr.shadowAlgorithm, out algo, out vari, out prec);
if (algo == ShadowAlgorithm.PCF)
if (algo == ShadowAlgorithm.PCF || algo == ShadowAlgorithm.PCSS)
{
AdditionalShadowData asd = lights[sr.index].light.GetComponent<AdditionalShadowData>();
if (!asd)

Debug.Log("Fixed up shadow data for algorithm " + algo + ", variant " + vari);
}
switch (vari)
if (algo == ShadowAlgorithm.PCF)
case ShadowVariant.V0:
case ShadowVariant.V1:
case ShadowVariant.V2:
case ShadowVariant.V3:
case ShadowVariant.V4:
switch (vari)
sp.Set(shadowData[0] | (SystemInfo.usesReversedZBuffer ? 1 : 0), shadowData[1], 0, 0);
payload[payloadOffset] = sp;
payloadOffset++;
case ShadowVariant.V0:
case ShadowVariant.V1:
case ShadowVariant.V2:
case ShadowVariant.V3:
case ShadowVariant.V4:
{
sp.Set(shadowData[0] | (SystemInfo.usesReversedZBuffer ? 1 : 0), shadowData[1], 0, 0);
payload[payloadOffset] = sp;
payloadOffset++;
}
break;
break;
}
else if (algo == ShadowAlgorithm.PCSS)
{
sp.Set(shadowData[0], shadowData[1], 0, 0);
payload[payloadOffset] = sp;
payloadOffset++;
}
}
}

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


public class ShadowInitParameters
{
public const int kDefaultShadowAtlasSize = 4096;
public const int kDefaultMaxPointLightShadows = 6;
public const int kDefaultMaxSpotLightShadows = 12;
public const int kDefaultMaxDirectionalLightShadows = 1;
public int maxPointLightShadows = kDefaultMaxPointLightShadows;
public int maxSpotLightShadows = kDefaultMaxSpotLightShadows;
public int maxDirectionalLightShadows = kDefaultMaxDirectionalLightShadows;
}
// Class used to pass parameters to the shadow system on a per frame basis.

VSM,
EVSM,
MSM,
PCSS,
Custom = 32
};

EVSM_4 = ShadowAlgorithm.EVSM << 3 | ShadowVariant.V1,
MSM_Ham = ShadowAlgorithm.MSM << 3 | ShadowVariant.V0,
MSM_Haus = ShadowAlgorithm.MSM << 3 | ShadowVariant.V1,
PCSS = ShadowAlgorithm.PCSS << 3 | ShadowVariant.V0,
Custom = ShadowAlgorithm.Custom << 3
}

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


#define GPUSHADOWALGORITHM_EVSM_4 (17)
#define GPUSHADOWALGORITHM_MSM_HAM (24)
#define GPUSHADOWALGORITHM_MSM_HAUS (25)
#define GPUSHADOWALGORITHM_PCSS (32)
#define GPUSHADOWALGORITHM_CUSTOM (256)
// Generated from UnityEngine.Experimental.Rendering.ShadowData

7
com.unity.render-pipelines.high-definition/CHANGELOG.md


- Added a temporary workaround to Lit.hlsl to avoid broken lighting code with Metal/AMD
- Fixed compilation errors on Nintendo Switch (limited XRSetting support).
- Fixed apply range attenuation option on punctual light
- Fixed issue when using more than one volume mask texture with density volumes.
- Fixed an error which prevented volumetric lighting from working if no density volumes with 3D textures were present.
- Add PCSS shadow filter support (from SRP Core)
- Exposed shadow budget parameters in HDRP asset
- Change code in area light with LTC for Lit shader. Magnitude is now take from FGD texture instead of a separate texture
- Improve camera relative rendering: We now apply camera translation on the model matrix, so before the TransformObjectToWorld(). Note: unity_WorldToObject and unity_ObjectToWorld must never be used directly.
- Rename positionWS to positionRWS (Camera relative world position) at a lot of places (mainly in interpolator and FragInputs). In case of custom shader user will be required to update their code.
### Fixed
- Fix contact shadows applied on transmission

1
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/Lit/LitUI.cs


public static GUIContent baseColorText = new GUIContent("Base Color + Opacity", "Albedo (RGB) and Opacity (A)");
public static GUIContent smoothnessMapChannelText = new GUIContent("Smoothness Source", "Smoothness texture and channel");
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");

4
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/StackLit/BaseMaterialUI.cs


m_ChannelProperty = new ComboProperty(parent, propertyName + "Channel", "Channel", Enum.GetNames(typeof(Channel)), false);
m_RemapProperty = new Property(parent, constantPropertyName + "Remap", "Remapping", "Defines the range to remap/scale the values in texture", false);
m_InvertRemapProperty = new Property(parent, constantPropertyName + "RemapInverted", "Invert Remapping", "Whether the mapping values are inverted.", false);
m_RemapProperty = new Property(parent, propertyName + "Remap", "Remapping", "Defines the range to remap/scale the values in texture", false);
m_InvertRemapProperty = new Property(parent, propertyName + "RemapInverted", "Invert Remapping", "Whether the mapping values are inverted.", false);
}
public override void OnFindProperty(MaterialProperty[] props)

127
com.unity.render-pipelines.high-definition/HDRP/Editor/Material/StackLit/StackLitUI.cs


protected const string k_IridescenceThickness = "_IridescenceThickness";
protected const string k_IridescenceThicknessMap = "_IridescenceThicknessMap";
protected const string k_IridescenceThicknessMapUV = "_IridescenceThicknessMapUV";
protected const string k_IridescenceMask = "_IridescenceMask";
protected const string k_IridescenceMaskMap = "_IridescenceMaskMap";
protected const string k_IridescenceMaskMapUV = "_IridescenceMaskMapUV";
// Details
protected const string k_EnableDetails = "_EnableDetails";
protected const string k_DetailMask = "_DetailMask";
protected const string k_DetailMaskMap = "_DetailMaskMap";
protected const string k_DetailMaskMapUV = "_DetailMaskMapUV";
protected const string k_DetailSmoothness = "_DetailSmoothness";
protected const string k_DetailSmoothnessScale = "_DetailSmoothnessScale";
protected const string k_DetailSmoothnessMap = "_DetailSmoothnessMap";
protected const string k_DetailSmoothnessMapUV = "_DetailSmoothnessMapUV";
protected const string k_DetailNormalMap = "_DetailNormalMap";
protected const string k_DetailNormalMapUV = "_DetailNormalMapUV";
protected const string k_DetailNormalScale = "_DetailNormalScale";
// Stencil is use to control lighting mode (regular, split lighting)
protected const string kStencilRef = "_StencilRef";

private readonly GroupProperty _baseMaterialProperties = null;
private readonly GroupProperty _materialProperties = null;
private Property EnableDetails;
private Property EnableDualSpecularLobe;
private Property EnableDualSpecularLobe;
private Property EnableIridescence;
private Property EnableGeometricNormalFiltering;

});
//
EnableDetails = new Property(this, k_EnableDetails, "Enable Details", "Enable Detail", true);
EnableSSS = new Property(this, k_EnableSubsurfaceScattering, "Enable Subsurface Scattering", "Enable Subsurface Scattering", true);
EnableTransmission = new Property(this, k_EnableTransmission, "Enable Transmission", "Enable Transmission", true);
EnableCoat = new Property(this, k_EnableCoat, "Enable Coat", "Enable coat layer with true vertical physically based BSDF mixing", true);

{
new GroupProperty(this, "_MaterialFeatures", "Material Features", new BaseProperty[]
{
EnableDetails,
EnableDualSpecularLobe,
EnableAnisotropy,
EnableCoat,

new TextureProperty(this, k_AmbientOcclusionMap, k_AmbientOcclusion, "AmbientOcclusion", "AmbientOcclusion Map", false, false),
}),
new GroupProperty(this, "_Details", "Details", new BaseProperty[]
{
new TextureProperty(this, k_DetailMaskMap, "", "Detail Mask Map", "Detail Mask Map", false, false),
new TextureProperty(this, k_DetailNormalMap, k_DetailNormalScale, "Detail Normal Map", "Detail Normal Map Scale", true, false, true),
new TextureProperty(this, k_DetailSmoothnessMap, k_DetailSmoothnessScale, "Detail Smoothness", "Detail Smoothness", true, false),
}, _ => EnableDetails.BoolValue == true),
new GroupProperty(this, "_DualSpecularLobe", "Dual Specular Lobe", new BaseProperty[]
{
new TextureProperty(this, k_SmoothnessBMap, k_SmoothnessB, "Smoothness B", "Smoothness B", false, false),

new GroupProperty(this, "_Iridescence", "Iridescence", new BaseProperty[]
{
new Property(this, "_IridescenceIor", "IOR", "Index of refraction of iridescence layer", false),
new Property(this, "_IridescenceThickness", "Thickness", "Iridescence thickness (Remap to 0..3000nm)", false),
//just to test: to use the same EvalIridescence as lit, find a good mapping for the top IOR (over the iridescence dielectric film)
//when having iridescence:
//new Property(this, "_IridescenceIor", "TopIOR", "Index of refraction on top of iridescence layer", false),
new TextureProperty(this, k_IridescenceMaskMap, k_IridescenceMask, "Iridescence Mask", "Iridescence Mask", false),
new TextureProperty(this, k_IridescenceThicknessMap, k_IridescenceThickness, "Iridescence thickness (Remap to 0..3000nm)", "Iridescence thickness (Remap to 0..3000nm)", false),
}, _ => EnableIridescence.BoolValue == true),
new GroupProperty(this, "_SSS", "Sub-Surface Scattering", new BaseProperty[]

// TODO: Caution this can generate a lot of garbage collection call ?
string useMapPropertyName = basePropertyName + "UseMap";
string mapPropertyName = basePropertyName + "Map";
string remapPropertyName = basePropertyName + "Remap";
string invertPropertyName = basePropertyName + "RemapInverted";
string rangePropertyName = basePropertyName + "Range";
string remapPropertyName = basePropertyName + "MapRemap";
string invertPropertyName = basePropertyName + "MapRemapInverted";
string rangePropertyName = basePropertyName + "MapRange";
Vector4 rangeVector = material.GetVector(remapPropertyName);
if (material.HasProperty(invertPropertyName) && material.GetFloat(invertPropertyName) > 0.0f)
if (material.HasProperty(remapPropertyName) && material.HasProperty(rangePropertyName))
float s = rangeVector.x;
rangeVector.x = rangeVector.y;
rangeVector.y = s;
Vector4 rangeVector = material.GetVector(remapPropertyName);
if (material.HasProperty(invertPropertyName) && material.GetFloat(invertPropertyName) > 0.0f)
{
float s = rangeVector.x;
rangeVector.x = rangeVector.y;
rangeVector.y = s;
}
material.SetVector(rangePropertyName, rangeVector);
material.SetFloat(useMapPropertyName, 1.0f);
material.SetVector(rangePropertyName, rangeVector);
if (material.HasProperty(useMapPropertyName))
{
material.SetFloat(useMapPropertyName, 1.0f);
}
int channel = (int)material.GetFloat(channelPropertyName);
switch (channel)
if (material.HasProperty(channelPropertyName))
case 0:
material.SetVector(channelMaskPropertyName, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
break;
case 1:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
break;
case 2:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 0.0f, 1.0f, 0.0f));
break;
case 3:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
break;
int channel = (int)material.GetFloat(channelPropertyName);
switch (channel)
{
case 0:
material.SetVector(channelMaskPropertyName, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
break;
case 1:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
break;
case 2:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 0.0f, 1.0f, 0.0f));
break;
case 3:
material.SetVector(channelMaskPropertyName, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
break;
}
material.SetFloat(useMapPropertyName, 0.0f);
material.SetVector(rangePropertyName, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
material.SetVector(channelMaskPropertyName, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
if (material.HasProperty(useMapPropertyName))
{
material.SetFloat(useMapPropertyName, 0.0f);
}
if (material.HasProperty(rangePropertyName))
{
material.SetVector(rangePropertyName, new Vector4(0.0f, 1.0f, 0.0f, 0.0f));
}
if (material.HasProperty(channelPropertyName))
{
material.SetVector(channelMaskPropertyName, new Vector4(1.0f, 0.0f, 0.0f, 0.0f));
}
}
}

//TODO see BaseLitUI.cs:SetupBaseLitKeywords (stencil etc)
SetupBaseUnlitKeywords(material);
SetupBaseUnlitMaterialPass(material);

}
}
//TODO: stencil state, displacement, wind, depthoffset, tessellation
SetupMainTexForAlphaTestGI("_BaseColorMap", "_BaseColor", material);
//TODO: disable DBUFFER

SetupTextureMaterialProperty(material, k_Thickness);
SetupTextureMaterialProperty(material, k_Anisotropy);
SetupTextureMaterialProperty(material, k_IridescenceThickness);
SetupTextureMaterialProperty(material, k_IridescenceMask);
// details
SetupTextureMaterialProperty(material, k_DetailMask);
SetupTextureMaterialProperty(material, k_DetailSmoothness);
// Check if we are using specific UVs.
TextureProperty.UVMapping[] uvIndices = new[]
{

(TextureProperty.UVMapping)material.GetFloat(k_ThicknessMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_AnisotropyMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_IridescenceThicknessMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_IridescenceMaskMapUV),
// Details
(TextureProperty.UVMapping)material.GetFloat(k_DetailMaskMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_DetailSmoothnessMapUV),
(TextureProperty.UVMapping)material.GetFloat(k_DetailNormalMapUV),
};
// Set keyword for mapping

requireTriplanar = requireTriplanar || uvIndices[i] == TextureProperty.UVMapping.Triplanar;
}
CoreUtils.SetKeyword(material, "_USE_TRIPLANAR", requireTriplanar);
bool detailsEnabled = material.HasProperty(k_EnableDetails) && material.GetFloat(k_EnableDetails) > 0.0f;
CoreUtils.SetKeyword(material, "_USE_DETAILMAP", detailsEnabled);
bool dualSpecularLobeEnabled = material.HasProperty(k_EnableDualSpecularLobe) && material.GetFloat(k_EnableDualSpecularLobe) > 0.0f;
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_DUAL_SPECULAR_LOBE", dualSpecularLobeEnabled);

5
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/RenderPipelineSettingsUI.cs


EditorGUILayout.PropertyField(d.supportSSR, _.GetContent("Support SSR|Enable memory use by SSR effect."));
EditorGUILayout.PropertyField(d.supportSSAO, _.GetContent("Support SSAO|Enable memory use by SSAO effect."));
EditorGUILayout.PropertyField(d.supportDBuffer, _.GetContent("Support Decal Buffer|Enable memory and variant of decal buffer."));
EditorGUILayout.PropertyField(d.supportMSAA, _.GetContent("Support Multi Sampling Anti-Aliasing|This feature doesn't work currently."));
EditorGUILayout.PropertyField(d.MSAASampleCount, _.GetContent("MSAA Sample Count|Allow to select the level of MSAA."));
// TODO: Implement MSAA - Hide for now as it doesn't work
//EditorGUILayout.PropertyField(d.supportMSAA, _.GetContent("Support Multi Sampling Anti-Aliasing|This feature doesn't work currently."));
//EditorGUILayout.PropertyField(d.MSAASampleCount, _.GetContent("MSAA Sample Count|Allow to select the level of MSAA."));
EditorGUILayout.PropertyField(d.supportSubsurfaceScattering, _.GetContent("Support Subsurface Scattering"));
EditorGUILayout.PropertyField(d.supportOnlyForward, _.GetContent("Support Only Forward|Remove all the memory and shader variant of GBuffer. The renderer can be switch to deferred anymore."));
EditorGUILayout.PropertyField(d.supportMotionVectors, _.GetContent("Support Motion Vectors|Motion vector are use for Motion Blur, TAA, temporal re-projection of various effect like SSR."));

7
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/SerializedShadowInitParameters.cs


public SerializedProperty shadowAtlasWidth;
public SerializedProperty shadowAtlasHeight;
public SerializedProperty maxPointLightShadows;
public SerializedProperty maxSpotLightShadows;
public SerializedProperty maxDirectionalLightShadows;
public SerializedShadowInitParameters(SerializedProperty root)
{
this.root = root;

maxPointLightShadows = root.Find((ShadowInitParameters s) => s.maxPointLightShadows);
maxSpotLightShadows = root.Find((ShadowInitParameters s) => s.maxSpotLightShadows);
maxDirectionalLightShadows = root.Find((ShadowInitParameters s) => s.maxDirectionalLightShadows);
}
}
}

24
com.unity.render-pipelines.high-definition/HDRP/Editor/RenderPipeline/Settings/ShadowInitParametersUI.cs


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

static void Drawer_FieldShadowSize(ShadowInitParametersUI s, SerializedShadowInitParameters d, Editor o)
{
EditorGUILayout.LabelField(_.GetContent("Shadow Atlas Settings"), EditorStyles.boldLabel);
EditorGUILayout.LabelField(_.GetContent("Shadow"), EditorStyles.boldLabel);
++EditorGUI.indentLevel;
EditorGUILayout.LabelField(_.GetContent("Shadow Atlas"), EditorStyles.boldLabel);
--EditorGUI.indentLevel;
EditorGUILayout.Space();
EditorGUILayout.LabelField(_.GetContent("Shadow Map Budget"), EditorStyles.boldLabel);
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(d.maxPointLightShadows, _.GetContent("Max Point Light Shadows"));
EditorGUILayout.PropertyField(d.maxSpotLightShadows, _.GetContent("Max Spot Light Shadows"));
EditorGUILayout.PropertyField(d.maxDirectionalLightShadows, _.GetContent("Max Directional Light Shadows"));
--EditorGUI.indentLevel;
// Clamp negative values
d.shadowAtlasHeight.intValue = Mathf.Max(0, d.shadowAtlasHeight.intValue);
d.shadowAtlasWidth.intValue = Mathf.Max(0, d.shadowAtlasWidth.intValue);
d.maxPointLightShadows.intValue = Mathf.Max(0, d.maxPointLightShadows.intValue);
d.maxSpotLightShadows.intValue = Mathf.Max(0, d.maxSpotLightShadows.intValue);
d.maxDirectionalLightShadows.intValue = Mathf.Max(0, d.maxDirectionalLightShadows.intValue);
--EditorGUI.indentLevel;
}
}

36
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDPBRPass.template


$AttributesMesh.uv2: #define ATTRIBUTES_NEED_TEXCOORD2
$AttributesMesh.uv3: #define ATTRIBUTES_NEED_TEXCOORD3
$AttributesMesh.color: #define ATTRIBUTES_NEED_COLOR
$VaryingsMeshToPS.positionWS: #define VARYINGS_NEED_POSITION_WS
$VaryingsMeshToPS.positionRWS: #define VARYINGS_NEED_POSITION_WS
$VaryingsMeshToPS.normalWS: #define VARYINGS_NEED_TANGENT_TO_WORLD
$VaryingsMeshToPS.texCoord0: #define VARYINGS_NEED_TEXCOORD0
$VaryingsMeshToPS.texCoord1: #define VARYINGS_NEED_TEXCOORD1

$VertexDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = TransformWorldToViewDir(output.WorldSpaceBiTangent);
$VertexDescriptionInputs.TangentSpaceBiTangent: output.TangentSpaceBiTangent = float3(0.0f, 1.0f, 0.0f);
$VertexDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = input.positionOS;
$VertexDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = TransformObjectToWorld(input.positionOS);
$VertexDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = GetAbsolutePositionWS(TransformObjectToWorld(input.positionOS));
$VertexDescriptionInputs.ViewSpacePosition: output.ViewSpacePosition = TransformWorldToView(output.WorldSpacePosition);
$VertexDescriptionInputs.TangentSpacePosition: output.TangentSpacePosition = float3(0.0f, 0.0f, 0.0f);
$VertexDescriptionInputs.WorldSpaceViewDirection: output.WorldSpaceViewDirection = GetWorldSpaceNormalizeViewDir(output.WorldSpacePosition);

output.worldToTangent = k_identity3x3;
output.positionSS = input.positionCS; // input.positionCS is SV_Position
$FragInputs.positionWS: output.positionWS = input.positionWS;
$FragInputs.positionRWS: output.positionRWS = input.positionRWS;
$FragInputs.worldToTangent: output.worldToTangent = BuildWorldToTangent(input.tangentWS, input.normalWS);
$FragInputs.texCoord0: output.texCoord0 = input.texCoord0;
$FragInputs.texCoord1: output.texCoord1 = input.texCoord1;

$SurfaceDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_I_V); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
$SurfaceDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = input.worldToTangent[0].xyz;
$SurfaceDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = mul((float3x3) unity_WorldToObject, output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = mul((float3x3) UNITY_MATRIX_V, output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = TransformWorldToObjectDir(output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = TransformWorldToViewDir(output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = mul((float3x3) unity_WorldToObject, output.WorldSpaceBiTangent);
$SurfaceDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = mul((float3x3) UNITY_MATRIX_V, output.WorldSpaceBiTangent);
$SurfaceDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = TransformWorldToObjectDir(output.WorldSpaceBiTangent);
$SurfaceDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = TransformWorldToViewDir(output.WorldSpaceBiTangent);
$SurfaceDescriptionInputs.ObjectSpaceViewDirection: output.ObjectSpaceViewDirection = mul((float3x3) unity_WorldToObject, output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.ViewSpaceViewDirection: output.ViewSpaceViewDirection = mul((float3x3) UNITY_MATRIX_V, output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.ObjectSpaceViewDirection: output.ObjectSpaceViewDirection = TransformWorldToObjectDir(output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.ViewSpaceViewDirection: output.ViewSpaceViewDirection = TransformWorldToViewDir(output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.WorldSpacePosition: // TODO: FragInputs.positionWS is badly named -- it's camera relative, not in world space
$SurfaceDescriptionInputs.WorldSpacePosition: // we have to fix it up here to match graph input expectations
$SurfaceDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = input.positionWS + _WorldSpaceCameraPos;
$SurfaceDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = mul(unity_WorldToObject, float4(input.positionWS + _WorldSpaceCameraPos, 1.0f)).xyz;
$SurfaceDescriptionInputs.ViewSpacePosition: float4 posViewSpace = mul(UNITY_MATRIX_V, float4(input.positionWS, 1.0f));
$SurfaceDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = GetAbsolutePositionWS(input.positionRWS);
$SurfaceDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = TransformWorldToObject(input.positionRWS);
$SurfaceDescriptionInputs.ViewSpacePosition: float4 posViewSpace = TransformWorldToView(input.positionRWS);
$SurfaceDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(input.positionWS), _ProjectionParams.x);
$SurfaceDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(input.positionRWS), _ProjectionParams.x);
$SurfaceDescriptionInputs.VertexColor: output.VertexColor = input.color;
$SurfaceDescriptionInputs.FaceSign: output.FaceSign = input.isFrontFace;

float3 bentNormalWS = surfaceData.normalWS; // TODO : make bent normals work
builtinData.opacity = surfaceDescription.Alpha;
builtinData.bakeDiffuseLighting = SampleBakedGI(fragInputs.positionWS, bentNormalWS, fragInputs.texCoord1, fragInputs.texCoord2); // see GetBuiltinData()
builtinData.bakeDiffuseLighting = SampleBakedGI(fragInputs.positionRWS, bentNormalWS, fragInputs.texCoord1, fragInputs.texCoord2); // see GetBuiltinData()
// It is safe to call this function here as surfaceData have been filled
// We want to know if we must enable transmission on GI for SSS material, if the material have no SSS, this code will be remove by the compiler.

// however it will not optimize the lightprobe case due to the proxy volume relying on dynamic if (we rely must get right of this dynamic if), not a problem for SH9, but a problem for proxy volume.
// TODO: optimize more this code.
// Add GI transmission contribution by resampling the GI for inverted vertex normal
builtinData.bakeDiffuseLighting += SampleBakedGI(fragInputs.positionWS, -fragInputs.worldToTangent[2], fragInputs.texCoord1, fragInputs.texCoord2) * bsdfData.transmittance;
builtinData.bakeDiffuseLighting += SampleBakedGI(fragInputs.positionRWS, -fragInputs.worldToTangent[2], fragInputs.texCoord1, fragInputs.texCoord2) * bsdfData.transmittance;
float4 shadowMask = SampleShadowMask(fragInputs.positionWS, fragInputs.texCoord1);
float4 shadowMask = SampleShadowMask(fragInputs.positionRWS, fragInputs.texCoord1);
builtinData.shadowMask0 = shadowMask.x;
builtinData.shadowMask1 = shadowMask.y;
builtinData.shadowMask2 = shadowMask.z;

29
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDPBRSubShader.cs


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

RequiredFields = new List<string>()
{
"FragInputs.worldToTangent",
"FragInputs.positionWS",
"FragInputs.positionRWS",
"FragInputs.texCoord1",
"FragInputs.texCoord2"
},

RequiredFields = new List<string>()
{
// "FragInputs.worldToTangent",
// "FragInputs.positionWS",
// "FragInputs.positionRWS",
},
PixelShaderSlots = new List<int>()
{

RequiredFields = new List<string>()
{
// "FragInputs.worldToTangent",
// "FragInputs.positionWS",
// "FragInputs.positionRWS",
},
PixelShaderSlots = new List<int>()
{

RequiredFields = new List<string>()
{
// "FragInputs.worldToTangent",
// "FragInputs.positionWS",
// "FragInputs.positionRWS",
},
PixelShaderSlots = new List<int>()
{

},
RequiredFields = new List<string>()
{
"FragInputs.positionWS",
"FragInputs.positionRWS",
},
StencilOverride = new List<string>()
{

RequiredFields = new List<string>()
{
// "FragInputs.worldToTangent",
// "FragInputs.positionWS",
// "FragInputs.positionRWS",
},
PixelShaderSlots = new List<int>()
{

RequiredFields = new List<string>()
{
// "FragInputs.worldToTangent",
// "FragInputs.positionWS",
// "FragInputs.positionRWS",
},
PixelShaderSlots = new List<int>()
{

RequiredFields = new List<string>()
{
// "FragInputs.worldToTangent",
// "FragInputs.positionWS",
// "FragInputs.positionRWS",
},
PixelShaderSlots = new List<int>()
{

RequiredFields = new List<string>()
{
"FragInputs.worldToTangent",
// "FragInputs.positionWS",
// "FragInputs.positionRWS",
},
PixelShaderSlots = new List<int>()
{

RequiredFields = new List<string>()
{
// "FragInputs.worldToTangent",
// "FragInputs.positionWS",
// "FragInputs.positionRWS",
},
PixelShaderSlots = new List<int>()
{

subShader.AddShaderChunk("}", true);
return subShader.GetShaderString(0);
}
public bool IsPipelineCompatible(RenderPipelineAsset renderPipelineAsset)
{
return renderPipelineAsset is HDRenderPipelineAsset;
}
}
}

18
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDSubShaderUtilities.cs


struct VaryingsMeshToPS
{
[Semantic("SV_Position")] Vector4 positionCS;
[Optional] Vector3 positionWS;
[Optional] Vector3 positionRWS;
[Optional] Vector3 normalWS;
[Optional] Vector4 tangentWS; // w contain mirror sign
[Optional] Vector2 texCoord0;

public static Dependency[] tessellationDependencies = new Dependency[]
{
new Dependency("VaryingsMeshToPS.positionWS", "VaryingsMeshToDS.positionWS"),
new Dependency("VaryingsMeshToPS.positionRWS", "VaryingsMeshToDS.positionRWS"),
new Dependency("VaryingsMeshToPS.normalWS", "VaryingsMeshToDS.normalWS"),
new Dependency("VaryingsMeshToPS.tangentWS", "VaryingsMeshToDS.tangentWS"),
new Dependency("VaryingsMeshToPS.texCoord0", "VaryingsMeshToDS.texCoord0"),

public static Dependency[] standardDependencies = new Dependency[]
{
new Dependency("VaryingsMeshToPS.positionWS", "AttributesMesh.positionOS"),
new Dependency("VaryingsMeshToPS.positionRWS", "AttributesMesh.positionOS"),
new Dependency("VaryingsMeshToPS.normalWS", "AttributesMesh.normalOS"),
new Dependency("VaryingsMeshToPS.tangentWS", "AttributesMesh.tangentOS"),
new Dependency("VaryingsMeshToPS.texCoord0", "AttributesMesh.uv0"),

struct VaryingsMeshToDS
{
Vector3 positionWS;
Vector3 positionRWS;
Vector3 normalWS;
[Optional] Vector4 tangentWS;
[Optional] Vector2 texCoord0;

{
public static Dependency[] dependencies = new Dependency[]
{
new Dependency("FragInputs.positionWS", "VaryingsMeshToPS.positionWS"),
new Dependency("FragInputs.positionRWS", "VaryingsMeshToPS.positionRWS"),
new Dependency("FragInputs.worldToTangent", "VaryingsMeshToPS.tangentWS"),
new Dependency("FragInputs.worldToTangent", "VaryingsMeshToPS.normalWS"),
new Dependency("FragInputs.texCoord0", "VaryingsMeshToPS.texCoord0"),

new Dependency("SurfaceDescriptionInputs.ObjectSpaceBiTangent", "SurfaceDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("SurfaceDescriptionInputs.ViewSpaceBiTangent", "SurfaceDescriptionInputs.WorldSpaceBiTangent"),
new Dependency("SurfaceDescriptionInputs.WorldSpacePosition", "FragInputs.positionWS"),
new Dependency("SurfaceDescriptionInputs.ObjectSpacePosition", "FragInputs.positionWS"),
new Dependency("SurfaceDescriptionInputs.ViewSpacePosition", "FragInputs.positionWS"),
new Dependency("SurfaceDescriptionInputs.WorldSpacePosition", "FragInputs.positionRWS"),
new Dependency("SurfaceDescriptionInputs.ObjectSpacePosition", "FragInputs.positionRWS"),
new Dependency("SurfaceDescriptionInputs.ViewSpacePosition", "FragInputs.positionRWS"),
new Dependency("SurfaceDescriptionInputs.WorldSpaceViewDirection", "FragInputs.positionWS"), // we build WorldSpaceViewDirection using FragInputs.positionWS in GetWorldSpaceNormalizeViewDir()
new Dependency("SurfaceDescriptionInputs.WorldSpaceViewDirection", "FragInputs.positionRWS"), // we build WorldSpaceViewDirection using FragInputs.positionRWS in GetWorldSpaceNormalizeViewDir()
new Dependency("SurfaceDescriptionInputs.ObjectSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("SurfaceDescriptionInputs.ViewSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceViewDirection"),
new Dependency("SurfaceDescriptionInputs.TangentSpaceViewDirection", "SurfaceDescriptionInputs.WorldSpaceViewDirection"),

32
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDUnlitPassForward.template


$AttributesMesh.uv2: #define ATTRIBUTES_NEED_TEXCOORD2
$AttributesMesh.uv3: #define ATTRIBUTES_NEED_TEXCOORD3
$AttributesMesh.color: #define ATTRIBUTES_NEED_COLOR
$VaryingsMeshToPS.positionWS: #define VARYINGS_NEED_POSITION_WS
$VaryingsMeshToPS.positionRWS: #define VARYINGS_NEED_POSITION_WS
$VaryingsMeshToPS.normalWS: #define VARYINGS_NEED_TANGENT_TO_WORLD
$VaryingsMeshToPS.texCoord0: #define VARYINGS_NEED_TEXCOORD0
$VaryingsMeshToPS.texCoord1: #define VARYINGS_NEED_TEXCOORD1

$VertexDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = TransformWorldToViewDir(output.WorldSpaceBiTangent);
$VertexDescriptionInputs.TangentSpaceBiTangent: output.TangentSpaceBiTangent = float3(0.0f, 1.0f, 0.0f);
$VertexDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = input.positionOS;
$VertexDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = TransformObjectToWorld(input.positionOS);
$VertexDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = GetAbsolutePositionWS(TransformObjectToWorld(input.positionOS));
$VertexDescriptionInputs.ViewSpacePosition: output.ViewSpacePosition = TransformWorldToView(output.WorldSpacePosition);
$VertexDescriptionInputs.TangentSpacePosition: output.TangentSpacePosition = float3(0.0f, 0.0f, 0.0f);
$VertexDescriptionInputs.WorldSpaceViewDirection: output.WorldSpaceViewDirection = GetWorldSpaceNormalizeViewDir(output.WorldSpacePosition);

output.worldToTangent = k_identity3x3;
output.positionSS = input.positionCS; // input.positionCS is SV_Position
$FragInputs.positionWS: output.positionWS = input.positionWS;
$FragInputs.positionRWS: output.positionRWS = input.positionRWS;
$FragInputs.worldToTangent: output.worldToTangent = BuildWorldToTangent(input.tangentWS, input.normalWS);
$FragInputs.texCoord0: output.texCoord0 = input.texCoord0;
$FragInputs.texCoord1: output.texCoord1 = input.texCoord1;

$SurfaceDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_I_V); // transposed multiplication by inverse matrix to handle normal scale
$SurfaceDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
$SurfaceDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = input.worldToTangent[0].xyz;
$SurfaceDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = mul((float3x3) unity_WorldToObject, output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = mul((float3x3) UNITY_MATRIX_V, output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = TransformWorldToObjectDir(output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = TransformWorldToViewDir(output.WorldSpaceTangent);
$SurfaceDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = mul((float3x3) unity_WorldToObject, output.WorldSpaceBiTangent);
$SurfaceDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = mul((float3x3) UNITY_MATRIX_V, output.WorldSpaceBiTangent);
$SurfaceDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = TransformWorldToObjectDir(output.WorldSpaceBiTangent);
$SurfaceDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = TransformWorldToViewDir(output.WorldSpaceBiTangent);
$SurfaceDescriptionInputs.ObjectSpaceViewDirection: output.ObjectSpaceViewDirection = mul((float3x3) unity_WorldToObject, output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.ViewSpaceViewDirection: output.ViewSpaceViewDirection = mul((float3x3) UNITY_MATRIX_V, output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.ObjectSpaceViewDirection: output.ObjectSpaceViewDirection = TransformWorldToObjectDir(output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.ViewSpaceViewDirection: output.ViewSpaceViewDirection = TransformWorldToViewDir(output.WorldSpaceViewDirection);
$SurfaceDescriptionInputs.WorldSpacePosition: // TODO: FragInputs.positionWS is badly named -- it's camera relative, not in world space
$SurfaceDescriptionInputs.WorldSpacePosition: // we have to fix it up here to match graph input expectations
$SurfaceDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = input.positionWS + _WorldSpaceCameraPos;
$SurfaceDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = mul(unity_WorldToObject, float4(input.positionWS + _WorldSpaceCameraPos, 1.0f)).xyz;
$SurfaceDescriptionInputs.ViewSpacePosition: float4 posViewSpace = mul(UNITY_MATRIX_V, float4(input.positionWS, 1.0f));
$SurfaceDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = GetAbsolutePositionWS(input.positionRWS);
$SurfaceDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = TransformWorldToObject(input.positionRWS);
$SurfaceDescriptionInputs.ViewSpacePosition: float4 posViewSpace = TransformWorldToView(input.positionRWS);
$SurfaceDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(input.positionWS), _ProjectionParams.x);
$SurfaceDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(input.positionRWS), _ProjectionParams.x);
$SurfaceDescriptionInputs.VertexColor: output.VertexColor = input.color;
$SurfaceDescriptionInputs.FaceSign: output.FaceSign = input.isFrontFace;

9
com.unity.render-pipelines.high-definition/HDRP/Editor/ShaderGraph/HDUnlitSubShader.cs


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

subShader.AddShaderChunk("}", true);
return subShader.GetShaderString(0);
}
public bool IsPipelineCompatible(RenderPipelineAsset renderPipelineAsset)
{
return renderPipelineAsset is HDRenderPipelineAsset;
}
}
}

4
com.unity.render-pipelines.high-definition/HDRP/HDRenderPipelineAsset.asset


enableUltraQualitySSS: 0
supportVolumetric: 1
supportRuntimeDebugDisplay: 1
supportDitheringCrossFade: 1
supportDBuffer: 1
supportMSAA: 0
msaaSampleCount: 1

shadowInitParams:
shadowAtlasWidth: 4096
shadowAtlasHeight: 4096
maxPointLightShadows: 6
maxSpotLightShadows: 12
maxDirectionalLightShadows: 1
decalSettings:
drawDistance: 1000
atlasWidth: 4096

25
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightEvaluation.hlsl


// Punctual Light evaluation helper
//-----------------------------------------------------------------------------
// Return L vector for punctual light (normalize surface to light), lightToSample (light to surface non normalize) and distances {d, d^2, 1/d, d_proj}
void GetPunctualLightVectors(float3 positionWS, LightData lightData, out float3 L, out float3 lightToSample, out float4 distances)
{
lightToSample = positionWS - lightData.positionWS;
int lightType = lightData.lightType;
distances.w = dot(lightToSample, lightData.forward);
if (lightType == GPULIGHTTYPE_PROJECTOR_BOX)
{
L = -lightData.forward;
distances.xyz = 1; // No distance or angle attenuation
}
else
{
float3 unL = -lightToSample;
float distSq = dot(unL, unL);
float distRcp = rsqrt(distSq);
float dist = distSq * distRcp;
L = unL * distRcp;
distances.xyz = float3(dist, distSq, distRcp);
}
}
float4 EvaluateCookie_Punctual(LightLoopContext lightLoopContext, LightData lightData,
float3 lightToSample)
{

8
com.unity.render-pipelines.high-definition/HDRP/Lighting/LightLoop/LightLoop.cs


scInit.resourceBinder = binder;
ShadowManager.ShadowBudgets budgets;
budgets.maxPointLights = 6;
budgets.maxSpotLights = 12;
budgets.maxDirectionalLights = 1;
budgets.maxPointLights = shadowInit.maxPointLightShadows;
budgets.maxSpotLights = shadowInit.maxSpotLightShadows;
budgets.maxDirectionalLights = shadowInit.maxDirectionalLightShadows;
m_ShadowMgr = new ShadowManager(shadowSettings, ref scInit, ref budgets, m_Shadowmaps);
// set global overrides - these need to match the override specified in LightLoop/Shadow.hlsl

lightData.color = GetLightColor(light);
lightData.forward = light.light.transform.forward; // Note: Light direction is oriented backward (-Z)
lightData.forward = light.light.transform.forward;
lightData.up = light.light.transform.up;
lightData.right = light.light.transform.right;

2
com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumeTextureAtlas.cs


{
if (textures.Contains(volumeTexture))
{
textures.Add(volumeTexture);
textures.Remove(volumeTexture);
needTextureUpdate = true;
}

2
com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumeVoxelization.compute


// Express the voxel center in the local coordinate system of the box.
float3 voxelCenterBS = mul(voxelCenterWS - obb.center, transpose(obbFrame));
float3 voxelCenterUV = (voxelCenterBS / obbExtents) * 0.5 + 0.5;
float3 voxelCenterUV = (voxelCenterBS / obbExtents);
#if SOFT_VOXELIZATION
// We need to determine which is the face closest to 'voxelCenterBS'.

6
com.unity.render-pipelines.high-definition/HDRP/Lighting/Volumetrics/VolumetricLighting.cs


if (volumeAtlas != null)
{
volumeAtlasDimensions.x = volumeAtlas.width / volumeAtlas.depth; // 1 / number of textures
volumeAtlasDimensions.x = (float)volumeAtlas.width / volumeAtlas.depth; // 1 / number of textures
}
else
{
volumeAtlas = CoreUtils.blackVolumeTexture;
}
cmd.SetComputeTextureParam(m_VolumeVoxelizationCS, kernel, HDShaderIDs._VBufferDensity, m_DensityBufferHandle);

15
com.unity.render-pipelines.high-definition/HDRP/Material/Decal/DecalUtilities.hlsl


decalStart = 0;
#endif
float3 positionWS = GetAbsolutePositionWS(posInput.positionWS);
float3 positionRWS = posInput.positionWS;
float3 positionWSDdx = ddx(positionWS);
float3 positionWSDdy = ddy(positionWS);
float3 positionRWSDdx = ddx(positionRWS);
float3 positionRWSDdy = ddy(positionRWS);
float3 positionDS = mul(decalData.worldToDecal, float4(positionWS, 1.0)).xyz;
// Get the relative world camera to decal matrix
float4x4 worldToDecal = ApplyCameraTranslationToInverseMatrix(decalData.worldToDecal);
float3 positionDS = mul(worldToDecal, float4(positionRWS, 1.0)).xyz;
positionDS = positionDS * float3(1.0, -1.0, 1.0) + float3(0.5, 0.0f, 0.5); // decal clip space
if ((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f)))
{

float2 sampleMask = clamp(positionDS.xz * decalData.maskScaleBias.xy + decalData.maskScaleBias.zw, maskMin, maskMax);
// need to compute the mipmap LOD manually because we are sampling inside a loop
float3 positionDSDdx = mul(decalData.worldToDecal, float4(positionWSDdx, 0.0)).xyz; // transform the derivatives to decal space, any translation is irrelevant
float3 positionDSDdy = mul(decalData.worldToDecal, float4(positionWSDdy, 0.0)).xyz;
float3 positionDSDdx = mul(worldToDecal, float4(positionRWSDdx, 0.0)).xyz; // transform the derivatives to decal space, any translation is irrelevant
float3 positionDSDdy = mul(worldToDecal, float4(positionRWSDdy, 0.0)).xyz;
float2 sampleDiffuseDdx = positionDSDdx.xz * decalData.diffuseScaleBias.xy; // factor in the atlas scale
float2 sampleDiffuseDdy = positionDSDdy.xz * decalData.diffuseScaleBias.xy;

22
com.unity.render-pipelines.high-definition/HDRP/Material/LTCAreaLight/LTCAreaLight.cs


int m_refCounting;
// For area lighting - We pack all texture inside a texture array to reduce the number of resource required
Texture2DArray m_LtcData; // 0: m_LtcGGXMatrix - RGBA, 2: m_LtcDisneyDiffuseMatrix - RGBA, 3: m_LtcMultiGGXFresnelDisneyDiffuse - RGB, A unused
Texture2DArray m_LtcData; // 0: m_LtcGGXMatrix - RGBA, 1: m_LtcDisneyDiffuseMatrix - RGBA
const int k_LtcLUTMatrixDim = 3; // size of the matrix (3x3)
const int k_LtcLUTResolution = 64;

tex.SetPixels(pixels, arrayElement);
}
// Special-case function for 'm_LtcMultiGGXFresnelDisneyDiffuse'.
void LoadLUT(Texture2DArray tex, int arrayElement, TextureFormat format, float[] LtcGGXMagnitudeData, float[] LtcGGXFresnelData, float[] LtcDisneyDiffuseMagnitudeData)
{
const int count = k_LtcLUTResolution * k_LtcLUTResolution;
Color[] pixels = new Color[count];
for (int i = 0; i < count; i++)
{
// We store the result of the subtraction as a run-time optimization.
// See the footnote 2 of "LTC Fresnel Approximation" by Stephen Hill.
pixels[i] = new Color(LtcGGXMagnitudeData[i] - LtcGGXFresnelData[i], LtcGGXFresnelData[i], LtcDisneyDiffuseMagnitudeData[i], 1);
}
tex.SetPixels(pixels, arrayElement);
}
public void Build()
{
Debug.Assert(m_refCounting >= 0);

hideFlags = HideFlags.HideAndDontSave,
wrapMode = TextureWrapMode.Clamp,
filterMode = FilterMode.Bilinear,
name = CoreUtils.GetTextureAutoName(k_LtcLUTResolution, k_LtcLUTResolution, TextureFormat.RGBAHalf, depth: 3, dim: TextureDimension.Tex2DArray, name: "LTC_LUT")
name = CoreUtils.GetTextureAutoName(k_LtcLUTResolution, k_LtcLUTResolution, TextureFormat.RGBAHalf, depth: 2, dim: TextureDimension.Tex2DArray, name: "LTC_LUT")
// TODO: switch to RGBA64 when it becomes available.
LoadLUT(m_LtcData, 2, TextureFormat.RGBAHalf, s_LtcGGXMagnitudeData, s_LtcGGXFresnelData, s_LtcDisneyDiffuseMagnitudeData);
m_LtcData.Apply();
}

1
com.unity.render-pipelines.high-definition/HDRP/Material/LTCAreaLight/LTCAreaLight.hlsl


#define LTC_GGX_MATRIX_INDEX 0 // RGBA
#define LTC_DISNEY_DIFFUSE_MATRIX_INDEX 1 // RGBA
#define LTC_MULTI_GGX_FRESNEL_DISNEY_DIFFUSE_INDEX 2 // RGB, A unused
#define LTC_LUT_SIZE 64
#define LTC_LUT_SCALE ((LTC_LUT_SIZE - 1) * rcp(LTC_LUT_SIZE))

998
com.unity.render-pipelines.high-definition/HDRP/Material/LTCAreaLight/LtcData.DisneyDiffuse.cs
文件差异内容过多而无法显示
查看文件

992
com.unity.render-pipelines.high-definition/HDRP/Material/LTCAreaLight/LtcData.GGX.cs
文件差异内容过多而无法显示
查看文件

2
com.unity.render-pipelines.high-definition/HDRP/Material/LayeredLit/LayeredLitData.hlsl


#endif
GetLayerTexCoord( input.texCoord0, input.texCoord1, input.texCoord2, input.texCoord3,
input.positionWS, input.worldToTangent[2].xyz, layerTexCoord);
input.positionRWS, input.worldToTangent[2].xyz, layerTexCoord);
}
void ApplyDisplacementTileScale(inout float height0, inout float height1, inout float height2, inout float height3)

177
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/Lit.hlsl


TEXTURE2D(_GBufferTexture2);
TEXTURE2D(_GBufferTexture3);
#include "../LTCAreaLight/LTCAreaLight.hlsl"
#include "../PreIntegratedFGD/PreIntegratedFGD.hlsl"
#include "HDRP/Material/LTCAreaLight/LTCAreaLight.hlsl"
#include "HDRP/Material/PreIntegratedFGD/PreIntegratedFGD.hlsl"
//-----------------------------------------------------------------------------
// Definition

#define CLEAR_COAT_PERCEPTUAL_ROUGHNESS RoughnessToPerceptualRoughness(CLEAR_COAT_ROUGHNESS)
//-----------------------------------------------------------------------------
// Ligth and material classification for the deferred rendering path
// Light and material classification for the deferred rendering path
// Configure what kind of combination is supported
//-----------------------------------------------------------------------------

float energyCompensation;
// IBL
float3 iblR; // Dominant specular direction, used for IBL in EvaluateBSDF_Env()
float3 iblR; // Reflected specular direction, used for IBL in EvaluateBSDF_Env()
float3 specularFGD; // Store preconvoled BRDF for both specular and diffuse
float3 specularFGD; // Store preintegrated BSDF for both specular and diffuse
float diffuseFGD;
// Area lights (17 VGPRs)

float3x3 ltcTransformSpecular; // Inverse transformation for GGX (4x VGPRs)
float ltcMagnitudeDiffuse;
float3 ltcMagnitudeFresnel;
// Clear coat
float coatPartLambdaV;

float ltcMagnitudeCoatFresnel;
#if HAS_REFRACTION
// Refraction

preLightData.coatIblF = F_Schlick(CLEAR_COAT_F0, NdotV) * bsdfData.coatMask;
}
float3 iblN, iblR;
// Handle IBL + area light + multiscattering.
// Note: use the not modified by anisotropy iblPerceptualRoughness here.
float specularReflectivity;
GetPreIntegratedFGDGGXAndDisneyDiffuse(NdotV, preLightData.iblPerceptualRoughness, bsdfData.fresnel0, preLightData.specularFGD, preLightData.diffuseFGD, specularReflectivity);
#ifdef USE_DIFFUSE_LAMBERT_BRDF
preLightData.diffuseFGD = 1.0;
#endif
#ifdef LIT_USE_GGX_ENERGY_COMPENSATION
// Ref: Practical multiple scattering compensation for microfacet models.
// We only apply the formulation for metals.
// For dielectrics, the change of reflectance is negligible.
// We deem the intensity difference of a couple of percent for high values of roughness
// to not be worth the cost of another precomputed table.
// Note: this formulation bakes the BSDF non-symmetric!
preLightData.energyCompensation = 1.0 / specularReflectivity - 1.0;
#else
preLightData.energyCompensation = 0.0;
#endif // LIT_USE_GGX_ENERGY_COMPENSATION
float3 iblN;
// We avoid divergent evaluation of the GGX, as that nearly doubles the cost.
// If the tile has anisotropy, all the pixels within the tile are evaluated as anisotropic.

preLightData.partLambdaV = GetSmithJointGGXAnisoPartLambdaV(TdotV, BdotV, NdotV, bsdfData.roughnessT, bsdfData.roughnessB);
// For GGX aniso and IBL we have done an empirical (eye balled) approximation compare to the reference.
// We use a single fetch, and we stretch the normal to use based on various criteria.
// result are far away from the reference but better than nothing
// For positive anisotropy values: tangent = highlight stretch (anisotropy) direction, bitangent = grain (brush) direction.
float3 grainDirWS = (bsdfData.anisotropy >= 0.0) ? bsdfData.bitangentWS : bsdfData.tangentWS;
// Reduce stretching for (perceptualRoughness < 0.2).
float stretch = abs(bsdfData.anisotropy) * saturate(5 * preLightData.iblPerceptualRoughness);
// NOTE: If we follow the theory we should use the modified normal for the different calculation implying a normal (like NdotV) and use 'anisoIblNormalWS'
// into function like GetSpecularDominantDir(). However modified normal is just a hack. The goal is just to stretch a cubemap, no accuracy here.
// With this in mind and for performance reasons we chose to only use modified normal to calculate R.
iblN = GetAnisotropicModifiedNormal(grainDirWS, N, V, stretch);
// perceptualRoughness is use as input and output here
GetGGXAnisotropicModifiedNormalAndRoughness(bsdfData.bitangentWS, bsdfData.tangentWS, N, V, bsdfData.anisotropy, preLightData.iblPerceptualRoughness, iblN, preLightData.iblPerceptualRoughness);
}
else
{

// IBL
// Handle IBL + multiscattering
float specularReflectivity;
GetPreIntegratedFGDGGXAndDisneyDiffuse(NdotV, preLightData.iblPerceptualRoughness, bsdfData.fresnel0, preLightData.specularFGD, preLightData.diffuseFGD, specularReflectivity);
#ifdef USE_DIFFUSE_LAMBERT_BRDF
preLightData.diffuseFGD = 1.0;
#endif
iblR = reflect(-V, iblN);
// This is a ad-hoc tweak to better match reference of anisotropic GGX.
// TODO: We need a better hack.
preLightData.iblPerceptualRoughness *= saturate(1.2 - abs(bsdfData.anisotropy));
// Corretion of reflected direction for better handling of rough material
preLightData.iblR = iblR;
#ifdef LIT_USE_GGX_ENERGY_COMPENSATION
// Ref: Practical multiple scattering compensation for microfacet models.
// We only apply the formulation for metals.
// For dielectrics, the change of reflectance is negligible.
// We deem the intensity difference of a couple of percent for high values of roughness
// to not be worth the cost of another precomputed table.
// Note: this formulation bakes the BSDF non-symmetric!
preLightData.energyCompensation = 1.0 / specularReflectivity - 1.0;
#else
preLightData.energyCompensation = 0.0;
#endif // LIT_USE_GGX_ENERGY_COMPENSATION
preLightData.iblR = reflect(-V, iblN);
// Area light
// UVs for sampling the LUTs

preLightData.orthoBasisViewNormal[2] = N;
preLightData.orthoBasisViewNormal[1] = cross(preLightData.orthoBasisViewNormal[2], preLightData.orthoBasisViewNormal[0]);
float3 ltcMagnitude = SAMPLE_TEXTURE2D_ARRAY_LOD(_LtcData, s_linear_clamp_sampler, uv, LTC_MULTI_GGX_FRESNEL_DISNEY_DIFFUSE_INDEX, 0).rgb;
float ltcGGXFresnelMagnitudeDiff = ltcMagnitude.r; // The difference of magnitudes of GGX and Fresnel
float ltcGGXFresnelMagnitude = ltcMagnitude.g;
float ltcDisneyDiffuseMagnitude = ltcMagnitude.b;
#ifdef USE_DIFFUSE_LAMBERT_BRDF
preLightData.ltcMagnitudeDiffuse = 1;
#else
preLightData.ltcMagnitudeDiffuse = ltcDisneyDiffuseMagnitude;
#endif
// TODO: the fit seems rather poor. The scaling factor of 0.5 allows us
// to match the reference for rough metals, but further darkens dielectrics.
preLightData.ltcMagnitudeFresnel = bsdfData.fresnel0 * ltcGGXFresnelMagnitudeDiff + (float3)ltcGGXFresnelMagnitude;
preLightData.ltcTransformCoat = 0.0;
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_CLEAR_COAT))
{
float2 uv = LTC_LUT_OFFSET + LTC_LUT_SCALE * float2(CLEAR_COAT_PERCEPTUAL_ROUGHNESS, theta * INV_HALF_PI);

preLightData.ltcTransformCoat = 0.0;
ltcMagnitude = SAMPLE_TEXTURE2D_ARRAY_LOD(_LtcData, s_linear_clamp_sampler, uv, LTC_MULTI_GGX_FRESNEL_DISNEY_DIFFUSE_INDEX, 0).rgb;
ltcGGXFresnelMagnitudeDiff = ltcMagnitude.r; // The difference of magnitudes of GGX and Fresnel
ltcGGXFresnelMagnitude = ltcMagnitude.g;
preLightData.ltcMagnitudeCoatFresnel = (CLEAR_COAT_F0 * ltcGGXFresnelMagnitudeDiff + ltcGGXFresnelMagnitude) * bsdfData.coatMask;
}
else
{
preLightData.ltcTransformCoat = 0.0;
preLightData.ltcMagnitudeCoatFresnel = 0.0;
}
// refraction (forward only)

// This function require the 3 structure surfaceData, builtinData, bsdfData because it may require both the engine side data, and data that will not be store inside the gbuffer.
float3 GetBakedDiffuseLighting(SurfaceData surfaceData, BuiltinData builtinData, BSDFData bsdfData, PreLightData preLightData)
{
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING)) // This test is static as it is done in GBuffer or forward pass, will be remove by compiler
{
bsdfData.diffuseColor = GetModifiedDiffuseColorForSSS(bsdfData); // local modification of bsdfData
}
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)
{

#endif
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_SUBSURFACE_SCATTERING)) // This test is static as it is done in GBuffer or forward pass, will be remove by compiler
{
bsdfData.diffuseColor = GetModifiedDiffuseColorForSSS(bsdfData); // local modification of bsdfData
}
// Premultiply bake diffuse lighting information with DisneyDiffuse pre-integration
return builtinData.bakeDiffuseLighting * preLightData.diffuseFGD * surfaceData.ambientOcclusion * bsdfData.diffuseColor + builtinData.emissiveColor;

DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
float3 N = bsdfData.normalWS;
float3 L = -lightData.forward; // Lights point backward in Unity
float NdotL = dot(N, L);
float3 L = -lightData.forward;
float3 N = bsdfData.normalWS;
float NdotL = dot(N, L);
float3 transmittance = float3(0.0, 0.0, 0.0);
if (HasFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_THIN_THICKNESS))

DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
float3 lightToSample = posInput.positionWS - lightData.positionWS;
int lightType = lightData.lightType;
float3 lightToSample;
distances.w = dot(lightToSample, lightData.forward);
if (lightType == GPULIGHTTYPE_PROJECTOR_BOX)
{
L = -lightData.forward;
distances.xyz = 1; // No distance or angle attenuation
}
else
{
float3 unL = -lightToSample;
float distSq = dot(unL, unL);
float distRcp = rsqrt(distSq);
float dist = distSq * distRcp;
L = unL * distRcp;
distances.xyz = float3(dist, distSq, distRcp);
}
GetPunctualLightVectors(posInput.positionWS, lightData, L, lightToSample, distances);
float3 N = bsdfData.normalWS;
float NdotL = dot(N, L);

ltcValue = LTCEvaluate(P1, P2, B, preLightData.ltcTransformDiffuse);
ltcValue *= lightData.diffuseScale;
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse = preLightData.ltcMagnitudeDiffuse * ltcValue;
// See comment for specular magnitude, it apply to diffuse as well
lighting.diffuse = preLightData.diffuseFGD * ltcValue;
UNITY_BRANCH if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{

// Evaluate the specular part
ltcValue = LTCEvaluate(P1, P2, B, preLightData.ltcTransformSpecular);
ltcValue *= lightData.specularScale;
lighting.specular = preLightData.ltcMagnitudeFresnel * ltcValue;
// We need to multiply by the magnitude of the integral of the BRDF
// ref: http://advances.realtimerendering.com/s2016/s2016_ltc_fresnel.pdf
// This value is what we store in specularFGD, so reuse it
lighting.specular = preLightData.specularFGD * ltcValue;
lighting.diffuse *= (1.0 - preLightData.ltcMagnitudeCoatFresnel);
lighting.specular *= (1.0 - preLightData.ltcMagnitudeCoatFresnel);
lighting.specular += preLightData.ltcMagnitudeCoatFresnel * ltcValue;
// For clear coat we don't fetch specularFGD we can use directly the perfect fresnel coatIblF
lighting.diffuse *= (1.0 - preLightData.coatIblF);
lighting.specular *= (1.0 - preLightData.coatIblF);
lighting.specular += preLightData.coatIblF * ltcValue;
}
// Save ALU by applying 'lightData.color' only once.

}
//-----------------------------------------------------------------------------
// EvaluateBSDF_Area - Approximation with Linearly Transformed Cosines
// EvaluateBSDF_Rect - Approximation with Linearly Transformed Cosines
//-----------------------------------------------------------------------------
// #define ELLIPSOIDAL_ATTENUATION

ltcValue = PolygonIrradiance(mul(lightVerts, preLightData.ltcTransformDiffuse));
ltcValue *= lightData.diffuseScale;
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse = preLightData.ltcMagnitudeDiffuse * ltcValue;
// See comment for specular magnitude, it apply to diffuse as well
lighting.diffuse = preLightData.diffuseFGD * ltcValue;
UNITY_BRANCH if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
{

// Polygon irradiance in the transformed configuration.
ltcValue = PolygonIrradiance(mul(lightVerts, preLightData.ltcTransformSpecular));
ltcValue *= lightData.specularScale;
lighting.specular += preLightData.ltcMagnitudeFresnel * ltcValue;
// We need to multiply by the magnitude of the integral of the BRDF
// ref: http://advances.realtimerendering.com/s2016/s2016_ltc_fresnel.pdf
// This value is what we store in specularFGD, so reuse it
lighting.specular += preLightData.specularFGD * ltcValue;
lighting.diffuse *= (1.0 - preLightData.ltcMagnitudeCoatFresnel);
lighting.specular *= (1.0 - preLightData.ltcMagnitudeCoatFresnel);
lighting.specular += preLightData.ltcMagnitudeCoatFresnel * ltcValue;
// For clear coat we don't fetch specularFGD we can use directly the perfect fresnel coatIblF
lighting.diffuse *= (1.0 - preLightData.coatIblF);
lighting.specular *= (1.0 - preLightData.coatIblF);
lighting.specular += preLightData.coatIblF * ltcValue;
}
// Save ALU by applying 'lightData.color' only once.

else
#endif
{
if ((lightData.envIndex & 1) == ENVCACHETYPE_CUBEMAP)
if (!IsEnvIndexTexture2D(lightData.envIndex)) // ENVCACHETYPE_CUBEMAP
{
R = GetSpecularDominantDir(bsdfData.normalWS, R, preLightData.iblPerceptualRoughness, ClampNdotV(preLightData.NdotV));
// When we are rough, we tend to see outward shifting of the reflection when at the boundary of the projection volume

#else
GetScreenSpaceAmbientOcclusionMultibounce(posInput.positionSS, preLightData.NdotV, bsdfData.perceptualRoughness, 1.0, bsdfData.specularOcclusion, bsdfData.diffuseColor, bsdfData.fresnel0, aoFactor);
#endif
ApplyAmbientOcclusionFactor(aoFactor, bakeLightingData, lighting);
// Subsurface scattering mode

8
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitBuiltinData.hlsl


// TODO: Sample lightmap/lightprobe/volume proxy
// This should also handle projective lightmap
builtinData.bakeDiffuseLighting = SampleBakedGI(input.positionWS, bentNormalWS, input.texCoord1, input.texCoord2);
builtinData.bakeDiffuseLighting = SampleBakedGI(input.positionRWS, bentNormalWS, input.texCoord1, input.texCoord2);
// It is safe to call this function here as surfaceData have been filled
// We want to know if we must enable transmission on GI for SSS material, if the material have no SSS, this code will be remove by the compiler.

// however it will not optimize the lightprobe case due to the proxy volume relying on dynamic if (we rely must get right of this dynamic if), not a problem for SH9, but a problem for proxy volume.
// TODO: optimize more this code.
// Add GI transmission contribution by resampling the GI for inverted vertex normal
builtinData.bakeDiffuseLighting += SampleBakedGI(input.positionWS, -input.worldToTangent[2], input.texCoord1, input.texCoord2) * bsdfData.transmittance;
builtinData.bakeDiffuseLighting += SampleBakedGI(input.positionRWS, -input.worldToTangent[2], input.texCoord1, input.texCoord2) * bsdfData.transmittance;
float4 shadowMask = SampleShadowMask(input.positionWS, input.texCoord1);
float4 shadowMask = SampleShadowMask(input.positionRWS, input.texCoord1);
builtinData.shadowMask0 = shadowMask.x;
builtinData.shadowMask1 = shadowMask.y;
builtinData.shadowMask2 = shadowMask.z;

#endif
input.texCoord0, input.texCoord1, input.texCoord2, input.texCoord3, _UVMappingMaskEmissive, _UVMappingMaskEmissive,
_EmissiveColorMap_ST.xy, _EmissiveColorMap_ST.zw, float2(0.0, 0.0), float2(0.0, 0.0), 1.0, false,
input.positionWS, _TexWorldScaleEmissive,
input.positionRWS, _TexWorldScaleEmissive,
mappingType, layerTexCoord);
#ifndef LAYERED_LIT_SHADER

11
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitData.hlsl


layerTexCoord.vertexTangentWS0 = input.worldToTangent[0];
layerTexCoord.vertexBitangentWS0 = input.worldToTangent[1];
// TODO: We should use relative camera position here - This will be automatic when we will move to camera relative space.
float3 dPdx = ddx_fine(input.positionWS);
float3 dPdy = ddy_fine(input.positionWS);
float3 dPdx = ddx_fine(input.positionRWS);
float3 dPdy = ddy_fine(input.positionRWS);
float3 sigmaX = dPdx - dot(dPdx, vertexNormalWS) * vertexNormalWS;
float3 sigmaY = dPdy - dot(dPdy, vertexNormalWS) * vertexNormalWS;

// in function with FragInputs input as parameters
// layerTexCoord must have been initialize to 0 outside of this function
void GetLayerTexCoord(float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3,
float3 positionWS, float3 vertexNormalWS, inout LayerTexCoord layerTexCoord)
float3 positionRWS, float3 vertexNormalWS, inout LayerTexCoord layerTexCoord)
{
layerTexCoord.vertexNormalWS = vertexNormalWS;
layerTexCoord.triplanarWeights = ComputeTriplanarWeights(vertexNormalWS);

// Be sure that the compiler is aware that we don't use UV1 to UV3 for main layer so it can optimize code
ComputeLayerTexCoord( texCoord0, texCoord1, texCoord2, texCoord3, _UVMappingMask, _UVDetailsMappingMask,
_BaseColorMap_ST.xy, _BaseColorMap_ST.zw, _DetailMap_ST.xy, _DetailMap_ST.zw, 1.0, _LinkDetailsWithBase,
positionWS, _TexWorldScale,
positionRWS, _TexWorldScale,
mappingType, layerTexCoord);
}

#endif
GetLayerTexCoord( input.texCoord0, input.texCoord1, input.texCoord2, input.texCoord3,
input.positionWS, input.worldToTangent[2].xyz, layerTexCoord);
input.positionRWS, input.worldToTangent[2].xyz, layerTexCoord);
}
#include "LitDataDisplacement.hlsl"

10
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitDataDisplacement.hlsl


{
float3 objectScale = float3(1.0, 1.0, 1.0);
// TODO: This should be an uniform for the object, this code should be remove once we have it. - Workaround for now
// To handle object scaling with pixel displacement we need to multiply the view vector by the inverse scale.
// To Handle object scaling with vertex/tessellation displacement we must multiply displacement by object scale
// Currently we extract either the scale (ObjectToWorld) or the inverse scale (worldToObject) directly by taking the transform matrix
float4x4 worldTransform;
// TODO: This should be an uniform for the object, this code should be remove once we have it. - Workaround for now
// To handle object scaling with pixel displacement we need to multiply the view vector by the inverse scale.
// To Handle object scaling with vertex/tessellation displacement we must multiply displacement by object scale
// Currently we extract either the scale (ObjectToWorld) or the inverse scale (worldToObject) directly by taking the transform matrix
float4x4 worldTransform;
if (vertexDisplacement)
{
worldTransform = GetObjectToWorldMatrix();

4
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitDataIndividualLayer.hlsl


// scale and bias for base and detail + global tiling factor (for layered lit only)
float2 texScale, float2 texBias, float2 texScaleDetails, float2 texBiasDetails, float additionalTiling, float linkDetailsWithBase,
// parameter for planar/triplanar
float3 positionWS, float worldScale,
float3 positionRWS, float worldScale,
// mapping type and output
int mappingType, inout LayerTexCoord layerTexCoord)
{

float2 uvXY;
float2 uvZY;
GetTriplanarCoordinate(GetAbsolutePositionWS(positionWS) * worldScale, uvXZ, uvXY, uvZY);
GetTriplanarCoordinate(GetAbsolutePositionWS(positionRWS) * worldScale, uvXZ, uvXY, uvZY);
// Planar is just XZ of triplanar
if (mappingType == UV_MAPPING_PLANAR)

21
com.unity.render-pipelines.high-definition/HDRP/Material/Lit/LitDataMeshModification.hlsl


float3 GetVertexDisplacement(float3 positionWS, float3 normalWS, float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3, float4 vertexColor)
// Note: positionWS can be either in camera relative space or not
float3 GetVertexDisplacement(float3 positionRWS, float3 normalWS, float2 texCoord0, float2 texCoord1, float2 texCoord2, float2 texCoord3, float4 vertexColor)
GetLayerTexCoord(texCoord0, texCoord1, texCoord2, texCoord3, positionWS, normalWS, layerTexCoord);
GetLayerTexCoord(texCoord0, texCoord1, texCoord2, texCoord3, positionRWS, normalWS, layerTexCoord);
// TODO: do this algorithm for lod fetching as lod not available in vertex/domain shader
// http://www.sebastiansylvan.com/post/the-problem-with-tessellation-in-directx-11/

void ApplyVertexModification(AttributesMesh input, float3 normalWS, inout float3 positionWS, float4 time)
// Note: positionWS can be either in camera relative space or not
void ApplyVertexModification(AttributesMesh input, float3 normalWS, inout float3 positionRWS, float4 time)
positionWS += GetVertexDisplacement(positionWS, normalWS,
positionRWS += GetVertexDisplacement(positionRWS, normalWS,
#ifdef ATTRIBUTES_NEED_TEXCOORD0
input.uv0,
#else

#endif
#ifdef _VERTEX_WIND
float3 rootWP = mul(GetObjectToWorldMatrix(), float4(0, 0, 0, 1)).xyz;
ApplyWindDisplacement(positionWS, normalWS, rootWP, _Stiffness, _Drag, _ShiverDrag, _ShiverDirectionality, _InitialBend, input.color.a, time);
// current wind implementation is in absolute world space
float3 rootWP = GetObjectAbsolutePositionWS();
float3 absolutePositionWS = GetAbsolutePositionWS(positionRWS);
ApplyWindDisplacement(absolutePositionWS, normalWS, rootWP, _Stiffness, _Drag, _ShiverDrag, _ShiverDirectionality, _InitialBend, input.color.a, time);
positionRWS = GetCameraRelativePositionWS(absolutePositionWS);
#endif
}

// y - 2->0 edge
// z - 0->1 edge
// w - inside tessellation factor
void ApplyTessellationModification(VaryingsMeshToDS input, float3 normalWS, inout float3 positionWS)
void ApplyTessellationModification(VaryingsMeshToDS input, float3 normalWS, inout float3 positionRWS)
positionWS += GetVertexDisplacement(positionWS, normalWS,
positionRWS += GetVertexDisplacement(positionRWS, normalWS,
#ifdef VARYINGS_DS_NEED_TEXCOORD0
input.texCoord0,
#else

16
com.unity.render-pipelines.high-definition/HDRP/Material/MaterialUtilities.hlsl


// Return camera relative probe volume world to object transformation
float4x4 GetProbeVolumeWorldToObject()
{
return ApplyCameraTranslationToInverseMatrix(unity_ProbeVolumeWorldToObject);
}
float3 SampleBakedGI(float3 positionWS, float3 normalWS, float2 uvStaticLightmap, float2 uvDynamicLightmap)
float3 SampleBakedGI(float3 positionRWS, float3 normalWS, float2 uvStaticLightmap, float2 uvDynamicLightmap)
{
// If there is no lightmap, it assume lightprobe
#if !defined(LIGHTMAP_ON) && !defined(DYNAMICLIGHTMAP_ON)

}
else
{
// 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...)
return SampleProbeVolumeSH4(TEXTURE3D_PARAM(unity_ProbeVolumeSH, samplerunity_ProbeVolumeSH), GetAbsolutePositionWS(positionWS), normalWS, unity_ProbeVolumeWorldToObject,
return SampleProbeVolumeSH4(TEXTURE3D_PARAM(unity_ProbeVolumeSH, samplerunity_ProbeVolumeSH), positionRWS, normalWS, GetProbeVolumeWorldToObject(),
unity_ProbeVolumeParams.y, unity_ProbeVolumeParams.z, unity_ProbeVolumeMin, unity_ProbeVolumeSizeInv);
}

#endif
}
float4 SampleShadowMask(float3 positionWS, float2 uvStaticLightmap) // normalWS not use for now
float4 SampleShadowMask(float3 positionRWS, float2 uvStaticLightmap) // normalWS not use for now
{
#if defined(LIGHTMAP_ON)
float2 uv = uvStaticLightmap * unity_LightmapST.xy + unity_LightmapST.zw;

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,
rawOcclusionMask = SampleProbeOcclusion(TEXTURE3D_PARAM(unity_ProbeVolumeSH, samplerunity_ProbeVolumeSH), positionRWS, GetProbeVolumeWorldToObject(),
unity_ProbeVolumeParams.y, unity_ProbeVolumeParams.z, unity_ProbeVolumeMin, unity_ProbeVolumeSizeInv);
}
else

3
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.cs


public float iridescenceIor;
[SurfaceDataAttributes("IridescenceThickness")]
public float iridescenceThickness;
[SurfaceDataAttributes("Iridescence Mask")]
public float iridescenceMask;
// Top interface and media (clearcoat)
[SurfaceDataAttributes("Coat Smoothness")]

// iridescence
public float iridescenceIor;
public float iridescenceThickness;
public float iridescenceMask;
// SSS
public uint diffusionProfile;

34
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.cs.hlsl


#define DEBUGVIEW_STACKLIT_SURFACEDATA_ANISOTROPY (1115)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_IRIDESCENCE_IOR (1116)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_IRIDESCENCE_THICKNESS (1117)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_COAT_SMOOTHNESS (1118)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_COAT_IOR (1119)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_COAT_THICKNESS (1120)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_COAT_EXTINCTION_COEFFICIENT (1121)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_DIFFUSION_PROFILE (1122)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_SUBSURFACE_MASK (1123)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_THICKNESS (1124)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_IRIDESCENCE_MASK (1118)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_COAT_SMOOTHNESS (1119)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_COAT_IOR (1120)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_COAT_THICKNESS (1121)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_COAT_EXTINCTION_COEFFICIENT (1122)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_DIFFUSION_PROFILE (1123)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_SUBSURFACE_MASK (1124)
#define DEBUGVIEW_STACKLIT_SURFACEDATA_THICKNESS (1125)
//
// UnityEngine.Experimental.Rendering.HDPipeline.StackLit+BSDFData: static fields

#define DEBUGVIEW_STACKLIT_BSDFDATA_COAT_EXTINCTION (1174)
#define DEBUGVIEW_STACKLIT_BSDFDATA_IRIDESCENCE_IOR (1175)
#define DEBUGVIEW_STACKLIT_BSDFDATA_IRIDESCENCE_THICKNESS (1176)
#define DEBUGVIEW_STACKLIT_BSDFDATA_DIFFUSION_PROFILE (1177)
#define DEBUGVIEW_STACKLIT_BSDFDATA_SUBSURFACE_MASK (1178)
#define DEBUGVIEW_STACKLIT_BSDFDATA_THICKNESS (1179)
#define DEBUGVIEW_STACKLIT_BSDFDATA_USE_THICK_OBJECT_MODE (1180)
#define DEBUGVIEW_STACKLIT_BSDFDATA_TRANSMITTANCE (1181)
#define DEBUGVIEW_STACKLIT_BSDFDATA_IRIDESCENCE_MASK (1177)
#define DEBUGVIEW_STACKLIT_BSDFDATA_DIFFUSION_PROFILE (1178)
#define DEBUGVIEW_STACKLIT_BSDFDATA_SUBSURFACE_MASK (1179)
#define DEBUGVIEW_STACKLIT_BSDFDATA_THICKNESS (1180)
#define DEBUGVIEW_STACKLIT_BSDFDATA_USE_THICK_OBJECT_MODE (1181)
#define DEBUGVIEW_STACKLIT_BSDFDATA_TRANSMITTANCE (1182)
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.StackLit+SurfaceData
// PackingRules = Exact

float anisotropy;
float iridescenceIor;
float iridescenceThickness;
float iridescenceMask;
float coatPerceptualSmoothness;
float coatIor;
float coatThickness;

float3 coatExtinction;
float iridescenceIor;
float iridescenceThickness;
float iridescenceMask;
uint diffusionProfile;
float subsurfaceMask;
float thickness;

break;
case DEBUGVIEW_STACKLIT_SURFACEDATA_IRIDESCENCE_THICKNESS:
result = surfacedata.iridescenceThickness.xxx;
break;
case DEBUGVIEW_STACKLIT_SURFACEDATA_IRIDESCENCE_MASK:
result = surfacedata.iridescenceMask.xxx;
break;
case DEBUGVIEW_STACKLIT_SURFACEDATA_COAT_SMOOTHNESS:
result = surfacedata.coatPerceptualSmoothness.xxx;

break;
case DEBUGVIEW_STACKLIT_BSDFDATA_IRIDESCENCE_THICKNESS:
result = bsdfdata.iridescenceThickness.xxx;
break;
case DEBUGVIEW_STACKLIT_BSDFDATA_IRIDESCENCE_MASK:
result = bsdfdata.iridescenceMask.xxx;
break;
case DEBUGVIEW_STACKLIT_BSDFDATA_DIFFUSION_PROFILE:
result = GetIndexColor(bsdfdata.diffusionProfile);

609
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.hlsl


//-----------------------------------------------------------------------------
// Choose between Lambert diffuse and Disney diffuse (enable only one of them)
// TODO Disney Diffuse
// Enable reference mode for IBL and area lights
// Both reference defined below can be defined only if LightLoop is present, else we get a compile error
#ifdef HAS_LIGHTLOOP
// TODO for stacklit
// #define STACK_LIT_DISPLAY_REFERENCE_AREA
// #define STACK_LIT_DISPLAY_REFERENCE_IBL
#endif
//-----------------------------------------------------------------------------
// Texture and constant buffer declaration

// Required for SSS, GBuffer texture declaration
TEXTURE2D(_GBufferTexture0);
// Declare the BSDF specific FGD property and its fetching function
#include "../PreIntegratedFGD/PreIntegratedFGD.hlsl"
#include "HDRP/Material/LTCAreaLight/LTCAreaLight.hlsl"
#include "HDRP/Material/PreIntegratedFGD/PreIntegratedFGD.hlsl"
//-----------------------------------------------------------------------------
// Definition

#ifdef _MATERIAL_FEATURE_COAT
# define COAT_NB_LOBES 1
# define COAT_LOBE_IDX 0
# define COAT_LOBE_IDX 0 // Leave coat index == 0, otherwise change IF_FEATURE_COAT etc
# define BASE_LOBEA_IDX (COAT_LOBE_IDX+1)
# define BASE_LOBEB_IDX (BASE_LOBEA_IDX+1)

#else // ! _MATERIAL_FEATURE_COAT
// For iridescence, we will reuse the recompute per light keyword even when not vlayered.
// When vlayered and iridescence is on, iridescence is also automatically recomputed per light too,
// so the following gives the recompute option for iridescence when NOT vlayered:
#ifdef VLAYERED_RECOMPUTE_PERLIGHT
# if _MATERIAL_FEATURE_IRIDESCENCE
# define IRIDESCENCE_RECOMPUTE_PERLIGHT
# endif
#endif
# undef VLAYERED_RECOMPUTE_PERLIGHT
# undef VLAYERED_USE_REFRACTED_ANGLES_FOR_BASE
# undef _MATERIAL_FEATURE_COAT_NORMALMAP // enforce a "coat enabled subfeature" condition on this shader_feature

bsdfData.anisotropy = anisotropy;
bsdfData.tangentWS = tangentWS;
bsdfData.bitangentWS = bitangentWS;
}
void FillMaterialIridescence(float mask, float thickness, float ior, inout BSDFData bsdfData)
{
bsdfData.iridescenceMask = mask;
bsdfData.iridescenceThickness = thickness;
bsdfData.iridescenceIor = ior;
}
void FillMaterialCoatData(float coatPerceptualRoughness, float coatIor, float coatThickness, float3 coatExtinction, inout BSDFData bsdfData)

bsdfData.lobeMix = surfaceData.lobeMix;
// There is no metallic with SSS and specular color mode
float metallic = HasFlag(surfaceData.materialFeatures, /*MATERIALFEATUREFLAGS_LIT_SPECULAR_COLOR |*/ MATERIALFEATUREFLAGS_STACK_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION) ? 0.0 : surfaceData.metallic;
float metallic = HasFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_SUBSURFACE_SCATTERING | MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION) ? 0.0 : surfaceData.metallic;
bsdfData.diffuseColor = ComputeDiffuseColor(surfaceData.baseColor, metallic);
bsdfData.fresnel0 = ComputeFresnel0(surfaceData.baseColor, surfaceData.metallic, IorToFresnel0(surfaceData.dielectricIor));

if (HasFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_ANISOTROPY))
{
FillMaterialAnisotropy(surfaceData.anisotropy, surfaceData.tangentWS, cross(surfaceData.normalWS, surfaceData.tangentWS), bsdfData);
}
if (HasFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_IRIDESCENCE))
{
FillMaterialIridescence(surfaceData.iridescenceMask, surfaceData.iridescenceThickness, surfaceData.iridescenceIor, bsdfData);
}
if (HasFlag(surfaceData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_COAT))

{
float NdotV[NB_NORMALS]; // Could be negative due to normal mapping, use ClampNdotV()
float geomNdotV;
float bottomAngleFGD;
float bottomAngleFGD; // Only used when dual normal maps are enabled
float TdotV; // Stored only when VLAYERED_RECOMPUTE_PERLIGHT
float BdotV;

// is split by anisotropy, while IBL anisotropy is delt with a hack on the used iblR
// vector, with the non-anisotropic roughness).
float3 specularFGD[TOTAL_NB_LOBES]; // Store preconvoled BSDF for both specular and diffuse
float3 specularFGD[TOTAL_NB_LOBES]; // Store preintegrated BSDF for both specular and diffuse
float diffuseFGD;

// for it (hence the name iblF in Lit). Here, we will fold all data into
// lobe-indexed arrays.
// For iridescence, to avoid recalculation per analytical light, we store the calculated
// iridescence reflectance that was used (as an approximation to "iridescent pre-integrated" FGD)
// to calculate FGD with the precalculated table:
float3 fresnelIridforCalculatingFGD;
// For clarity, we will dump the base layer lobes roughnesses used by analytical lights
// here, to avoid confusion with the per-vlayer (vs per lobe) vLayerPerceptualRoughness

// For IBLs (and analytical lights if approximation is used)
float3 vLayerEnergyCoeff[NB_VLAYERS];
//float vLayerPerceptualRoughness[NB_VLAYERS];
// TODOENERGY
// For now since FGD fetches aren't used in compute adding (instead we do non integrated
// Fresnel( ) evaluations and 1 - Fresnel( ) which is wrong, the former only ok for analytical
// lights for the top interface for R12), we will use these for FGD fetches but keep them
// for BSDF( ) eval for analytical lights since the later don't use FGD terms.
// TODOENERGY:
// For the vlayered case, fold compensation into FGD terms during ComputeAdding

//See VLAYERED_DIFFUSE_ENERGY_HACKED_TERM
float3 diffuseEnergy;
float3 diffuseEnergy; // We don't fold into diffuseFGD because of analytical lights that require it separately.
//
// Area lights
// TODO: 'orthoBasisViewNormal' is just a rotation around the normal and should thus be just 1x VGPR.
float3x3 orthoBasisViewNormal[NB_NORMALS]; // Right-handed view-dependent orthogonal basis around the normal
float3x3 ltcTransformDiffuse; // Inverse transformation for Lambertian or Disney Diffuse
float3x3 ltcTransformSpecular[TOTAL_NB_LOBES]; // Inverse transformation for GGX
//-----------------------------------------------------------------------------
//

// correct is a (1-FGD) term at the top), ie, for everything below the first interface,
// but use the actual Fresnel term for that light for R12 at the start
// of the algo (top interface) and not FGD.
//
// Interaction and performance considerations with the recompute per light option:
//
// If you recompute everything per light, FGD fetches per light might be expensive,
// so could use the FGD used for IBLs, angle used will be more or less incorrect
// depending on light directions, but probably better than using F0 terms everywhere).

// Update energy
R12 = F_Schlick(bsdfData.fresnel0, ctiForFGD);
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_IRIDESCENCE))
{
if (bsdfData.iridescenceMask > 0.0)
{
//float topIor = bsdfData.coatIor;
// TODO:
// We will avoid using coatIor directly as with the fake refraction, it can cause TIR
// which even when handled in EvalIridescence (tested), doesn't look pleasing and
// creates a discontinuity.
float scale = clamp((1.0-bsdfData.coatPerceptualRoughness), 0.0, 1.0);
float topIor = lerp(1.0001, bsdfData.coatIor, scale);
R12 = lerp(R12, EvalIridescence(topIor, ctiForFGD, bsdfData.iridescenceThickness, bsdfData.fresnel0), bsdfData.iridescenceMask);
}
}
T12 = 0.0;
#ifdef VLAYERED_DIFFUSE_ENERGY_HACKED_TERM
// Still should use FGD!

#endif
}
void PreLightData_SetupAreaLightBasis(float3 V, float3 N, int normalIdx, inout PreLightData preLightData)
{
// Construct a right-handed view-dependent orthogonal basis around the normal
preLightData.orthoBasisViewNormal[normalIdx][0] = normalize(V - N * preLightData.NdotV[normalIdx]); // Do not clamp NdotV here
preLightData.orthoBasisViewNormal[normalIdx][2] = N;
preLightData.orthoBasisViewNormal[normalIdx][1] = cross(preLightData.orthoBasisViewNormal[normalIdx][2], preLightData.orthoBasisViewNormal[normalIdx][0]);
}
void PreLightData_LoadLtcTransformSpecular(float2 uv, int lobeIdx, inout PreLightData preLightData)
{
// Get the inverse LTC matrix for GGX
// Note we load the matrix transpose (avoid to have to transpose it in shader)
preLightData.ltcTransformSpecular[lobeIdx] = 0.0;
preLightData.ltcTransformSpecular[lobeIdx]._m22 = 1.0;
preLightData.ltcTransformSpecular[lobeIdx]._m00_m02_m11_m20 = SAMPLE_TEXTURE2D_ARRAY_LOD(_LtcData, s_linear_clamp_sampler, uv, LTC_GGX_MATRIX_INDEX, 0);
}
void PreLightData_SetupAreaLights(BSDFData bsdfData, float3 V, float3 N[NB_NORMALS], float NdotV[NB_NORMALS], inout PreLightData preLightData)
{
// For sampling the LUTs
float theta[NB_NORMALS];
float2 uv[TOTAL_NB_LOBES];
// These 2 cases will generate the same code when no dual normal maps since COAT_NORMAL_IDX == BASE_NORMAL_IDX == 0,
// and one will be pruned out:
theta[COAT_NORMAL_IDX] = FastACosPos(NdotV[COAT_NORMAL_IDX]);
theta[BASE_NORMAL_IDX] = FastACosPos(NdotV[BASE_NORMAL_IDX]);
PreLightData_SetupAreaLightBasis(V, N[COAT_NORMAL_IDX], COAT_NORMAL_IDX, preLightData);
PreLightData_SetupAreaLightBasis(V, N[BASE_NORMAL_IDX], BASE_NORMAL_IDX, preLightData);
if( IsVLayeredEnabled(bsdfData) )
{
uv[COAT_LOBE_IDX] = LTC_LUT_OFFSET + LTC_LUT_SCALE * float2(bsdfData.coatPerceptualRoughness, theta[COAT_NORMAL_IDX] * INV_HALF_PI);
PreLightData_LoadLtcTransformSpecular(uv[COAT_LOBE_IDX], COAT_LOBE_IDX, preLightData);
}
uv[BASE_LOBEA_IDX] = LTC_LUT_OFFSET + LTC_LUT_SCALE * float2(bsdfData.perceptualRoughnessA, theta[BASE_NORMAL_IDX] * INV_HALF_PI);
uv[BASE_LOBEB_IDX] = LTC_LUT_OFFSET + LTC_LUT_SCALE * float2(bsdfData.perceptualRoughnessB, theta[BASE_NORMAL_IDX] * INV_HALF_PI);
PreLightData_LoadLtcTransformSpecular(uv[BASE_LOBEA_IDX], BASE_LOBEA_IDX, preLightData);
PreLightData_LoadLtcTransformSpecular(uv[BASE_LOBEB_IDX], BASE_LOBEB_IDX, preLightData);
#ifdef USE_DIFFUSE_LAMBERT_BRDF
preLightData.ltcTransformDiffuse = k_identity3x3;
#else
// TODO
// Get the inverse LTC matrix for Disney Diffuse
//preLightData.ltcTransformDiffuse = 0.0;
//preLightData.ltcTransformDiffuse._m22 = 1.0;
//preLightData.ltcTransformDiffuse._m00_m02_m11_m20 = SAMPLE_TEXTURE2D_ARRAY_LOD(_LtcData, s_linear_clamp_sampler, uv, LTC_DISNEY_DIFFUSE_MATRIX_INDEX, 0);
#endif
}
PreLightData GetPreLightData(float3 V, PositionInputs posInput, inout BSDFData bsdfData)
{
PreLightData preLightData;

//
// preLightData.iblPerceptualRoughness[]
// preLightData.vLayerEnergyCoeff[]
// preLightData.diffuseEnergy (just one term, computed ifdef VLAYERED_DIFFUSE_ENERGY_HACKED_TERM)
// preLightData.iblAnisotropy[] (only if anisotropy is enabled)
// If we're not using VLAYERED_RECOMPUTE_PERLIGHT we also have calculated

//
// Handle IBL + area light + multiscattering.
// Note: use the not modified by anisotropy iblPerceptualRoughness here.
// Here, we will fetch our actual FGD terms, see ComputeAdding for details: the F0 params
// will be replaced by our energy coefficients. Note that the way to do it depends on the
// formulation of ComputeAdding (with FGD fetches or only Fresnel terms).
// Also note that while the fetch directions for the light samples (IBL) are the ones
// at the top interface, for the FGD terms (in fact, for all angle dependent BSDF
// parametrization data), we need to use the actual interface angle a propagated direction
// would have. So, for the base layer, this is a refracted direction through the coat.
// Same for the top, but this is just NdotV.
// This is because we should really have fetched FGD with the tracked cti (cos theta incoming)
// at the bottom layer or top layer during ComputeAdding itself. We delayed the fetch after,
// because our ComputeAdding formulation is with "energy" coefficients calculated with a
// chain of Fresnel terms instead of a correct chain computed with the true FGD.
float baseLayerNdotV = PreLightData_GetBaseNdotVForFGD(bsdfData, preLightData, NdotV);
float diffuseFGDTmp; // unused, for coat layer FGD fetch
GetPreIntegratedFGDGGXAndDisneyDiffuse(NdotV[COAT_NORMAL_IDX],
preLightData.iblPerceptualRoughness[COAT_LOBE_IDX],
preLightData.vLayerEnergyCoeff[TOP_VLAYER_IDX],
preLightData.specularFGD[COAT_LOBE_IDX],
diffuseFGDTmp,
specularReflectivity[COAT_LOBE_IDX]);
GetPreIntegratedFGDGGXAndDisneyDiffuse(baseLayerNdotV,
preLightData.iblPerceptualRoughness[BASE_LOBEA_IDX],
preLightData.vLayerEnergyCoeff[BOTTOM_VLAYER_IDX],
preLightData.specularFGD[BASE_LOBEA_IDX],
diffuseFGD[0],
specularReflectivity[BASE_LOBEA_IDX]);
GetPreIntegratedFGDGGXAndDisneyDiffuse(baseLayerNdotV,
preLightData.iblPerceptualRoughness[BASE_LOBEB_IDX],
preLightData.vLayerEnergyCoeff[BOTTOM_VLAYER_IDX],
preLightData.specularFGD[BASE_LOBEB_IDX],
diffuseFGD[1],
specularReflectivity[BASE_LOBEB_IDX]);
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_ANISOTROPY))
{
// Note: there's no anisotropy possible on coat.

preLightData.TdotV = TdotV;
preLightData.BdotV = BdotV;
#endif
// For GGX aniso and IBL we have done an empirical (eye balled) approximation compare to the reference.
// We use a single fetch, and we stretch the normal to use based on various criteria.
// result are far away from the reference but better than nothing
// For positive anisotropy values: tangent = highlight stretch (anisotropy) direction, bitangent = grain (brush) direction.
float3 grainDirWS[2];
//grainDirWS[0] = (bsdfData.anisotropy >= 0.0) ? bsdfData.bitangentWS : bsdfData.tangentWS;
grainDirWS[0] = (preLightData.iblAnisotropy[0] >= 0.0) ? bsdfData.bitangentWS : bsdfData.tangentWS;
grainDirWS[1] = (preLightData.iblAnisotropy[1] >= 0.0) ? bsdfData.bitangentWS : bsdfData.tangentWS;
// Reduce stretching for (perceptualRoughness < 0.2).
float stretch[2];
stretch[0] = abs(preLightData.iblAnisotropy[0]) * saturate(5 * preLightData.iblPerceptualRoughness[BASE_LOBEA_IDX]);
stretch[1] = abs(preLightData.iblAnisotropy[1]) * saturate(5 * preLightData.iblPerceptualRoughness[BASE_LOBEB_IDX]);
// perceptualRoughness is use as input and output here
float3 outNormal;
float outPerceptualRoughness;
GetGGXAnisotropicModifiedNormalAndRoughness(bsdfData.bitangentWS, bsdfData.tangentWS, N[0], V, preLightData.iblAnisotropy[0], preLightData.iblPerceptualRoughness[BASE_LOBEA_IDX], outNormal, outPerceptualRoughness);
iblN[BASE_LOBEA_IDX] = outNormal;
preLightData.iblPerceptualRoughness[BASE_LOBEA_IDX] = outPerceptualRoughness;
GetGGXAnisotropicModifiedNormalAndRoughness(bsdfData.bitangentWS, bsdfData.tangentWS, N[0], V, preLightData.iblAnisotropy[1], preLightData.iblPerceptualRoughness[BASE_LOBEB_IDX], outNormal, outPerceptualRoughness);
iblN[BASE_LOBEB_IDX] = outNormal;
preLightData.iblPerceptualRoughness[BASE_LOBEB_IDX] = outPerceptualRoughness;
iblN[BASE_LOBEA_IDX] = GetAnisotropicModifiedNormal(grainDirWS[0], N[BASE_NORMAL_IDX], V, stretch[0]);
iblN[BASE_LOBEB_IDX] = GetAnisotropicModifiedNormal(grainDirWS[1], N[BASE_NORMAL_IDX], V, stretch[1]);
}
else
{

// IBL
// Handle IBL pre calculated data + GGX multiscattering energy loss compensation term
// Here, we will fetch our actual FGD terms, see ComputeAdding for details: the F0 params
// will be replaced by our energy coefficients. Note that the way to do it depends on the
// formulation of ComputeAdding (with FGD fetches or only Fresnel terms).
// Also note that while the fetch directions for the light samples (IBL) are the ones
// at the top interface, for the FGD terms (in fact, for all angle dependent BSDF
// parametrization data), we need to use the actual interface angle a propagated direction
// would have. So, for the base layer, this is a refracted direction through the coat.
// Same for the top, but this is just NdotV.
// This is because we should really have fetched FGD with the tracked cti (cos theta incoming)
// at the bottom layer or top layer during ComputeAdding itself. We delayed the fetch after,
// because our ComputeAdding formulation is with "energy" coefficients calculated with a
// chain of Fresnel terms instead of a correct chain computed with the true FGD.
float baseLayerNdotV = PreLightData_GetBaseNdotVForFGD(bsdfData, preLightData, NdotV);
float diffuseFGDTmp; // unused, for coat layer FGD fetch
GetPreIntegratedFGDGGXAndDisneyDiffuse(NdotV[COAT_NORMAL_IDX],
preLightData.iblPerceptualRoughness[COAT_LOBE_IDX],
preLightData.vLayerEnergyCoeff[TOP_VLAYER_IDX],
preLightData.specularFGD[COAT_LOBE_IDX],
diffuseFGDTmp,
specularReflectivity[COAT_LOBE_IDX]);
GetPreIntegratedFGDGGXAndDisneyDiffuse(baseLayerNdotV,
preLightData.iblPerceptualRoughness[BASE_LOBEA_IDX],
preLightData.vLayerEnergyCoeff[BOTTOM_VLAYER_IDX],
preLightData.specularFGD[BASE_LOBEA_IDX],
diffuseFGD[0],
specularReflectivity[BASE_LOBEA_IDX]);
GetPreIntegratedFGDGGXAndDisneyDiffuse(baseLayerNdotV,
preLightData.iblPerceptualRoughness[BASE_LOBEB_IDX],
preLightData.vLayerEnergyCoeff[BOTTOM_VLAYER_IDX],
preLightData.specularFGD[BASE_LOBEB_IDX],
diffuseFGD[1],
specularReflectivity[BASE_LOBEB_IDX]);
// This is a ad-hoc tweak to better match reference of anisotropic GGX.
// TODO: We need a better hack.
preLightData.iblPerceptualRoughness[BASE_LOBEA_IDX] *= saturate(1.2 - abs(preLightData.iblAnisotropy[0]));
preLightData.iblPerceptualRoughness[BASE_LOBEB_IDX] *= saturate(1.2 - abs(preLightData.iblAnisotropy[1]));
// Correction of reflected direction for better handling of rough material

iblN[0] = iblN[1] = N[0];
} // ...no anisotropy
float3 f0forCalculatingFGD = bsdfData.fresnel0;
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_IRIDESCENCE))
{
float topIor = 1.0; // Air on top, no coat.
if (bsdfData.iridescenceMask > 0.0)
{
preLightData.fresnelIridforCalculatingFGD = EvalIridescence(topIor, NdotV[0], bsdfData.iridescenceThickness, bsdfData.fresnel0);
f0forCalculatingFGD = lerp(f0forCalculatingFGD, preLightData.fresnelIridforCalculatingFGD, bsdfData.iridescenceMask);
}
}
// IBL
// Handle IBL pre calculated data + GGX multiscattering energy loss compensation term

bsdfData.fresnel0,
f0forCalculatingFGD,
preLightData.specularFGD[BASE_LOBEA_IDX],
diffuseFGD[0],
specularReflectivity[BASE_LOBEA_IDX]);

bsdfData.fresnel0,
f0forCalculatingFGD,
preLightData.specularFGD[BASE_LOBEB_IDX],
diffuseFGD[1],
specularReflectivity[BASE_LOBEB_IDX]);

preLightData.diffuseFGD = lerp(diffuseFGD[0], diffuseFGD[1], bsdfData.lobeMix);
#ifdef USE_DIFFUSE_LAMBERT_BRDF
// TODO: DiffuseFGD not done anyway, applied on bakeddiffuse:
// Area Lights:
PreLightData_SetupAreaLights(bsdfData, V, N, NdotV, preLightData);
return preLightData;
}

// This function require the 3 structure surfaceData, builtinData, bsdfData because it may require both the engine side data, and data that will not be store inside the gbuffer.
float3 GetBakedDiffuseLighting(SurfaceData surfaceData, BuiltinData builtinData, BSDFData bsdfData, PreLightData preLightData)
{
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_SUBSURFACE_SCATTERING)) // This test is static as it is done in GBuffer or forward pass, will be remove by compiler
{
bsdfData.diffuseColor = GetModifiedDiffuseColorForSSS(bsdfData); // local modification of bsdfData
}
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)
{

#endif
// Note bsdfData isn't modified outside of this function scope.
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_SUBSURFACE_SCATTERING)) // This test is static as it is done in GBuffer or forward pass, will be remove by compiler
{
// SSS Texturing mode can change albedo because diffuse maps can already contain some SSS too
bsdfData.diffuseColor = GetModifiedDiffuseColorForSSS(bsdfData); // local modification of bsdfData
}
return builtinData.bakeDiffuseLighting * surfaceData.ambientOcclusion * bsdfData.diffuseColor + builtinData.emissiveColor;
// preLightData.diffuseEnergy will be 1,1,1 if no vlayering or no VLAYERED_DIFFUSE_ENERGY_HACKED_TERM
return builtinData.bakeDiffuseLighting * preLightData.diffuseFGD * preLightData.diffuseEnergy * surfaceData.ambientOcclusion * bsdfData.diffuseColor + builtinData.emissiveColor;
}

// Note (see p9 eq(39)): if we don't recompute per light, we just reuse the IBL energy terms as the fresnel
// terms for our LdotH, too bad (similar to what we do with iridescence), along with the "wrongly" calculated
// energy.
// TODOENERGY:
// In any case, we should have used FGD terms (except for R12 at the start of the process) for the analytical
// light case, see comments at the top of ComputeAdding
#endif //...VLAYERED_RECOMPUTE_PERLIGHT

// TODO: Proper Fresnel
float3 F = F_Schlick(bsdfData.fresnel0, savedLdotH);
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_IRIDESCENCE))
{
float3 fresnelIridescent = preLightData.fresnelIridforCalculatingFGD;
#ifdef IRIDESCENCE_RECOMPUTE_PERLIGHT
float topIor = 1.0; // default air on top.
fresnelIridescent = EvalIridescence(topIor, savedLdotH, bsdfData.iridescenceThickness, bsdfData.fresnel0);
#endif
F = lerp(F, fresnelIridescent, bsdfData.iridescenceMask);
}
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_ANISOTROPY))
{
float TdotH, TdotL, BdotH, BdotL;

float3 diffuseTerm = Lambert() * max(0, NdotL[DNLV_BASE_IDX]);
#ifdef VLAYERED_DIFFUSE_ENERGY_HACKED_TERM
// TODOTODO: Energy when vlayered.
// TODOENERGYDIFFUSE: Energy when vlayered.
// Controlled by ifdef VLAYERED_DIFFUSE_ENERGY_HACKED_TERM
// since preLightData.diffuseEnergy == float3(1,1,1) when not defined
diffuseTerm *= preLightData.diffuseEnergy;
}
#endif

DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
float3 N; float unclampedNdotV;
float3 L = -lightData.forward;
float3 N;
float unclampedNdotV;
float3 L = -lightData.forward; // Lights point backward in Unity
float NdotL = dot(N, L);
float NdotL = dot(N, L);
// For shadow attenuation (ie receiver bias), always use the geometric normal
float3 shadowBiasNormal = bsdfData.geomNormalWS;

float NdotV = ClampNdotV(unclampedNdotV);
float LdotV = dot(L, V);
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
// TODOENERGYDIFFUSE:
//
// With coat, will need a diffuse energy term here. eg preLightData.diffuseEnergyTransmitted, from something like e_T0i,
// but we would need to balance it with the term used from e_Ti0 == preLightData.diffuseEnergy, as
// the term as computed with VLAYERED_DIFFUSE_ENERGY_HACKED_TERM, assumes that all light that is not (Fresnel) reflected
// at the bottom interface thus corresponds to diffuse light.
// If we use the same term, we could just apply it in the end to diffuse light since coat can't produce diffuse lighting,
// so diffuse lighting from the base interface should all have the term applied. (Then, we would need to make sure the
// energy term is separate from diffuseFGD.) But the terms are not the same:
//
// Even without energy conservation, preLightData.diffuseEnergyTransmitted should still != preLightData.diffuseEnergy
// as although statistics T12 == T21 for the interface, the stack has terms e_T0i != e_Ti0
lighting.diffuse += EvaluateTransmission(bsdfData, transmittance, NdotL, NdotV, LdotV, attenuation * lightData.diffuseScale);
}

DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
float3 lightToSample = posInput.positionWS - lightData.positionWS;
int lightType = lightData.lightType;
float3 lightToSample;
distances.w = dot(lightToSample, lightData.forward);
if (lightType == GPULIGHTTYPE_PROJECTOR_BOX)
{
L = -lightData.forward;
distances.xyz = 1; // No distance or angle attenuation
}
else
{
float3 unL = -lightToSample;
float distSq = dot(unL, unL);
float distRcp = rsqrt(distSq);
float dist = distSq * distRcp;
L = unL * distRcp;
distances.xyz = float3(dist, distSq, distRcp);
}
GetPunctualLightVectors(posInput.positionWS, lightData, L, lightToSample, distances);
float3 N; float unclampedNdotV;
EvaluateBSDF_GetNormalUnclampedNdotV(bsdfData, preLightData, V, N, unclampedNdotV);

float3 color;
float attenuation;
// For shadow attenuation (ie receiver bias), always use the geometric normal:
EvaluateLight_Punctual(lightLoopContext, posInput, lightData, bakeLightingData, shadowBiasNormal, L,
lightToSample, distances, color, attenuation);

float NdotV = ClampNdotV(unclampedNdotV);
float LdotV = dot(L, V);
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
// TODOENERGYDIFFUSE
lighting.diffuse += EvaluateTransmission(bsdfData, transmittance, NdotL, NdotV, LdotV, attenuation * lightData.diffuseScale);
}

return lighting;
}
// NEWLITTODO: For a refence rendering option for area light, like LIT_DISPLAY_REFERENCE_AREA option in eg EvaluateBSDF_<area light type> :
// NEWLITTODO: For a refence rendering option for area light, like STACK_LIT_DISPLAY_REFERENCE_AREA option in eg EvaluateBSDF_<area light type> :
//#include "LitReference.hlsl"
//-----------------------------------------------------------------------------

DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
//NEWLITTODO
float3 positionWS = posInput.positionWS;
#ifdef STACK_LIT_DISPLAY_REFERENCE_AREA
// TODO This ref doesn't handle the StackLit model
IntegrateBSDF_LineRef(V, positionWS, preLightData, lightData, bsdfData,
lighting.diffuse, lighting.specular);
#else
float len = lightData.size.x;
float3 T = lightData.right;
float3 unL = lightData.positionWS - positionWS;
// Pick the major axis of the ellipsoid.
float3 axis = lightData.right;
// We define the ellipsoid s.t. r1 = (r + len / 2), r2 = r3 = r.
// TODO: This could be precomputed.
float radius = rsqrt(lightData.rangeAttenuationScale); // // rangeAttenuationScale is inverse Square Radius
float invAspectRatio = saturate(radius / (radius + (0.5 * len)));
// Compute the light attenuation.
float intensity = EllipsoidalDistanceAttenuation(unL, lightData.rangeAttenuationScale, lightData.rangeAttenuationBias,
axis, invAspectRatio);
// Terminate if the shaded point is too far away.
if (intensity == 0.0)
return lighting;
lightData.diffuseScale *= intensity;
lightData.specularScale *= intensity;
// Translate the light s.t. the shaded point is at the origin of the coordinate system.
lightData.positionWS -= positionWS;
// TODO: some of this could be precomputed.
float3 P1 = lightData.positionWS - T * (0.5 * len);
float3 P2 = lightData.positionWS + T * (0.5 * len);
// Rotate the endpoints into the local coordinate system.
float3 localP1 = mul(P1, transpose(preLightData.orthoBasisViewNormal[BASE_NORMAL_IDX]));
float3 localP2 = mul(P2, transpose(preLightData.orthoBasisViewNormal[BASE_NORMAL_IDX]));
// Compute the binormal in the local coordinate system.
float3 B = normalize(cross(localP1, localP2));
float ltcValue;
// Evaluate the diffuse part
ltcValue = LTCEvaluate(localP1, localP2, B, preLightData.ltcTransformDiffuse);
ltcValue *= lightData.diffuseScale;
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse = preLightData.diffuseFGD * preLightData.diffuseEnergy * ltcValue;
UNITY_BRANCH if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION))
{
// Flip the view vector and the normal. The bitangent stays the same.
float3x3 flipMatrix = float3x3(-1, 0, 0,
0, 1, 0,
0, 0, -1);
// Use the Lambertian approximation for performance reasons.
// The matrix multiplication should not generate any extra ALU on GCN.
// TODO: double evaluation is very inefficient! This is a temporary solution.
ltcValue = LTCEvaluate(localP1, localP2, B, mul(flipMatrix, k_identity3x3));
ltcValue *= lightData.diffuseScale;
// TODOENERGYDIFFUSE: In Lit with Lambert, there's no diffuseFGD, it is one. In our case, we also
// need a diffuse energy term when vlayered. See preLightData.diffuseEnergyTransmitted
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse += bsdfData.transmittance * ltcValue;
}
// Evaluate the specular lobes for the stack
IF_DEBUG( if ( _DebugLobeMask.y != 0.0) )
{
ltcValue = LTCEvaluate(localP1, localP2, B, preLightData.ltcTransformSpecular[BASE_LOBEA_IDX]);
lighting.specular += preLightData.specularFGD[BASE_LOBEA_IDX] * ltcValue;
}
IF_DEBUG( if ( _DebugLobeMask.z != 0.0) )
{
ltcValue = LTCEvaluate(localP1, localP2, B, preLightData.ltcTransformSpecular[BASE_LOBEB_IDX]);
lighting.specular += preLightData.specularFGD[BASE_LOBEB_IDX] * ltcValue;
}
if (IsVLayeredEnabled(bsdfData))
{
if (IsCoatNormalMapEnabled(bsdfData))
{
// Rotate the endpoints into the local coordinate system using the coat normal.
localP1 = mul(P1, transpose(preLightData.orthoBasisViewNormal[COAT_NORMAL_IDX]));
localP2 = mul(P2, transpose(preLightData.orthoBasisViewNormal[COAT_NORMAL_IDX]));
// Reompute the binormal in the local coordinate system.
B = normalize(cross(localP1, localP2));
}
IF_DEBUG( if ( _DebugLobeMask.x != 0.0) )
{
ltcValue = LTCEvaluate(localP1, localP2, B, preLightData.ltcTransformSpecular[COAT_LOBE_IDX]);
lighting.specular += preLightData.specularFGD[COAT_LOBE_IDX] * ltcValue;
}
}
lighting.specular *= lightData.specularScale;
// Save ALU by applying 'lightData.color' only once.
lighting.diffuse *= lightData.color;
lighting.specular *= lightData.color;
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)
{
// Only lighting, not BSDF
// Apply area light on lambert then multiply by PI to cancel Lambert
lighting.diffuse = LTCEvaluate(localP1, localP2, B, k_identity3x3);
lighting.diffuse *= PI * lightData.diffuseScale;
}
#endif
#endif // STACK_LIT_DISPLAY_REFERENCE_AREA
// EvaluateBSDF_Area - Approximation with Linearly Transformed Cosines
// EvaluateBSDF_Rect - Approximation with Linearly Transformed Cosines
//-----------------------------------------------------------------------------
// #define ELLIPSOIDAL_ATTENUATION

DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
//NEWLITTODO
float3 positionWS = posInput.positionWS;
#ifdef STACK_LIT_DISPLAY_REFERENCE_AREA
IntegrateBSDF_AreaRef(V, positionWS, preLightData, lightData, bsdfData,
lighting.diffuse, lighting.specular);
#else
float3 unL = lightData.positionWS - positionWS;
if (dot(lightData.forward, unL) >= 0.0001)
{
// The light is back-facing.
return lighting;
}
// Rotate the light direction into the light space.
float3x3 lightToWorld = float3x3(lightData.right, lightData.up, -lightData.forward);
unL = mul(unL, transpose(lightToWorld));
// TODO: This could be precomputed.
float halfWidth = lightData.size.x * 0.5;
float halfHeight = lightData.size.y * 0.5;
// Define the dimensions of the attenuation volume.
// TODO: This could be precomputed.
float radius = rsqrt(lightData.rangeAttenuationScale); // rangeAttenuationScale is inverse Square Radius
float3 invHalfDim = rcp(float3(radius + halfWidth,
radius + halfHeight,
radius));
// Compute the light attenuation.
#ifdef ELLIPSOIDAL_ATTENUATION
// The attenuation volume is an axis-aligned ellipsoid s.t.
// r1 = (r + w / 2), r2 = (r + h / 2), r3 = r.
float intensity = EllipsoidalDistanceAttenuation(unL, invHalfDim);
#else
// The attenuation volume is an axis-aligned box s.t.
// hX = (r + w / 2), hY = (r + h / 2), hZ = r.
float intensity = BoxDistanceAttenuation(unL, invHalfDim);
#endif
// Terminate if the shaded point is too far away.
if (intensity == 0.0)
return lighting;
lightData.diffuseScale *= intensity;
lightData.specularScale *= intensity;
// Translate the light s.t. the shaded point is at the origin of the coordinate system.
lightData.positionWS -= positionWS;
float4x3 lightVerts;
// TODO: some of this could be precomputed.
lightVerts[0] = lightData.positionWS + lightData.right * halfWidth + lightData.up * halfHeight;
lightVerts[1] = lightData.positionWS + lightData.right * halfWidth + lightData.up * -halfHeight;
lightVerts[2] = lightData.positionWS + lightData.right * -halfWidth + lightData.up * -halfHeight;
lightVerts[3] = lightData.positionWS + lightData.right * -halfWidth + lightData.up * halfHeight;
// Rotate the endpoints into the local coordinate system.
float4x3 localLightVerts = mul(lightVerts, transpose(preLightData.orthoBasisViewNormal[BASE_NORMAL_IDX]));
float ltcValue;
// Evaluate the diffuse part
// Polygon irradiance in the transformed configuration.
ltcValue = PolygonIrradiance(mul(localLightVerts, preLightData.ltcTransformDiffuse));
ltcValue *= lightData.diffuseScale;
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse = preLightData.diffuseFGD * preLightData.diffuseEnergy * ltcValue;
UNITY_BRANCH if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION))
{
// Flip the view vector and the normal. The bitangent stays the same.
float3x3 flipMatrix = float3x3(-1, 0, 0,
0, 1, 0,
0, 0, -1);
// Use the Lambertian approximation for performance reasons.
// The matrix multiplication should not generate any extra ALU on GCN.
float3x3 ltcTransform = mul(flipMatrix, k_identity3x3);
// Polygon irradiance in the transformed configuration.
// TODO: double evaluation is very inefficient! This is a temporary solution.
ltcValue = PolygonIrradiance(mul(localLightVerts, ltcTransform));
ltcValue *= lightData.diffuseScale;
// TODOENERGYDIFFUSE: In Lit with Lambert, there's no diffuseFGD, it is one. In our case, we also
// need a diffuse energy term when vlayered. See preLightData.diffuseEnergyTransmitted
// We use diffuse lighting for accumulation since it is going to be blurred during the SSS pass.
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().
lighting.diffuse += bsdfData.transmittance * ltcValue;
}
// Evaluate the specular lobes for the stack
IF_DEBUG( if ( _DebugLobeMask.y != 0.0) )
{
// Polygon irradiance in the transformed configuration.
ltcValue = PolygonIrradiance(mul(localLightVerts, preLightData.ltcTransformSpecular[BASE_LOBEA_IDX]));
lighting.specular += preLightData.specularFGD[BASE_LOBEA_IDX] * ltcValue;
}
IF_DEBUG( if ( _DebugLobeMask.z != 0.0) )
{
ltcValue = PolygonIrradiance(mul(localLightVerts, preLightData.ltcTransformSpecular[BASE_LOBEB_IDX]));
lighting.specular += preLightData.specularFGD[BASE_LOBEB_IDX] * ltcValue;
}
if (IsVLayeredEnabled(bsdfData))
{
if (IsCoatNormalMapEnabled(bsdfData))
{
localLightVerts = mul(lightVerts, transpose(preLightData.orthoBasisViewNormal[COAT_NORMAL_IDX]));
}
IF_DEBUG( if ( _DebugLobeMask.x != 0.0) )
{
ltcValue = PolygonIrradiance(mul(localLightVerts, preLightData.ltcTransformSpecular[COAT_LOBE_IDX]));
lighting.specular += preLightData.specularFGD[COAT_LOBE_IDX] * ltcValue;
}
}
lighting.specular *= lightData.specularScale;
// Save ALU by applying 'lightData.color' only once.
lighting.diffuse *= lightData.color;
lighting.specular *= lightData.color;
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)
{
// Only lighting, not BSDF
// Apply area light on lambert then multiply by PI to cancel Lambert
lighting.diffuse = PolygonIrradiance(mul(localLightVerts, k_identity3x3));
lighting.diffuse *= PI * lightData.diffuseScale;
}
#endif
#endif // STACK_LIT_DISPLAY_REFERENCE_AREA
return lighting;
}

float3 positionWS = posInput.positionWS;
float weight = 0.0;
#ifdef LIT_DISPLAY_REFERENCE_IBL
#ifdef STACK_LIT_DISPLAY_REFERENCE_IBL
envLighting = IntegrateSpecularGGXIBLRef(lightLoopContext, V, preLightData, lightData, bsdfData);

for( i = 0; i < TOTAL_NB_LOBES; ++i)
{
//TOTO not needed anymore, single R
R[i] = preLightData.iblR[i];
tempWeight[i] = 1.0;
}

weight /= TOTAL_NB_LOBES;
weight = tempWeight[1];
#endif // LIT_DISPLAY_REFERENCE_IBL
#endif // STACK_LIT_DISPLAY_REFERENCE_IBL
UpdateLightingHierarchyWeights(hierarchyWeight, weight);
envLighting *= weight * lightData.multiplier;

// Use GTAOMultiBounce approximation for ambient occlusion (allow to get a tint from the baseColor)
//GetScreenSpaceAmbientOcclusionMultibounce(posInput.positionSS, preLightData.NdotV, lerp(bsdfData.perceptualRoughnessA, bsdfData.perceptualRoughnessB, bsdfData.lobeMix), bsdfData.ambientOcclusion, 1.0, bsdfData.diffuseColor, bsdfData.fresnel0, aoFactor);
GetScreenSpaceAmbientOcclusionMultibounce(posInput.positionSS, unclampedNdotV, lerp(bsdfData.perceptualRoughnessA, bsdfData.perceptualRoughnessB, bsdfData.lobeMix), bsdfData.ambientOcclusion, 1.0, bsdfData.diffuseColor, bsdfData.fresnel0, aoFactor);
ApplyAmbientOcclusionFactor(aoFactor, bakeLightingData, lighting);
// Subsurface scattering mode

125
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLit.shader


_MetallicMapUV("Metallic Map UV", Float) = 0.0
_MetallicMapUVLocal("Metallic Map UV Local", Float) = 0.0
_MetallicMapChannel("Metallic Map Channel", Float) = 0.0
_MetallicMapChannelMask("Metallic Map Channel Mask", Vector) = (1, 0, 0, 0)
_MetallicRemap("Metallic Remap", Vector) = (0, 1, 0, 0)
[HideInInspector] _MetallicRange("Metallic Range", Vector) = (0, 1, 0, 0)
[HideInInspector] _MetallicMapChannelMask("Metallic Map Channel Mask", Vector) = (1, 0, 0, 0)
_MetallicMapRemap("Metallic Remap", Vector) = (0, 1, 0, 0)
[HideInInspector] _MetallicMapRange("Metallic Range", Vector) = (0, 1, 0, 0)
_DielectricIor("DielectricIor IOR", Range(1.0, 2.5)) = 1.5

_SmoothnessAUseMap("SmoothnessA Use Map", Float) = 0
_SmoothnessAMapUV("SmoothnessA Map UV", Float) = 0.0
_SmoothnessAMapUVLocal("_SmoothnessA Map UV Local", Float) = 0.0
_SmoothnessAMapUVLocal("SmoothnessA Map UV Local", Float) = 0.0
_SmoothnessAMapChannelMask("SmoothnessA Map Channel Mask", Vector) = (1, 0, 0, 0)
_SmoothnessARemap("SmoothnessA Remap", Vector) = (0, 1, 0, 0)
[ToggleUI] _SmoothnessARemapInverted("Invert SmoothnessA Remap", Float) = 0.0
[HideInInspector] _SmoothnessARange("SmoothnessA Range", Vector) = (0, 1, 0, 0)
[HideInInspector] _SmoothnessAMapChannelMask("SmoothnessA Map Channel Mask", Vector) = (1, 0, 0, 0)
_SmoothnessAMapRemap("SmoothnessA Remap", Vector) = (0, 1, 0, 0)
[ToggleUI] _SmoothnessAMapRemapInverted("Invert SmoothnessA Remap", Float) = 0.0
[HideInInspector] _SmoothnessAMapRange("SmoothnessA Range", Vector) = (0, 1, 0, 0)
[ToggleUI] _EnableDualSpecularLobe("Enable Dual Specular Lobe", Float) = 0.0 // UI only
[HideInInspector] _SmoothnessBMapShow("SmoothnessB Map Show", Float) = 0

_SmoothnessBMapUV("SmoothnessB Map UV", Float) = 0.0
_SmoothnessAMapUVLocal("_SmoothnessB Map UV Local", Float) = 0.0
_SmoothnessBMapChannel("SmoothnessB Map Channel", Float) = 0.0
_SmoothnessBMapChannelMask("SmoothnessB Map Channel Mask", Vector) = (1, 0, 0, 0)
_SmoothnessBRemap("SmoothnessB Remap", Vector) = (0, 1, 0, 0)
[ToggleUI] _SmoothnessBRemapInverted("Invert SmoothnessB Remap", Float) = 0.0
[HideInInspector] _SmoothnessBRange("SmoothnessB Range", Vector) = (0, 1, 0, 0)
[HideInInspector] _SmoothnessBMapChannelMask("SmoothnessB Map Channel Mask", Vector) = (1, 0, 0, 0)
_SmoothnessBMapRemap("SmoothnessB Remap", Vector) = (0, 1, 0, 0)
[ToggleUI] _SmoothnessBMapRemapInverted("Invert SmoothnessB Remap", Float) = 0.0
[HideInInspector] _SmoothnessBMapRange("SmoothnessB Range", Vector) = (0, 1, 0, 0)
_LobeMix("Lobe Mix", Range(0.0, 1.0)) = 0
[ToggleUI] _VlayerRecomputePerLight("Vlayer Recompute Per Light", Float) = 0.0 // UI only

_AnisotropyMapUV("Anisotropy Map UV", Float) = 0.0
_AnisotropyMapUVLocal("Anisotropy Map UV Local", Float) = 0.0
_AnisotropyMapChannel("Anisotropy Map Channel", Float) = 0.0
_AnisotropyMapChannelMask("Anisotropy Map Channel Mask", Vector) = (1, 0, 0, 0)
_AnisotropyRemap("Anisotropy Remap", Vector) = (0, 1, 0, 0)
[HideInInspector] _AnisotropyRange("Anisotropy Range", Vector) = (0, 1, 0, 0)
[HideInInspector] _AnisotropyMapChannelMask("Anisotropy Map Channel Mask", Vector) = (1, 0, 0, 0)
_AnisotropyMapRemap("Anisotropy Remap", Vector) = (0, 1, 0, 0)
[HideInInspector] _AnisotropyMapRange("Anisotropy Range", Vector) = (0, 1, 0, 0)
[ToggleUI] _EnableCoat("Enable Coat", Float) = 0.0 // UI only
[HideInInspector] _CoatSmoothnessMapShow("CoatSmoothness Show", Float) = 0

_CoatSmoothnessMapUV("CoatSmoothness Map UV", Float) = 0.0
_CoatSmoothnessMapUVLocal("CoatSmoothness Map UV Local", Float) = 0.0
_CoatSmoothnessMapChannel("CoatSmoothness Map Channel", Float) = 0.0
_CoatSmoothnessMapChannelMask("CoatSmoothness Map Channel Mask", Vector) = (1, 0, 0, 0)
_CoatSmoothnessRemap("CoatSmoothness Remap", Vector) = (0, 1, 0, 0)
[ToggleUI] _CoatSmoothnessRemapInverted("Invert CoatSmoothness Remap", Float) = 0.0
[HideInInspector] _CoatSmoothnessRange("CoatSmoothness Range", Vector) = (0, 1, 0, 0)
[HideInInspector] _CoatSmoothnessMapChannelMask("CoatSmoothness Map Channel Mask", Vector) = (1, 0, 0, 0)
_CoatSmoothnessMapRemap("CoatSmoothness Remap", Vector) = (0, 1, 0, 0)
[ToggleUI] _CoatSmoothnessMapRemapInverted("Invert CoatSmoothness Remap", Float) = 0.0
[HideInInspector] _CoatSmoothnessMapRange("CoatSmoothness Range", Vector) = (0, 1, 0, 0)
_CoatIor("Coat IOR", Range(1.0001, 2.0)) = 1.5
_CoatThickness("Coat Thickness", Range(0.0, 0.99)) = 0.0

_NormalMap("NormalMap", 2D) = "bump" {} // Tangent space normal map
_NormalMapUV("NormalMapUV", Float) = 0.0
_NormalMapUVLocal("NormalMapUV Local", Float) = 0.0
_NormalMapObjSpace("NormalMapUV Local", Float) = 0.0
_NormalMapObjSpace("NormalMapObjSpace", Float) = 0.0
_NormalScale("Normal Scale", Range(0.0, 2.0)) = 1
[HideInInspector] _AmbientOcclusionMapShow("AmbientOcclusion Map Show", Float) = 0

_AmbientOcclusionMapUV("AmbientOcclusion Map UV", Float) = 0.0
_AmbientOcclusionMapUVLocal("AmbientOcclusion Map UV Local", Float) = 0.0
_AmbientOcclusionMapChannel("AmbientOcclusion Map Channel", Float) = 0.0
_AmbientOcclusionMapChannelMask("AmbientOcclusion Map Channel Mask", Vector) = (1, 0, 0, 0)
_AmbientOcclusionRemap("AmbientOcclusion Remap", Vector) = (0, 1, 0, 0)
[HideInInspector] _AmbientOcclusionRange("AmbientOcclusion Range", Vector) = (0, 1, 0, 0)
[HideInInspector] _AmbientOcclusionMapChannelMask("AmbientOcclusion Map Channel Mask", Vector) = (1, 0, 0, 0)
_AmbientOcclusionMapRemap("AmbientOcclusion Remap", Vector) = (0, 1, 0, 0)
[HideInInspector] _AmbientOcclusionMapRange("AmbientOcclusion Range", Vector) = (0, 1, 0, 0)
[HideInInspector] _EmissiveColorMapShow("Emissive Color Map Show", Float) = 0.0
[HDR] _EmissiveColor("EmissiveColor", Color) = (0, 0, 0)

_SubsurfaceMaskMapUV("Subsurface Mask Map UV", Float) = 0.0
_SubsurfaceMaskMapUVLocal("Subsurface Mask UV Local", Float) = 0.0
_SubsurfaceMaskMapChannel("Subsurface Mask Map Channel", Float) = 0.0
_SubsurfaceMaskMapChannelMask("Subsurface Mask Map Channel Mask", Vector) = (1, 0, 0, 0)
_SubsurfaceMaskRemap("Subsurface Mask Remap", Vector) = (0, 1, 0, 0)
[HideInInspector] _SubsurfaceMaskRange("Subsurface Mask Range", Vector) = (0, 1, 0, 0)
[HideInInspector] _SubsurfaceMaskMapChannelMask("Subsurface Mask Map Channel Mask", Vector) = (1, 0, 0, 0)
_SubsurfaceMaskMapRemap("Subsurface Mask Remap", Vector) = (0, 1, 0, 0)
[HideInInspector] _SubsurfaceMaskMapRange("Subsurface Mask Range", Vector) = (0, 1, 0, 0)
[ToggleUI] _EnableTransmission("Enable Transmission", Float) = 0.0
[HideInInspector] _ThicknessMapShow("Thickness Show", Float) = 0

_ThicknessMapUV("Thickness Map UV", Float) = 0.0
_ThicknessMapUVLocal("Thickness Map UV Local", Float) = 0.0
_ThicknessMapChannel("Thickness Map Channel", Float) = 0.0
_ThicknessMapChannelMask("Thickness Map Channel Mask", Vector) = (1, 0, 0, 0)
_ThicknessRemap("Thickness Remap", Vector) = (0, 1, 0, 0)
[ToggleUI] _ThicknessRemapInverted("Invert Thickness Remap", Float) = 0.0
[HideInInspector] _ThicknessRange("Thickness Range", Vector) = (0, 1, 0, 0)
[HideInInspector] _ThicknessMapChannelMask("Thickness Map Channel Mask", Vector) = (1, 0, 0, 0)
_ThicknessMapRemap("Thickness Remap", Vector) = (0, 1, 0, 0)
[ToggleUI] _ThicknessMapRemapInverted("Invert Thickness Remap", Float) = 0.0
[HideInInspector] _ThicknessMapRange("Thickness Range", Vector) = (0, 1, 0, 0)
_IridescenceIor("Coat IOR", Range(1.0, 2.0)) = 1.5
_IridescenceThickness("_IridescenceThickness", Range(0.0, 1.0)) = 0.0
_IridescenceThicknessMap("IridescenceThickness Color Map", 2D) = "black" {}
_IridescenceIor("TopIOR over iridescent layer", Range(1.0, 2.0)) = 1.5
[HideInInspector] _IridescenceThicknessMapShow("IridescenceThickness Map Show", Float) = 0
_IridescenceThickness("IridescenceThickness", Range(0.0, 1.0)) = 0.0
_IridescenceThicknessMap("IridescenceThickness Map", 2D) = "black" {}
_IridescenceThicknessMapChannel("IridescenceThickness Mask Map Channel", Float) = 0.0
_IridescenceThicknessMapChannelMask("IridescenceThickness Mask Map Channel Mask", Vector) = (1, 0, 0, 0)
[HideInInspector] _IridescenceThicknessRange("IridescenceThickness Range", Vector) = (0, 1, 0, 0)
_IridescenceThicknessMapChannel("IridescenceThickness Map Channel", Float) = 0.0
[HideInInspector] _IridescenceThicknessMapChannelMask("IridescenceThickness Map Channel Mask", Vector) = (1, 0, 0, 0)
_IridescenceThicknessMapRemap("IridescenceThickness Remap", Vector) = (0, 1, 0, 0)
[ToggleUI] _IridescenceThicknessMapRemapInverted("Invert IridescenceThickness Remap", Float) = 0.0
[HideInInspector] _IridescenceThicknessMapRange("IridescenceThickness Range", Vector) = (0, 1, 0, 0)
[HideInInspector] _IridescenceMaskMapShow("Iridescence Mask Map Show", Float) = 0
_IridescenceMask("Iridescence Mask", Range(0.0, 1.0)) = 1.0
_IridescenceMaskMap("Iridescence Mask Map", 2D) = "black" {}
_IridescenceMaskUseMap("Iridescence Mask Use Map", Float) = 0
_IridescenceMaskMapUV("Iridescence Mask Map UV", Float) = 0.0
_IridescenceMaskMapUVLocal("Iridescence Mask UV Local", Float) = 0.0
_IridescenceMaskMapChannel("Iridescence Mask Map Channel", Float) = 0.0
[HideInInspector] _IridescenceMaskMapChannelMask("Iridescence Mask Map Channel Mask", Vector) = (1, 0, 0, 0)
_IridescenceMaskMapRemap("Iridescence Mask Remap", Vector) = (0, 1, 0, 0)
[HideInInspector] _IridescenceMaskMapRange("Iridescence Mask Range", Vector) = (0, 1, 0, 0)
// Detail map (mask, normal, smoothness)
[ToggleUI] _EnableDetails("Enable Details", Float) = 0.0
[HideInInspector] _DetailMaskMapShow("DetailMask Map Show", Float) = 0
_DetailMaskMap("DetailMask Map", 2D) = "white" {}
_DetailMaskMapUV("DetailMask Map UV", Float) = 0.0
_DetailMaskMapUVLocal("DetailMask Map UV Local", Float) = 0.0
_DetailMaskMapChannel("DetailMask Map Channel", Float) = 0.0
[HideInInspector] _DetailMaskMapChannelMask("DetailSmoothness Map Channel Mask", Vector) = (1, 0, 0, 0)
[HideInInspector] _DetailNormalMapShow("DetailNormalMap Show", Float) = 0.0
_DetailNormalMap("DetailNormalMap", 2D) = "bump" {} // Tangent space normal map
_DetailNormalMapUV("DetailNormalMapUV", Float) = 0.0
_DetailNormalMapUVLocal("DetailNormalMapUV Local", Float) = 0.0
_DetailNormalScale("DetailNormal Scale", Range(0.0, 2.0)) = 1
[HideInInspector] _DetailSmoothnessMapShow("DetailSmoothness Map Show", Float) = 0
_DetailSmoothnessMap("DetailSmoothness Map", 2D) = "grey" {} // Neutral is 0.5 for detail map
_DetailSmoothnessMapUV("DetailSmoothness Map UV", Float) = 0.0
_DetailSmoothnessMapUVLocal("DetailSmoothness Map UV Local", Float) = 0.0
_DetailSmoothnessMapChannel("DetailSmoothness Map Channel", Float) = 0.0
[HideInInspector] _DetailSmoothnessMapChannelMask("DetailSmoothness Map Channel Mask", Vector) = (1, 0, 0, 0)
_DetailSmoothnessMapRemap("DetailSmoothness Remap", Vector) = (0, 1, 0, 0)
[ToggleUI] _DetailSmoothnessMapRemapInverted("Invert SmoothnessA Remap", Float) = 0.0
[HideInInspector] _DetailSmoothnessMapRange("DetailSmoothness Range", Vector) = (0, 1, 0, 0)
_DetailSmoothnessScale("DetailSmoothness Scale", Range(0.0, 2.0)) = 1
// Distortion
_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}
[ToggleUI] _DistortionEnable("Enable Distortion", Float) = 0.0
[ToggleUI] _DistortionOnly("Distortion Only", Float) = 0.0

// Sections show values.
[HideInInspector] _MaterialFeaturesShow("_MaterialFeaturesShow", Float) = 1.0
[HideInInspector] _StandardShow("_StandardShow", Float) = 0.0
[HideInInspector] _DetailsShow("_DetailsShow", Float) = 0.0
[HideInInspector] _EmissiveShow("_EmissiveShow", Float) = 0.0
[HideInInspector] _CoatShow("_CoatShow", Float) = 0.0
[HideInInspector] _DebugShow("_DebugShow", Float) = 0.0

#pragma shader_feature _ALPHATEST_ON
#pragma shader_feature _DOUBLESIDED_ON
#pragma shader_feature _NORMALMAP_TANGENT_SPACE
#pragma shader_feature _USE_DETAILMAP
#pragma shader_feature _USE_UV2
#pragma shader_feature _USE_UV3
#pragma shader_feature _USE_TRIPLANAR

#pragma multi_compile _ DEBUG_DISPLAY
//NEWLITTODO
//#pragma multi_compile _ LIGHTMAP_ON
//#pragma multi_compile _ DIRLIGHTMAP_COMBINED
//#pragma multi_compile _ DYNAMICLIGHTMAP_ON
//#pragma multi_compile _ SHADOWS_SHADOWMASK
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ SHADOWS_SHADOWMASK
// #include "../../Lighting/Forward.hlsl" : nothing left in there.
//#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS

73
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLitData.hlsl


void InitializeMappingData(FragInputs input, out TextureUVMapping uvMapping)
{
float3 position = GetAbsolutePositionWS(input.positionWS);
float2 uvXZ;
float2 uvXY;
float2 uvZY;

uvMapping.texcoords[TEXCOORD_INDEX_UV3][0] = uvMapping.texcoords[TEXCOORD_INDEX_UV3][1] = input.texCoord3.xy;
// planar/triplanar
GetTriplanarCoordinate(position, uvXZ, uvXY, uvZY);
GetTriplanarCoordinate(GetAbsolutePositionWS(input.positionRWS), uvXZ, uvXY, uvZY);
position = TransformWorldToObject(position);
GetTriplanarCoordinate(position, uvXZ, uvXY, uvZY);
GetTriplanarCoordinate(TransformWorldToObject(input.positionRWS), uvXZ, uvXY, uvZY);
uvMapping.texcoords[TEXCOORD_INDEX_PLANAR_XY][1] = uvXY;
uvMapping.texcoords[TEXCOORD_INDEX_PLANAR_YZ][1] = uvZY;
uvMapping.texcoords[TEXCOORD_INDEX_PLANAR_ZX][1] = uvXZ;

uvMapping.vertexTangentWS[0] = input.worldToTangent[0];
uvMapping.vertexBitangentWS[0] = input.worldToTangent[1];
float3 dPdx = ddx_fine(input.positionWS);
float3 dPdy = ddy_fine(input.positionWS);
float3 dPdx = ddx_fine(input.positionRWS);
float3 dPdy = ddy_fine(input.positionRWS);
float3 sigmaX = dPdx - dot(dPdx, vertexNormalWS) * vertexNormalWS;
float3 sigmaY = dPdy - dot(dPdy, vertexNormalWS) * vertexNormalWS;

}
#define SAMPLE_TEXTURE2D_SCALE_BIAS(name) SampleTexture2DTriplanarScaleBias(name, sampler##name, name##UV, name##UVLocal, name##_ST, uvMapping)
#define SAMPLE_TEXTURE2D_NORMAL_SCALE_BIAS(name, scale) SampleTexture2DTriplanarNormalScaleBias(name, sampler##name, name##UV, name##UVLocal, name##_ST, name##ObjSpace, uvMapping, scale)
#define SAMPLE_TEXTURE2D_NORMAL_SCALE_BIAS(name, scale, objSpace) SampleTexture2DTriplanarNormalScaleBias(name, sampler##name, name##UV, name##UVLocal, name##_ST, objSpace, uvMapping, scale)
//-----------------------------------------------------------------------------
// GetSurfaceAndBuiltinData

// Standard
surfaceData.baseColor = SAMPLE_TEXTURE2D_SCALE_BIAS(_BaseColorMap).rgb * _BaseColor.rgb;
float4 gradient = SAMPLE_TEXTURE2D_NORMAL_SCALE_BIAS(_NormalMap, _NormalScale);
float4 gradient = SAMPLE_TEXTURE2D_NORMAL_SCALE_BIAS(_NormalMap, _NormalScale, _NormalMapObjSpace);
surfaceData.perceptualSmoothnessA = lerp(_SmoothnessARange.x, _SmoothnessARange.y, surfaceData.perceptualSmoothnessA);
surfaceData.perceptualSmoothnessA = lerp(_SmoothnessAMapRange.x, _SmoothnessAMapRange.y, surfaceData.perceptualSmoothnessA);
surfaceData.metallic = lerp(_MetallicRange.x, _MetallicRange.y, surfaceData.metallic);
surfaceData.metallic = lerp(_MetallicMapRange.x, _MetallicMapRange.y, surfaceData.metallic);
surfaceData.ambientOcclusion = lerp(_AmbientOcclusionRange.x, _AmbientOcclusionRange.y, surfaceData.ambientOcclusion);
surfaceData.ambientOcclusion = lerp(_AmbientOcclusionMapRange.x, _AmbientOcclusionMapRange.y, surfaceData.ambientOcclusion);
surfaceData.ambientOcclusion = lerp(_AmbientOcclusion, surfaceData.ambientOcclusion, _AmbientOcclusionUseMap);
// These static material feature allow compile time optimization

surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_STACK_LIT_DUAL_SPECULAR_LOBE;
surfaceData.lobeMix = _LobeMix;
surfaceData.perceptualSmoothnessB = dot(SAMPLE_TEXTURE2D_SCALE_BIAS(_SmoothnessBMap), _SmoothnessBMapChannelMask);
surfaceData.perceptualSmoothnessB = lerp(_SmoothnessBRange.x, _SmoothnessBRange.y, surfaceData.perceptualSmoothnessB);
surfaceData.perceptualSmoothnessB = lerp(_SmoothnessBMapRange.x, _SmoothnessBMapRange.y, surfaceData.perceptualSmoothnessB);
surfaceData.perceptualSmoothnessB = lerp(_SmoothnessB, surfaceData.perceptualSmoothnessB, _SmoothnessBUseMap);
#else
surfaceData.lobeMix = 0.0;

surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_STACK_LIT_ANISOTROPY;
// TODO: manage anistropy map
//surfaceData.anisotropy = dot(SAMPLE_TEXTURE2D_SCALE_BIAS(_AnistropyMap), _AnistropyMapChannelMask);
//surfaceData.anisotropy = lerp(_AnistropyRange.x, _AnistropyRange.y, surfaceData.anisotropy);
//surfaceData.anisotropy = lerp(_AnistropyMapRange.x, _AnistropyMapRange.y, surfaceData.anisotropy);
surfaceData.anisotropy = _Anisotropy; // In all cases we must multiply anisotropy with the map
#else
surfaceData.anisotropy = 0.0;

#ifdef _MATERIAL_FEATURE_COAT
surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_STACK_LIT_COAT;
surfaceData.coatPerceptualSmoothness = dot(SAMPLE_TEXTURE2D_SCALE_BIAS(_CoatSmoothnessMap), _CoatSmoothnessMapChannelMask);
surfaceData.coatPerceptualSmoothness = lerp(_CoatSmoothnessRange.x, _CoatSmoothnessRange.y, surfaceData.coatPerceptualSmoothness);
surfaceData.coatPerceptualSmoothness = lerp(_CoatSmoothnessMapRange.x, _CoatSmoothnessMapRange.y, surfaceData.coatPerceptualSmoothness);
surfaceData.coatPerceptualSmoothness = lerp(_CoatSmoothness, surfaceData.coatPerceptualSmoothness, _CoatSmoothnessUseMap);
surfaceData.coatIor = _CoatIor;
surfaceData.coatThickness = _CoatThickness;

surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_STACK_LIT_COAT_NORMAL_MAP;
coatGradient = SAMPLE_TEXTURE2D_NORMAL_SCALE_BIAS(_CoatNormalMap, _CoatNormalScale);
coatGradient = SAMPLE_TEXTURE2D_NORMAL_SCALE_BIAS(_CoatNormalMap, _CoatNormalScale, _CoatNormalMapObjSpace);
#endif
#else

surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_STACK_LIT_IRIDESCENCE;
surfaceData.iridescenceIor = _IridescenceIor;
surfaceData.iridescenceThickness = dot(SAMPLE_TEXTURE2D_SCALE_BIAS(_IridescenceThicknessMap), _IridescenceThicknessMapChannelMask);
surfaceData.iridescenceThickness = lerp(_IridescenceThicknessRange.x, _IridescenceThicknessRange.y, surfaceData.iridescenceThickness);
surfaceData.iridescenceThickness = lerp(_IridescenceThicknessMapRange.x, _IridescenceThicknessMapRange.y, surfaceData.iridescenceThickness);
surfaceData.iridescenceMask = dot(SAMPLE_TEXTURE2D_SCALE_BIAS(_IridescenceMaskMap), _IridescenceMaskMapChannelMask);
surfaceData.iridescenceMask = lerp(_IridescenceMaskMapRange.x, _IridescenceMaskMapRange.y, surfaceData.iridescenceMask);
surfaceData.iridescenceMask = lerp(_IridescenceMask, surfaceData.iridescenceMask, _IridescenceMaskUseMap);
surfaceData.iridescenceMask = 0.0;
#endif
#if defined(_MATERIAL_FEATURE_SUBSURFACE_SCATTERING) || defined(_MATERIAL_FEATURE_TRANSMISSION)

#ifdef _MATERIAL_FEATURE_SUBSURFACE_SCATTERING
surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_STACK_LIT_SUBSURFACE_SCATTERING;
surfaceData.subsurfaceMask = dot(SAMPLE_TEXTURE2D_SCALE_BIAS(_SubsurfaceMaskMap), _SubsurfaceMaskMapChannelMask);
surfaceData.subsurfaceMask = lerp(_SubsurfaceMaskRange.x, _SubsurfaceMaskRange.y, surfaceData.subsurfaceMask);
surfaceData.subsurfaceMask = lerp(_SubsurfaceMaskMapRange.x, _SubsurfaceMaskMapRange.y, surfaceData.subsurfaceMask);
surfaceData.subsurfaceMask = lerp(_SubsurfaceMask, surfaceData.subsurfaceMask, _SubsurfaceMaskUseMap);
#else
surfaceData.subsurfaceMask = 0.0;

surfaceData.materialFeatures |= MATERIALFEATUREFLAGS_STACK_LIT_TRANSMISSION;
surfaceData.thickness = dot(SAMPLE_TEXTURE2D_SCALE_BIAS(_ThicknessMap), _ThicknessMapChannelMask);
surfaceData.thickness = lerp(_ThicknessRange.x, _ThicknessRange.y, surfaceData.thickness);
surfaceData.thickness = lerp(_ThicknessMapRange.x, _ThicknessMapRange.y, surfaceData.thickness);
#ifdef _USE_DETAILMAP
float detailMask = dot(SAMPLE_TEXTURE2D_SCALE_BIAS(_DetailMaskMap), _DetailMaskMapChannelMask);
float4 detailGradient = SAMPLE_TEXTURE2D_NORMAL_SCALE_BIAS(_DetailNormalMap, _DetailNormalScale, 0.0);
gradient += detailGradient * detailMask;
gradient.w *= 0.5; // Take mean of average normal length
float detailPerceptualSmoothness = dot(SAMPLE_TEXTURE2D_SCALE_BIAS(_DetailSmoothnessMap), _DetailSmoothnessMapChannelMask);
detailPerceptualSmoothness = lerp(_DetailSmoothnessMapRange.x, _DetailSmoothnessMapRange.y, detailPerceptualSmoothness);
// Use overlay blend mode for detail abledo: (base < 0.5 ? (2.0 * base * blend) : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend)))
float smoothnessOverlay = (detailPerceptualSmoothness < 0.5) ?
surfaceData.perceptualSmoothnessA * PositivePow(2.0 * detailPerceptualSmoothness, _DetailSmoothnessScale) :
1.0 - (1.0 - surfaceData.perceptualSmoothnessA) * PositivePow(2.0 * (1.0 - detailPerceptualSmoothness), _DetailSmoothnessScale);
// Lerp with details mask
surfaceData.perceptualSmoothnessA = lerp(surfaceData.perceptualSmoothnessA, saturate(smoothnessOverlay), detailMask);
#ifdef _MATERIAL_FEATURE_DUAL_SPECULAR_LOBE
// Use overlay blend mode for detail abledo: (base < 0.5 ? (2.0 * base * blend) : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend)))
smoothnessOverlay = (detailPerceptualSmoothness < 0.5) ?
surfaceData.perceptualSmoothnessB * PositivePow(2.0 * detailPerceptualSmoothness, _DetailSmoothnessScale) :
1.0 - (1.0 - surfaceData.perceptualSmoothnessB) * PositivePow(2.0 * (1.0 - detailPerceptualSmoothness), _DetailSmoothnessScale);
// Lerp with details mask
surfaceData.perceptualSmoothnessB = lerp(surfaceData.perceptualSmoothnessB, saturate(smoothnessOverlay), detailMask);
#endif
#endif
// -------------------------------------------------------------
// Surface Data Part 2 (outsite GetSurfaceData( ) in Lit shader):
// -------------------------------------------------------------

surfaceData.normalWS = SurfaceGradientResolveNormal(input.worldToTangent[2], gradient.xyz);
surfaceData.coatNormalWS = SurfaceGradientResolveNormal(input.worldToTangent[2], coatGradient.xyz);
surfaceData.tangentWS = Orthonormalize(surfaceData.tangentWS, surfaceData.normalWS);
if ((_GeometricNormalFilteringEnabled + _TextureNormalFilteringEnabled) > 0.0)
{

builtinData.opacity = alpha;
builtinData.bakeDiffuseLighting = SampleBakedGI(input.positionWS, surfaceData.normalWS, input.texCoord1, input.texCoord2);
builtinData.bakeDiffuseLighting = SampleBakedGI(input.positionRWS, surfaceData.normalWS, input.texCoord1, input.texCoord2);
// It is safe to call this function here as surfaceData have been filled
// We want to know if we must enable transmission on GI for SSS material, if the material have no SSS, this code will be remove by the compiler.

// however it will not optimize the lightprobe case due to the proxy volume relying on dynamic if (we rely must get right of this dynamic if), not a problem for SH9, but a problem for proxy volume.
// TODO: optimize more this code.
// Add GI transmission contribution by resampling the GI for inverted vertex normal
builtinData.bakeDiffuseLighting += SampleBakedGI(input.positionWS, -input.worldToTangent[2], input.texCoord1, input.texCoord2) * bsdfData.transmittance;
builtinData.bakeDiffuseLighting += SampleBakedGI(input.positionRWS, -input.worldToTangent[2], input.texCoord1, input.texCoord2) * bsdfData.transmittance;
}
builtinData.emissiveColor = _EmissiveColor * lerp(float3(1.0, 1.0, 1.0), surfaceData.baseColor.rgb, _AlbedoAffectEmissive);

builtinData.velocity = float2(0.0, 0.0);
#ifdef SHADOWS_SHADOWMASK
float4 shadowMask = SampleShadowMask(input.positionWS, input.texCoord1);
float4 shadowMask = SampleShadowMask(input.positionRWS, input.texCoord1);
builtinData.shadowMask0 = shadowMask.x;
builtinData.shadowMask1 = shadowMask.y;
builtinData.shadowMask2 = shadowMask.z;

67
com.unity.render-pipelines.high-definition/HDRP/Material/StackLit/StackLitProperties.hlsl


TEXTURE2D(_IridescenceThicknessMap);
SAMPLER(sampler_IridescenceThicknessMap);
TEXTURE2D(_IridescenceMaskMap);
SAMPLER(sampler_IridescenceMaskMap);
TEXTURE2D(_SubsurfaceMaskMap);
SAMPLER(sampler_SubsurfaceMaskMap);

// Details
TEXTURE2D(_DetailMaskMap);
SAMPLER(sampler_DetailMaskMap);
TEXTURE2D(_DetailSmoothnessMap);
SAMPLER(sampler_DetailSmoothnessMap);
TEXTURE2D(_DetailNormalMap);
SAMPLER(sampler_DetailNormalMap);
TEXTURE2D(_EmissiveColorMap);
SAMPLER(sampler_EmissiveColorMap);

float4 _MetallicMap_TexelSize;
float4 _MetallicMap_MipInfo;
float4 _MetallicMapChannelMask;
float4 _MetallicRange;
float4 _MetallicMapRange;
float _DielectricIor;

float4 _SmoothnessAMap_TexelSize;
float4 _SmoothnessAMap_MipInfo;
float4 _SmoothnessAMapChannelMask;
float4 _SmoothnessARange;
float4 _SmoothnessAMapRange;
float4 _DebugEnvLobeMask;
float4 _DebugLobeMask;

float4 _AmbientOcclusionMap_TexelSize;
float4 _AmbientOcclusionMap_MipInfo;
float4 _AmbientOcclusionMapChannelMask;
float4 _AmbientOcclusionRange;
float4 _AmbientOcclusionMapRange;
float _SmoothnessB;
float _SmoothnessBUseMap;

float4 _SmoothnessBMap_TexelSize;
float4 _SmoothnessBMap_MipInfo;
float4 _SmoothnessBMapChannelMask;
float4 _SmoothnessBRange;
float4 _SmoothnessBMapRange;
float _LobeMix;
float _Anisotropy;

float4 _AnisotropyMap_TexelSize;
float4 _AnisotropyMap_MipInfo;
float4 _AnisotropyMapChannelMask;
float4 _AnisotropyRange;
float4 _AnisotropyMapRange;
float _CoatSmoothness;
float _CoatSmoothnessUseMap;

float4 _CoatSmoothnessMap_TexelSize;
float4 _CoatSmoothnessMap_MipInfo;
float4 _CoatSmoothnessMapChannelMask;
float4 _CoatSmoothnessRange;
float4 _CoatSmoothnessMapRange;
float _CoatIor;
float _CoatThickness;
float3 _CoatExtinction;

float4 _CoatNormalMap_ST;
float4 _CoatNormalMap_TexelSize;
float4 _CoatNormalMap_MipInfo;
float _IridescenceThickness;
float _IridescenceThicknessUseMap;

float4 _IridescenceThicknessMap_TexelSize;
float4 _IridescenceThicknessMap_MipInfo;
float4 _IridescenceThicknessMapChannelMask;
float4 _IridescenceThicknessRange;
float4 _IridescenceThicknessMapRange;
float _IridescenceMask;
float _IridescenceMaskUseMap;
float _IridescenceMaskMapUV;
float _IridescenceMaskMapUVLocal;
float4 _IridescenceMaskMap_ST;
float4 _IridescenceMaskMap_TexelSize;
float4 _IridescenceMaskMap_MipInfo;
float4 _IridescenceMaskMapChannelMask;
float4 _IridescenceMaskMapRange;
int _DiffusionProfile;
float _SubsurfaceMask;
float _SubsurfaceMaskUseMap;

float4 _SubsurfaceMaskMap_TexelSize;
float4 _SubsurfaceMaskMap_MipInfo;
float4 _SubsurfaceMaskMapChannelMask;
float4 _SubsurfaceMaskRange;
float4 _SubsurfaceMaskMapRange;
float _Thickness;
float _ThicknessUseMap;

float4 _ThicknessMap_TexelSize;
float4 _ThicknessMap_MipInfo;
float4 _ThicknessMapChannelMask;
float4 _ThicknessRange;
float4 _ThicknessMapRange;
// Details
float _DetailMaskMapUV;
float _DetailMaskMapUVLocal;
float4 _DetailMaskMap_ST;
float4 _DetailMaskMap_TexelSize;
float4 _DetailMaskMap_MipInfo;
float4 _DetailMaskMapChannelMask;
float _DetailSmoothnessMapUV;
float _DetailSmoothnessMapUVLocal;
float4 _DetailSmoothnessMap_ST;
float4 _DetailSmoothnessMap_TexelSize;
float4 _DetailSmoothnessMap_MipInfo;
float4 _DetailSmoothnessMapChannelMask;
float4 _DetailSmoothnessMapRange;
float _DetailSmoothnessScale;
float _DetailNormalScale;
float _DetailNormalMapUV;
float _DetailNormalMapUVLocal;
float4 _DetailNormalMap_ST;
float4 _DetailNormalMap_TexelSize;
float4 _DetailNormalMap_MipInfo;
float3 _EmissiveColor;
float4 _EmissiveColorMap_ST;

4
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/FragInputs.hlsl


// Contain value return by SV_POSITION (That is name positionCS in PackedVarying).
// xy: unormalized screen position (offset by 0.5), z: device depth, w: depth in view space
// Note: SV_POSITION is the result of the clip space position provide to the vertex shaders that is transform by the viewport
float4 positionSS; // In case depth offset is use, positionWS.w is equal to depth offset
float3 positionWS;
float4 positionSS; // In case depth offset is use, positionRWS.w is equal to depth offset
float3 positionRWS; // Relative camera space position
float2 texCoord0;
float2 texCoord1;
float2 texCoord2;

11
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDBuffer.hlsl


{
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
DecalSurfaceData surfaceData;
// Transform from world space to decal space (DS) to clip the decal.
// For this we must use absolute position.
// There is no lose of precision here as it doesn't involve the camera matrix
float3 positionWS = GetAbsolutePositionWS(posInput.positionWS);
float3 positionDS = mul(UNITY_MATRIX_I_M, float4(positionWS, 1.0)).xyz;
// Transform from relative world space to decal space (DS) to clip the decal
float3 positionDS = TransformWorldToObject(posInput.positionWS);
float4x4 normalToWorld = UNITY_ACCESS_INSTANCED_PROP(matrix, _NormalToWorld);
GetSurfaceData(positionDS.xz, normalToWorld, surfaceData);
// have to do explicit test since compiler behavior is not defined for RW resources and discard instructions

4
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDepthOnly.hlsl


FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.positionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionWS);
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else
float3 V = 0; // Avoid the division by 0
#endif

4
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassDistortion.hlsl


FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.positionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionWS);
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else
float3 V = 0; // Avoid the division by 0
#endif

4
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForward.hlsl


FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.positionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionWS.xyz, uint2(input.positionSS.xy) / GetTileSize());
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS.xyz, uint2(input.positionSS.xy) / GetTileSize());
float3 V = GetWorldSpaceNormalizeViewDir(input.positionWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else
float3 V = 0; // Avoid the division by 0
#endif

4
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassForwardUnlit.hlsl


FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.positionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionWS);
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else
float3 V = 0; // Avoid the division by 0
#endif

4
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassGBuffer.hlsl


FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.positionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionWS);
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else
float3 V = 0; // Avoid the division by 0
#endif

7
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassLightTransport.hlsl


output.vmesh.positionCS = float4(uv * 2.0 - 1.0, inputMesh.positionOS.z > 0 ? 1.0e-4 : 0.0, 1.0);
#ifdef VARYINGS_NEED_POSITION_WS
float3 positionWS = GetCameraRelativePositionWS(TransformObjectToWorld(inputMesh.positionOS));
output.vmesh.positionWS = positionWS;
output.vmesh.positionRWS = TransformObjectToWorld(inputMesh.positionOS);
#endif
#ifdef VARYINGS_NEED_TANGENT_TO_WORLD

FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.positionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionWS);
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else
float3 V = 0; // Avoid the division by 0
#endif

24
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/ShaderPassVelocity.hlsl


#endif
}
// Transforms local position to camera relative world space
float3 TransformPreviousObjectToWorld(float3 positionOS)
{
float4x4 previousModelMatrix = ApplyCameraTranslationToMatrix(unity_MatrixPreviousM);
return mul(previousModelMatrix, float4(positionOS, 1.0)).xyz;
}
void VelocityPositionZBias(VaryingsToPS input)
{
#if defined(UNITY_REVERSED_Z)

// It is not possible to correctly generate the motion vector for tesselated geometry as tessellation parameters can change
// from one frame to another (adaptative, lod) + in Unity we only receive information for one non tesselated vertex.
// So motion vetor will be based on interpolate previous position at vertex level instead.
varyingsType.vpass.positionCS = mul(_NonJitteredViewProjMatrix, float4(varyingsType.vmesh.positionWS, 1.0));
varyingsType.vpass.positionCS = mul(_NonJitteredViewProjMatrix, float4(varyingsType.vmesh.positionRWS, 1.0));
// Note: unity_MotionVectorsParams.y is 0 is forceNoMotion is enabled
bool forceNoMotion = unity_MotionVectorsParams.y == 0.0;

if (hasDeformation)
previousMesh.positionOS = inputPass.previousPositionOS;
previousMesh = ApplyMeshModification(previousMesh);
float3 previousPositionWS = mul(unity_MatrixPreviousM, float4(previousMesh.positionOS, 1.0)).xyz;
float3 previousPositionRWS = TransformPreviousObjectToWorld(previousMesh.positionOS);
float3 previousPositionWS = mul(unity_MatrixPreviousM, hasDeformation ? float4(inputPass.previousPositionOS, 1.0) : float4(inputMesh.positionOS, 1.0)).xyz;
float3 previousPositionRWS = TransformPreviousObjectToWorld(hasDeformation ? inputPass.previousPositionOS : inputMesh.positionOS);
#endif
#ifdef ATTRIBUTES_NEED_NORMAL

#endif
#if defined(HAVE_VERTEX_MODIFICATION)
ApplyVertexModification(inputMesh, normalWS, previousPositionWS, _LastTime);
ApplyVertexModification(inputMesh, normalWS, previousPositionRWS, _LastTime);
//Need this since we are using the current position from VertMesh()
previousPositionWS = GetCameraRelativePositionWS(previousPositionWS);
varyingsType.vpass.previousPositionCS = mul(_PrevViewProjMatrix, float4(previousPositionWS, 1.0));
varyingsType.vpass.previousPositionCS = mul(_PrevViewProjMatrix, float4(previousPositionRWS, 1.0));
}
return PackVaryingsType(varyingsType);

FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// input.positionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionWS);
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionWS);
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else
float3 V = 0; // Avoid the division by 0
#endif

16
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/TessellationShare.hlsl


VaryingsToDS varying1 = UnpackVaryingsToDS(input[1]);
VaryingsToDS varying2 = UnpackVaryingsToDS(input[2]);
float3 p0 = varying0.vmesh.positionWS;
float3 p1 = varying1.vmesh.positionWS;
float3 p2 = varying2.vmesh.positionWS;
float3 p0 = varying0.vmesh.positionRWS;
float3 p1 = varying1.vmesh.positionRWS;
float3 p2 = varying2.vmesh.positionRWS;
float3 n0 = varying0.vmesh.normalWS;
float3 n1 = varying1.vmesh.normalWS;

// We have Phong tessellation in all case where we don't have displacement only
#ifdef _TESSELLATION_PHONG
float3 p0 = varying0.vmesh.positionWS;
float3 p1 = varying1.vmesh.positionWS;
float3 p2 = varying2.vmesh.positionWS;
float3 p0 = varying0.vmesh.positionRWS;
float3 p1 = varying1.vmesh.positionRWS;
float3 p2 = varying2.vmesh.positionRWS;
varying.vmesh.positionWS = PhongTessellation( varying.vmesh.positionWS,
varying.vmesh.positionRWS = PhongTessellation( varying.vmesh.positionRWS,
ApplyTessellationModification(varying.vmesh, varying.vmesh.normalWS, varying.vmesh.positionWS);
ApplyTessellationModification(varying.vmesh, varying.vmesh.normalWS, varying.vmesh.positionRWS);
#endif
return VertTesselation(varying);

16
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/VaryingMesh.hlsl


{
float4 positionCS;
#ifdef VARYINGS_NEED_POSITION_WS
float3 positionWS;
float3 positionRWS;
#endif
#ifdef VARYINGS_NEED_TANGENT_TO_WORLD
float3 normalWS;

output.positionCS = input.positionCS;
#ifdef VARYINGS_NEED_POSITION_WS
output.interpolators0 = input.positionWS;
output.interpolators0 = input.positionRWS;
#endif
#ifdef VARYINGS_NEED_TANGENT_TO_WORLD

output.positionSS = input.positionCS; // input.positionCS is SV_Position
#ifdef VARYINGS_NEED_POSITION_WS
output.positionWS.xyz = input.interpolators0.xyz;
output.positionRWS.xyz = input.interpolators0.xyz;
#endif
#ifdef VARYINGS_NEED_TANGENT_TO_WORLD

// Position and normal are always present (for tessellation) and in world space
struct VaryingsMeshToDS
{
float3 positionWS;
float3 positionRWS;
float3 normalWS;
#ifdef VARYINGS_DS_NEED_TANGENT
float4 tangentWS;

struct PackedVaryingsMeshToDS
{
float3 interpolators0 : INTERNALTESSPOS; // positionWS
float3 interpolators0 : INTERNALTESSPOS; // positionRWS
float3 interpolators1 : NORMAL; // NormalWS
#ifdef VARYINGS_DS_NEED_TANGENT

UNITY_TRANSFER_INSTANCE_ID(input, output);
output.interpolators0 = input.positionWS;
output.interpolators0 = input.positionRWS;
output.interpolators1 = input.normalWS;
#ifdef VARYINGS_DS_NEED_TANGENT
output.interpolators2 = input.tangentWS;

UNITY_TRANSFER_INSTANCE_ID(input, output);
output.positionWS = input.interpolators0;
output.positionRWS = input.interpolators0;
output.normalWS = input.interpolators1;
#ifdef VARYINGS_DS_NEED_TANGENT
output.tangentWS = input.interpolators2;

UNITY_TRANSFER_INSTANCE_ID(input0, output);
TESSELLATION_INTERPOLATE_BARY(positionWS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(positionRWS, baryCoords);
TESSELLATION_INTERPOLATE_BARY(normalWS, baryCoords);
#ifdef VARYINGS_DS_NEED_TANGENT
// This will interpolate the sign but should be ok in practice as we may expect a triangle to have same sign (? TO CHECK)

20
com.unity.render-pipelines.high-definition/HDRP/ShaderPass/VertMesh.hlsl


UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
float3 positionWS = TransformObjectToWorld(input.positionOS);
// This return the camera relative position (if enable)
float3 positionRWS = TransformObjectToWorld(input.positionOS);
#ifdef ATTRIBUTES_NEED_NORMAL
float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
#else

float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
#endif
// TODO: deal with camera center rendering and instancing (This is the reason why we always perform two steps transform to clip space + instancing matrix)
// Do vertex modification in camera relative space (if enable)
ApplyVertexModification(input, normalWS, positionWS, _Time);
ApplyVertexModification(input, normalWS, positionRWS, _Time);
positionWS = GetCameraRelativePositionWS(positionWS);
output.positionWS = positionWS;
output.positionRWS = positionRWS;
output.normalWS = normalWS;
#if defined(VARYINGS_NEED_TANGENT_TO_WORLD) || defined(VARYINGS_DS_NEED_TANGENT)
output.tangentWS = tangentWS;

output.positionWS = positionWS;
output.positionRWS = positionRWS;
output.positionCS = TransformWorldToHClip(positionWS);
output.positionCS = TransformWorldToHClip(positionRWS);
#ifdef VARYINGS_NEED_TANGENT_TO_WORLD
output.normalWS = normalWS;
output.tangentWS = tangentWS;

UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
output.positionCS = TransformWorldToHClip(input.positionWS);
output.positionCS = TransformWorldToHClip(input.positionRWS);
output.positionWS = input.positionWS;
output.positionRWS = input.positionRWS;
#endif
#ifdef VARYINGS_NEED_TANGENT_TO_WORLD

26
com.unity.render-pipelines.high-definition/HDRP/ShaderVariables.hlsl


return M;
}
// Helper to handle camera relative space
float4x4 ApplyCameraTranslationToMatrix(float4x4 modelMatrix)
{
// To handle camera relative rendering we substract the camera position in the model matrix
// User must not use UNITY_MATRIX_M directly, unless they understand what they do
#if (SHADEROPTIONS_CAMERA_RELATIVE_RENDERING != 0)
modelMatrix._m03_m13_m23 -= _WorldSpaceCameraPos;
#endif
return modelMatrix;
}
float4x4 ApplyCameraTranslationToInverseMatrix(float4x4 inverseModelMatrix)
{
#if (SHADEROPTIONS_CAMERA_RELATIVE_RENDERING != 0)
// To handle camera relative rendering we need to apply translation before converting to object space
float4x4 translationMatrix = { { 1.0, 0.0, 0.0, _WorldSpaceCameraPos.x },{ 0.0, 1.0, 0.0, _WorldSpaceCameraPos.y },{ 0.0, 0.0, 1.0, _WorldSpaceCameraPos.z },{ 0.0, 0.0, 0.0, 1.0 } };
return mul(inverseModelMatrix, translationMatrix);
#else
return inverseModelMatrix;
#endif
}
#ifdef USE_LEGACY_UNITY_MATRIX_VARIABLES
#include "ShaderVariablesMatrixDefsLegacyUnity.hlsl"
#else

// This define allow to tell to unity instancing that we will use our camera relative functions (ApplyCameraTranslationToMatrix and ApplyCameraTranslationToInverseMatrix) for the model view matrix
#define MODIFY_MATRIX_FOR_CAMERA_RELATIVE_RENDERING
#include "CoreRP/ShaderLibrary/UnityInstancing.hlsl"
#include "ShaderVariablesFunctions.hlsl"

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

正在加载...
取消
保存