浏览代码

Merge upstream/master

/main
Evgenii Golubev 7 年前
当前提交
0a2033df
共有 309 个文件被更改,包括 2967 次插入1346 次删除
  1. 3
      ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity.png.meta
  2. 999
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2004_AnimatedCookie.unity.png
  3. 3
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2004_AnimatedCookie.unity.png.meta
  4. 3
      ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2201_ReflectionProbes_Priority.unity.png.meta
  5. 3
      ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3001_DebugView.unity.png.meta
  6. 8
      README.md
  7. 2
      ScriptableRenderPipeline/Core/CoreRP/CoreResources/EncodeBC6H.compute
  8. 2
      ScriptableRenderPipeline/Core/CoreRP/CoreResources/GPUCopy.compute
  9. 9
      ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugUI.Fields.cs
  10. 7
      ScriptableRenderPipeline/Core/CoreRP/Debugging/Prefabs/Scripts/DebugUIHandlerCanvas.cs
  11. 9
      ScriptableRenderPipeline/Core/CoreRP/Editor/MaterialUpgrader.cs
  12. 2
      ScriptableRenderPipeline/Core/CoreRP/Editor/Volume/VolumeComponentEditor.cs
  13. 2
      ScriptableRenderPipeline/Core/CoreRP/Editor/Volume/VolumeProfileFactory.cs
  14. 19
      ScriptableRenderPipeline/Core/CoreRP/Inputs/InputRegistering.cs
  15. 10
      ScriptableRenderPipeline/Core/CoreRP/Shadow/AdditionalShadowData.cs
  16. 19
      ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs
  17. 2
      ScriptableRenderPipeline/Core/CoreRP/Shadow/ShadowBlurMoments.compute
  18. 23
      ScriptableRenderPipeline/Core/CoreRP/TextureCache.cs
  19. 4
      ScriptableRenderPipeline/Core/package.json
  20. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDAdditionalCameraData.cs
  21. 96
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs
  22. 384
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalSystem.cs
  23. 39
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraUI.cs
  24. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/SerializedHDCamera.cs
  25. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDAssetFactory.cs
  26. 46
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDRenderPipelineMenuItems.cs
  27. 12
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.Styles.cs
  28. 136
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs
  29. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/LitUI.cs
  30. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Sky/ProceduralSky/ProceduralSkyEditor.cs
  31. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Sky/SkySettingsEditor.cs
  32. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/UpgradeStandardShaderMaterials.cs
  33. 3
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDCustomSamplerId.cs
  34. 61
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs
  35. 15
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs
  36. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs
  37. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/DeferredDirectionalShadow.compute
  38. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs
  39. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDLightEditorUtilities.cs
  40. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Deferred.compute
  41. 255
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs
  42. 5
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs.hlsl
  43. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/builddispatchindirect.compute
  44. 1
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/cleardispatchindirect.compute
  45. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-bigtile.compute
  46. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-clustered.compute
  47. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild.compute
  48. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/materialflags.compute
  49. 26
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/scrbound.compute
  50. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/Resources/VolumetricLighting.compute
  51. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs
  52. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs.hlsl
  53. 10
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.hlsl
  54. 7
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalData.hlsl
  55. 96
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalUtilities.hlsl
  56. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/BuildProbabilityTables.compute
  57. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/ComputeGgxIblSampleData.compute
  58. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitData.hlsl
  59. 160
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl
  60. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitData.hlsl
  61. 20
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.compute
  62. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/ApplyDistorsion.compute
  63. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/ColorPyramid.compute
  64. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/DepthPyramid.compute
  65. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset
  66. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/RenderPipelineResources.cs
  67. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassDBuffer.hlsl
  68. 4
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariables.hlsl
  69. 6
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariablesMatrixDefsHDCamera.hlsl
  70. 46
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Shadows/HDShadowSettings.cs
  71. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISkyRenderer.cs
  72. 2
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSkyRenderer.cs
  73. 21
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyManager.cs
  74. 6
      ScriptableRenderPipeline/HDRenderPipeline/package.json
  75. 3
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/com.unity.render-pipelines.lightweight.Editor.asmdef
  76. 24
      ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs
  77. 9
      ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipelineUtils.cs
  78. 21
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Materials/Lightweight-DefaultParticle.mat
  79. 10
      ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardUnlit.shader
  80. 6
      ScriptableRenderPipeline/LightweightPipeline/package.json
  81. 5
      ScriptableRenderPipeline/LightweightPipeline/sub-package.json
  82. 4
      ScriptableRenderPipeline/master-package.json
  83. 2
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1201_Lit_Features/Lit_NormalMap_ObjectSpace.mat
  84. 76
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2004_AnimatedCookie.unity
  85. 9
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat__N.png.meta
  86. 18
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat_M_AO_D_S.png.meta
  87. 18
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat_H.png.meta
  88. 5
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat_BC_A.png.meta
  89. 999
      Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Materials/ComplexMaterial/Textures/ComplexMat_BC_A.png
  90. 8
      ScriptableRenderPipeline/Core/CoreRP/Editor/TextureCombiner.meta
  91. 217
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs
  92. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs.meta
  93. 44
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Unlit/UnlitsToHDUnlitUpgrader.cs
  94. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Unlit/UnlitsToHDUnlitUpgrader.cs.meta
  95. 8
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Shadows.meta
  96. 67
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtils.cs
  97. 11
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtils.cs.meta
  98. 16
      ScriptableRenderPipeline/HDRenderPipeline/HDRP/Shadows/ContactShadows.cs

3
ImageTemplates/HDRenderPipeline/Scenes/1xxx_Materials/1206_Lit_Transparent_Distortion.unity.png.meta


spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1

999
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2004_AnimatedCookie.unity.png
文件差异内容过多而无法显示
查看文件

3
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2004_AnimatedCookie.unity.png.meta


spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1

3
ImageTemplates/HDRenderPipeline/Scenes/2xxx_Lighting/2201_ReflectionProbes_Priority.unity.png.meta


spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1

3
ImageTemplates/HDRenderPipeline/Scenes/3xxx_DebugView/3001_DebugView.unity.png.meta


spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1

8
README.md


2. Navigate to ___Edit > Project Settings > Graphics___ and add the Lightweight Render Pipeline Asset you created to the __Render Pipeline Settings__ field.
Note: Always store your new Render Pipeline Asset outside of the Scriptable Render Pipeline folder. This ensures that your Lightweight settings are not lost when merging new changes from the SRP repo.
## Sample Scenes in ScriptableRenderPipelineData
If you want some sample scenes to use with SRP, you can find them at the [ScriptableRenderPipelineData GitHub repository](https://github.com/Unity-Technologies/ScriptableRenderPipelineData).
Clone the repo into your project's Assets\ folder, likely alongside your ScriptableRenderPipeline clone folder. You can use the same cloning process as described above for the main ScriptableRenderPipeline repo.
Previous iterations of the ScriptableRenderPipeline repo owned this sample scene data, in case you noticed it before, and wondered where it went.

2
ScriptableRenderPipeline/Core/CoreRP/CoreResources/EncodeBC6H.compute


#include "CoreRP/ShaderLibrary/BC6H.hlsl"
#include "CoreRP/ShaderLibrary/Sampling/Sampling.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
TextureCube<float4> _Source;
RWTexture2DArray<uint4> _Target;
int _MipIndex;

2
ScriptableRenderPipeline/Core/CoreRP/CoreResources/GPUCopy.compute


#include "../ShaderLibrary/Common.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
RWTexture2D<float1> _Result1;
Texture2D<float4> _Source4;

9
ScriptableRenderPipeline/Core/CoreRP/Debugging/DebugUI.Fields.cs


set
{
enumNames = Enum.GetNames(value).Select(x => new GUIContent(x)).ToArray();
enumValues = Enum.GetValues(value).Cast<int>().ToArray();
// Linq.Cast<T> on a typeless Array breaks the JIT on PS4/Mono so we have to do it manually
//enumValues = Enum.GetValues(value).Cast<int>().ToArray();
var values = Enum.GetValues(value);
enumValues = new int[values.Length];
for (int i = 0; i < values.Length; i++)
enumValues[i] = (int)values.GetValue(i);
}
}
}

7
ScriptableRenderPipeline/Core/CoreRP/Debugging/Prefabs/Scripts/DebugUIHandlerCanvas.cs


}
else
{
m_CurrentQueryPath = m_SelectedWidget != null
? m_SelectedWidget.GetWidget().queryPath
: string.Empty;
if (m_SelectedWidget == null || m_SelectedWidget.GetWidget() == null)
m_CurrentQueryPath = string.Empty;
else
m_CurrentQueryPath = m_SelectedWidget.GetWidget().queryPath;
}
}

9
ScriptableRenderPipeline/Core/CoreRP/Editor/MaterialUpgrader.cs


Dictionary<string, float> m_FloatPropertiesToSet = new Dictionary<string, float>();
Dictionary<string, Color> m_ColorPropertiesToSet = new Dictionary<string, Color>();
List<string> m_TexturesToRemove = new List<string>();
Dictionary<string, Texture> m_TexturesToSet = new Dictionary<string, Texture>();
class KeywordFloatRename

foreach (var prop in m_TexturesToRemove)
dstMaterial.SetTexture(prop, null);
foreach (var prop in m_TexturesToSet)
dstMaterial.SetTexture(prop.Key, prop.Value);
foreach (var prop in m_FloatPropertiesToSet)
dstMaterial.SetFloat(prop.Key, prop.Value);

public void SetColor(string propertyName, Color value)
{
m_ColorPropertiesToSet[propertyName] = value;
}
public void SetTexture(string propertyName, Texture value)
{
m_TexturesToSet[propertyName] = value;
}
public void RenameKeywordToFloat(string oldName, string newName, float setVal, float unsetVal)

2
ScriptableRenderPipeline/Core/CoreRP/Editor/Volume/VolumeComponentEditor.cs


}
}
// TODO: Doesn't work correctly with indented controls, fixme
overrideRect.xMin += EditorGUI.indentLevel * 15f;
var oldColor = GUI.color;
GUI.color = new Color(0.6f, 0.6f, 0.6f, 0.75f);

2
ScriptableRenderPipeline/Core/CoreRP/Editor/Volume/VolumeProfileFactory.cs


else
{
var scenePath = Path.GetDirectoryName(scene.path);
var extPath = scene.name + "_Profiles";
var extPath = scene.name;
var profilePath = scenePath + "/" + extPath;
if (!AssetDatabase.IsValidFolder(profilePath))

19
ScriptableRenderPipeline/Core/CoreRP/Inputs/InputRegistering.cs


using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class InputManagerEntry
{
public enum Kind { KeyOrButton, Mouse, Axis }

public class InputRegistering
{
static bool InputAlreadyRegistered(string name, InputManagerEntry.Kind kind, UnityEditor.SerializedProperty spAxes)
static bool InputAlreadyRegistered(string name, InputManagerEntry.Kind kind, SerializedProperty spAxes)
{
for (var i = 0; i < spAxes.arraySize; ++i)
{

return false;
}
static void WriteEntry(UnityEditor.SerializedProperty spAxes, InputManagerEntry entry)
static void WriteEntry(SerializedProperty spAxes, InputManagerEntry entry)
{
if (InputAlreadyRegistered(entry.name, entry.kind, spAxes))
return;

spAxis.FindPropertyRelative("joyNum").intValue = (int)entry.joystick;
}
static public void RegisterInputs(List<InputManagerEntry> entries)
public static void RegisterInputs(List<InputManagerEntry> entries)
var currentSelection = UnityEditor.Selection.activeObject;
UnityEditor.EditorApplication.ExecuteMenuItem("Edit/Project Settings/Input");
var inputManager = UnityEditor.Selection.activeObject;
var inputManager = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0];
var soInputManager = new UnityEditor.SerializedObject(inputManager);
var soInputManager = new SerializedObject(inputManager);
var spAxes = soInputManager.FindProperty("m_Axes");
foreach(InputManagerEntry entry in entries)

// Commit
soInputManager.ApplyModifiedProperties();
UnityEditor.Selection.activeObject = currentSelection;
}
}

10
ScriptableRenderPipeline/Core/CoreRP/Shadow/AdditionalShadowData.cs


[Range(0.0f, 1.0f)]
public float shadowDimmer = 1.0f;
public float shadowFadeDistance = 10000.0f;
// Contact shadows
public bool enableContactShadows = false;
[Range(0.0f, 1.0f)]
public float contactShadowLength = 0.0f;
[Range(0.0f, 1.0f)]
public float contactShadowDistanceScaleFactor = 0.5f;
public float contactShadowMaxDistance = 50.0f;
public float contactShadowFadeDistance = 5.0f;
[Range(4, 64)]
public uint contactShadowSampleCount = 8;
// bias control
public float viewBiasMin = 0.5f;
public float viewBiasMax = 10.0f;

19
ScriptableRenderPipeline/Core/CoreRP/Shadow/Shadow.cs


public VectorArray<ShadowPayload> payloads { get { return m_Payloads; } set { m_Payloads = value; } }
}
public struct ShadowBudgets
{
public int maxPointLights;
public int maxSpotLights;
public int maxDirectionalLights;
}
private const int k_MaxShadowmapPerType = 4;
private ShadowSettings m_ShadowSettings;
private ShadowmapBase[] m_Shadowmaps;

// and register itself
AdditionalShadowDataEditor.SetRegistry( this );
#endif
}
public ShadowManager(ShadowSettings shadowSettings, ref ShadowContext.CtxtInit ctxtInitializer, ref ShadowBudgets budgets, ShadowmapBase[] shadowmaps ) : this( shadowSettings, ref ctxtInitializer, shadowmaps )
{
SetPerFrameBudgets( ref budgets );
}
public void SetPerFrameBudgets( ref ShadowBudgets budgets )
{
m_MaxShadows[(int)GPUShadowType.Point ,0] = m_MaxShadows[(int)GPUShadowType.Point ,1] = budgets.maxPointLights;
m_MaxShadows[(int)GPUShadowType.Spot ,0] = m_MaxShadows[(int)GPUShadowType.Spot ,1] = budgets.maxSpotLights;
m_MaxShadows[(int)GPUShadowType.Directional,0] = m_MaxShadows[(int)GPUShadowType.Directional ,1] = budgets.maxDirectionalLights;
}
public override void UpdateCullingParameters( ref ScriptableCullingParameters cullingParams )

2
ScriptableRenderPipeline/Core/CoreRP/Shadow/ShadowBlurMoments.compute


#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/Shadow/ShadowMoments.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
#if MAX_MSAA > 1
Texture2DMS<float> depthTex;
#else

23
ScriptableRenderPipeline/Core/CoreRP/TextureCache.cs


using System;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.Rendering;
#if UNITY_EDITOR

public void Release()
{
Texture.DestroyImmediate(m_Cache); // do I need this?
CoreUtils.Destroy(m_Cache);
}
}

{
m_CubeMipLevelPropName = Shader.PropertyToID("_cubeMipLvl");
m_cubeSrcTexPropName = Shader.PropertyToID("_srcCubeTexture");
}
}
else

{
if (m_CacheNoCubeArray)
{
Texture.DestroyImmediate(m_CacheNoCubeArray);
CoreUtils.Destroy(m_CacheNoCubeArray);
if (m_CubeBlitMaterial) Material.DestroyImmediate(m_CubeBlitMaterial);
CoreUtils.Destroy(m_CubeBlitMaterial);
if (m_Cache)
Texture.DestroyImmediate(m_Cache);
CoreUtils.Destroy(m_Cache);
}
private void TransferToPanoCache(CommandBuffer cmd, int sliceIndex, Texture texture)

get
{
var format = TextureFormat.RGBAHalf;
// // On editor the texture is uncompressed when operating against mobile build targets
//#if UNITY_2017_2_OR_NEWER
//#else
// if (SystemInfo.SupportsTextureFormat(probeFormat) && !TextureCache.isMobileBuildTarget)
// format = probeFormat;
//#endif
return format;
}

{
get
{
//#if UNITY_2017_2_OR_NEWER
//#else
// return (SystemInfo.supportsCubemapArrayTextures && !TextureCache.isMobileBuildTarget);
//#endif
}
}

4
ScriptableRenderPipeline/Core/package.json


{
"name": "com.unity.render-pipelines.core",
"description": "Core library for Unity render pipelines.",
"version": "0.1.32",
"version": "0.1.33",
"com.unity.postprocessing": "0.1.8"
"com.unity.postprocessing": "0.2.0"
}
}

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDAdditionalCameraData.cs


[Tooltip("Layer Mask used for the volume interpolation for this camera.")]
public LayerMask volumeLayerMask = -1;
// Physical parameters
public float aperture = 8f;
public float shutterSpeed = 1f / 200f;
public float iso = 400f;
// To be able to turn on/off FrameSettings properties at runtime for debugging purpose without affecting the original one
// we create a runtime copy (m_ActiveFrameSettings that is used, and any parametrization is done on serialized frameSettings)
[SerializeField]

96
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Camera/HDCamera.cs


public Matrix4x4[] viewMatrixStereo;
public Matrix4x4[] projMatrixStereo;
public Vector4 centerEyeTranslationOffset;
// Non oblique projection matrix (RHS)
public Matrix4x4 nonObliqueProjMatrix

// The scene view has no additional data so this will correctly pick the editor preference backround color here.
return camera.backgroundColor.linear;
}
}
}
static Dictionary<Camera, HDCamera> s_Cameras = new Dictionary<Camera, HDCamera>();
static List<Camera> s_Cleanup = new List<Camera>(); // Recycled to reduce GC pressure

var gpuView = camera.worldToCameraMatrix;
var gpuNonJitteredProj = GL.GetGPUProjectionMatrix(nonJitteredCameraProj, true);
// In stereo, this corresponds to the center eye position
var relPos = pos; // World-origin-relative
relPos = Vector3.zero; // Camera-relative
}
var gpuVP = gpuNonJitteredProj * gpuView;

isFirstFrame = false;
}
// TEMP: Re-enable this code once we bump the postprocessing package to 0.1.19 (or above)
// current package 0.1.8 don't have the .sampleIndex and it fail with template...
// taaFrameIndex = taaEnabled ? (uint)postProcessLayer.temporalAntialiasing.sampleIndex : 0;
const uint taaFrameCount = 8;
taaFrameIndex = taaEnabled ? (uint)Time.renderedFrameCount % taaFrameCount : 0;
// END TEMP
taaFrameIndex = taaEnabled ? (uint)postProcessLayer.temporalAntialiasing.sampleIndex : 0;
taaFrameRotation = new Vector2(Mathf.Sin(taaFrameIndex * (0.5f * Mathf.PI)),
Mathf.Cos(taaFrameIndex * (0.5f * Mathf.PI)));

screenSize = new Vector4(screenWidth, screenHeight, 1.0f / screenWidth, 1.0f / screenHeight);
}
// Stopgap method used to extract stereo combined matrix state.
public void UpdateStereoDependentState(FrameSettings frameSettings, ref ScriptableCullingParameters cullingParams)
{
if (!frameSettings.enableStereo)
return;
// What constants in UnityPerPass need updating for stereo considerations?
// _ViewProjMatrix - It is used directly for generating tesselation factors. This should be the same
// across both eyes for consistency, and to keep shadow-generation eye-independent
// _ViewParam - Used for isFrontFace determination, should be the same for both eyes. There is the scenario
// where there might be multi-eye sets that are divergent enough where this assumption is not valid,
// but that's a future problem
// _InvProjParam - Intention was for generating linear depths, but not currently used. Will need to be stereo-ized if
// actually needed.
// _FrustumPlanes - Also used for generating tesselation factors. Should be fine to use the combined stereo VP
// to calculate frustum planes.
// TODO: Would it be worth calculating my own combined view/proj matrix in Update?
// In engine, we modify the view and proj matrices accordingly in order to generate the single cull
// * Get the center eye view matrix, and pull it back to cover both eyes
// * Generated an expanded projection matrix (one method - max bound of left/right proj matrices)
// and move near/far planes to match near/far locations of proj matrices located at eyes.
// I think using the cull matrices is valid, as long as I only use them for tess factors in shader.
// Using them for other calculations (like light list generation) could be problematic.
var stereoCombinedViewMatrix = cullingParams.cullStereoView;
if (ShaderConfig.s_CameraRelativeRendering != 0)
{
// This is pulled back from the center eye, so set the offset
var translation = stereoCombinedViewMatrix.GetColumn(3);
translation += centerEyeTranslationOffset;
stereoCombinedViewMatrix.SetColumn(3, translation);
}
viewMatrix = stereoCombinedViewMatrix;
var stereoCombinedProjMatrix = cullingParams.cullStereoProj;
projMatrix = GL.GetGPUProjectionMatrix(stereoCombinedProjMatrix, true);
viewParam = new Vector4(viewMatrix.determinant, 0.0f, 0.0f, 0.0f);
frustum = Frustum.Create(viewProjMatrix, true, true);
// Left, right, top, bottom, near, far.
for (int i = 0; i < 6; i++)
{
frustumPlaneEquations[i] = new Vector4(frustum.planes[i].normal.x, frustum.planes[i].normal.y, frustum.planes[i].normal.z, frustum.planes[i].distance);
}
}
void ConfigureStereoMatrices()
{
for (uint eyeIndex = 0; eyeIndex < 2; eyeIndex++)

projMatrixStereo[eyeIndex] = camera.GetStereoProjectionMatrix((Camera.StereoscopicEye)eyeIndex);
projMatrixStereo[eyeIndex] = GL.GetGPUProjectionMatrix(projMatrixStereo[eyeIndex], true);
}
if (ShaderConfig.s_CameraRelativeRendering != 0)
{
var leftTranslation = viewMatrixStereo[0].GetColumn(3);
var rightTranslation = viewMatrixStereo[1].GetColumn(3);
var centerTranslation = (leftTranslation + rightTranslation) / 2;
var centerOffset = -centerTranslation;
centerOffset.w = 0;
// TODO: Grabbing the CenterEye transform would be preferable, but XRNode.CenterEye
// doesn't always seem to be valid.
for (uint eyeIndex = 0; eyeIndex < 2; eyeIndex++)
{
var translation = viewMatrixStereo[eyeIndex].GetColumn(3);
translation += centerOffset;
viewMatrixStereo[eyeIndex].SetColumn(3, translation);
}
centerEyeTranslationOffset = centerOffset;
}
// TODO: Fetch the single cull matrix stuff

public void SetupGlobalStereoParams(CommandBuffer cmd)
{
var viewProjStereo = new Matrix4x4[2];
var invViewStereo = new Matrix4x4[2];
var invProjStereo = new Matrix4x4[2];
var invViewProjStereo = new Matrix4x4[2];

invProjStereo[eyeIndex] = proj.inverse;
var vp = proj * viewMatrixStereo[eyeIndex];
invViewProjStereo[eyeIndex] = vp.inverse;
var view = viewMatrixStereo[eyeIndex];
invViewStereo[eyeIndex] = view.inverse;
viewProjStereo[eyeIndex] = proj * view;
invViewProjStereo[eyeIndex] = viewProjStereo[eyeIndex].inverse;
cmd.SetGlobalMatrixArray(HDShaderIDs._ViewMatrixStereo, viewMatrixStereo);
cmd.SetGlobalMatrixArray(HDShaderIDs._ViewProjMatrixStereo, viewProjStereo);
cmd.SetGlobalMatrixArray(HDShaderIDs._InvViewMatrixStereo, invViewStereo);
cmd.SetGlobalMatrixArray(HDShaderIDs._InvProjMatrixStereo, invProjStereo);
cmd.SetGlobalMatrixArray(HDShaderIDs._InvViewProjMatrixStereo, invViewProjStereo);
}

384
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Decal/DecalSystem.cs


}
private const int kDefaultDrawDistance = 1000;
static public int DrawDistance
public int DrawDistance
{
get
{

}
}
private static readonly int m_NormalToWorldID = Shader.PropertyToID("normalToWorld");
public TextureCache2D TextureAtlas
{
get
{
if (m_DecalAtlas == null)
{
m_DecalAtlas = new TextureCache2D();
m_DecalAtlas.AllocTextureArray(2048, 128, 128, TextureFormat.RGBA32, true);
}
return m_DecalAtlas;
}
}
public Camera CurrentCamera
{
get
{
return m_Camera;
}
set
{
m_Camera = value;
}
}
private static MaterialPropertyBlock m_PropertyBlock = new MaterialPropertyBlock();
private const int kDecalBlockSize = 128;

// #if defined(SHADER_API_VULKAN) && defined(SHADER_API_MOBILE)
// #define UNITY_INSTANCED_ARRAY_SIZE 250
private const int kDrawIndexedBatchSize = 250;
private const int kDrawIndexedBatchSize = 250;
// cube mesh bounds for decal
static Vector4 kMin = new Vector4(-0.5f, -1.0f, -0.5f, 1.0f);

static public Matrix4x4[] m_InstanceMatrices = new Matrix4x4[kDrawIndexedBatchSize];
static public Matrix4x4[] m_InstanceNormalToWorld = new Matrix4x4[kDrawIndexedBatchSize];
// clustered draw data
static public DecalData[] m_DecalDatas = new DecalData[kDecalBlockSize];
static public SFiniteLightBound[] m_Bounds = new SFiniteLightBound[kDecalBlockSize];
static public LightVolumeData[] m_LightVolumes = new LightVolumeData[kDecalBlockSize];
static public int m_DecalDatasCount = 0;
private TextureCache2D m_DecalAtlas = null;
// current camera
private Camera m_Camera;
static public int m_DecalsVisibleThisFrame = 0;
private void InitializeMaterialValues()
{
m_DiffuseTexture = m_Material.GetTexture("_BaseColorMap");
m_NormalTexture = m_Material.GetTexture("_NormalMap");
m_MaskTexture = m_Material.GetTexture("_MaskMap");
m_Blend = m_Material.GetFloat("_DecalBlend");
}
public DecalSet(Material material)
{
m_Material = material;
InitializeMaterialValues();
}
private BoundingSphere GetDecalProjectBoundingSphere(Matrix4x4 decalToWorld)
{
Vector4 min = new Vector4();

BoundingSphere res = new BoundingSphere();
res.position = (max + min) / 2;
res.radius = ((Vector3)(max - min)).magnitude / 2;
res.radius = ((Vector3) (max - min)).magnitude / 2;
m_CachedTransforms[decal.CullIndex] = decal.transform.localToWorldMatrix;
m_CachedDecalToWorld[decal.CullIndex] = decal.transform.localToWorldMatrix;
float y0 = decalRotation.m01;
float y1 = decalRotation.m11;
float y2 = decalRotation.m21;
decalRotation.m01 = decalRotation.m02;
decalRotation.m11 = decalRotation.m12;
decalRotation.m21 = decalRotation.m22;
decalRotation.m02 = y0;
decalRotation.m12 = y1;
decalRotation.m22 = y2;
float y0 = decalRotation.m01;
float y1 = decalRotation.m11;
float y2 = decalRotation.m21;
decalRotation.m01 = decalRotation.m02;
decalRotation.m11 = decalRotation.m12;
decalRotation.m21 = decalRotation.m22;
decalRotation.m02 = y0;
decalRotation.m12 = y1;
decalRotation.m22 = y2;
// draw distance can't be more than global draw distance
m_CachedDrawDistances[decal.CullIndex].x = decal.m_DrawDistance < DrawDistance ? decal.m_DrawDistance : DrawDistance;
// draw distance can't be more than global draw distance
m_CachedDrawDistances[decal.CullIndex].x = decal.m_DrawDistance < instance.DrawDistance
? decal.m_DrawDistance
: instance.DrawDistance;
m_BoundingSpheres[decal.CullIndex] = GetDecalProjectBoundingSphere(m_CachedTransforms[decal.CullIndex]);
m_BoundingSpheres[decal.CullIndex] = GetDecalProjectBoundingSphere(m_CachedDecalToWorld[decal.CullIndex]);
}
public void AddDecal(DecalProjectorComponent decal)

m_Decals.CopyTo(newDecals, 0);
m_BoundingSpheres.CopyTo(newSpheres, 0);
m_CachedTransforms.CopyTo(newCachedTransforms, 0);
m_CachedDecalToWorld.CopyTo(newCachedTransforms, 0);
m_CachedDrawDistances.CopyTo(newCachedDrawDistances, 0);
m_CachedDrawDistances.CopyTo(newCachedDrawDistances, 0);
m_CachedTransforms = newCachedTransforms;
m_CachedDecalToWorld = newCachedTransforms;
m_CachedDrawDistances = newCachedDrawDistances;
m_CachedDrawDistances = newCachedDrawDistances;
}
m_Decals[m_DecalsCount] = decal;

// update the bounding spheres array
m_BoundingSpheres[removeAtIndex] = m_BoundingSpheres[m_DecalsCount - 1];
m_CachedTransforms[removeAtIndex] = m_CachedTransforms[m_DecalsCount - 1];
m_CachedDecalToWorld[removeAtIndex] = m_CachedDecalToWorld[m_DecalsCount - 1];
m_CachedDrawDistances[removeAtIndex] = m_CachedDrawDistances[m_DecalsCount - 1];
m_CachedDrawDistances[removeAtIndex] = m_CachedDrawDistances[m_DecalsCount - 1];
public void BeginCull(Camera camera)
public void BeginCull()
{
if (m_CullingGroup != null)
{

// let the culling group code do some of the heavy lifting for global draw distance
m_BoundingDistances[0] = DrawDistance;
// let the culling group code do some of the heavy lifting for global draw distance
m_BoundingDistances[0] = DecalSystem.instance.DrawDistance;
m_CullingGroup.targetCamera = camera;
m_CullingGroup.SetDistanceReferencePoint(camera.transform.position);
m_CullingGroup.SetBoundingDistances(m_BoundingDistances);
m_CullingGroup.targetCamera = instance.CurrentCamera;
m_CullingGroup.SetDistanceReferencePoint( m_CullingGroup.targetCamera.transform.position);
m_CullingGroup.SetBoundingDistances(m_BoundingDistances);
m_CullingGroup.SetBoundingSpheres(m_BoundingSpheres);
m_CullingGroup.SetBoundingSphereCount(m_DecalsCount);
}

return m_NumResults;
}
private void GetDecalVolumeDataAndBound(Matrix4x4 decalToWorld, Matrix4x4 worldToView)
{
var influenceX = decalToWorld.GetColumn(0) * 0.5f;
var influenceY = decalToWorld.GetColumn(1) * 0.5f;
var influenceZ = decalToWorld.GetColumn(2) * 0.5f;
var pos = decalToWorld.GetColumn(3) - influenceY; // decal cube mesh pivot is at 0,0,0, with bottom face at -1 on the y plane
Vector3 influenceExtents = new Vector3();
influenceExtents.x = influenceX.magnitude;
influenceExtents.y = influenceY.magnitude;
influenceExtents.z = influenceZ.magnitude;
// transform to camera space (becomes a left hand coordinate frame in Unity since Determinant(worldToView)<0)
var influenceRightVS = worldToView.MultiplyVector(influenceX / influenceExtents.x);
var influenceUpVS = worldToView.MultiplyVector(influenceY / influenceExtents.y);
var influenceForwardVS = worldToView.MultiplyVector(influenceZ / influenceExtents.z);
var influencePositionVS = worldToView.MultiplyPoint(pos); // place the mesh pivot in the center
m_Bounds[m_DecalDatasCount].center = influencePositionVS;
m_Bounds[m_DecalDatasCount].boxAxisX = influenceRightVS * influenceExtents.x;
m_Bounds[m_DecalDatasCount].boxAxisY = influenceUpVS * influenceExtents.y;
m_Bounds[m_DecalDatasCount].boxAxisZ = influenceForwardVS * influenceExtents.z;
m_Bounds[m_DecalDatasCount].scaleXY.Set(1.0f, 1.0f);
m_Bounds[m_DecalDatasCount].radius = influenceExtents.magnitude;
// The culling system culls pixels that are further
// than a threshold to the box influence extents.
// So we use an arbitrary threshold here (k_BoxCullingExtentOffset)
m_LightVolumes[m_DecalDatasCount].lightCategory = (uint)LightCategory.Decal;
m_LightVolumes[m_DecalDatasCount].lightVolume = (uint)LightVolumeType.Box;
m_LightVolumes[m_DecalDatasCount].featureFlags = (uint)LightFeatureFlags.Env;
m_LightVolumes[m_DecalDatasCount].lightPos = influencePositionVS;
m_LightVolumes[m_DecalDatasCount].lightAxisX = influenceRightVS;
m_LightVolumes[m_DecalDatasCount].lightAxisY = influenceUpVS;
m_LightVolumes[m_DecalDatasCount].lightAxisZ = influenceForwardVS;
m_LightVolumes[m_DecalDatasCount].boxInnerDist = influenceExtents - LightLoop.k_BoxCullingExtentThreshold;
m_LightVolumes[m_DecalDatasCount].boxInvRange.Set(1.0f / LightLoop.k_BoxCullingExtentThreshold.x, 1.0f /LightLoop. k_BoxCullingExtentThreshold.y, 1.0f / LightLoop.k_BoxCullingExtentThreshold.z);
}
private void AssignCurrentBatches(ref Matrix4x4[] decalToWorldBatch, ref Matrix4x4[] normalToWorldBatch, int batchCount)
{
if (m_DecalToWorld.Count == batchCount)
{
decalToWorldBatch = new Matrix4x4[kDrawIndexedBatchSize];
m_DecalToWorld.Add(decalToWorldBatch);
normalToWorldBatch = new Matrix4x4[kDrawIndexedBatchSize];
m_NormalToWorld.Add(normalToWorldBatch);
}
else
{
decalToWorldBatch = m_DecalToWorld[batchCount];
normalToWorldBatch = m_NormalToWorld[batchCount];
}
}
public void CreateDrawData()
{
if (m_NumResults == 0)
return;
int instanceCount = 0;
int batchCount = 0;
Matrix4x4[] decalToWorldBatch = null;
Matrix4x4[] normalToWorldBatch = null;
AssignCurrentBatches(ref decalToWorldBatch, ref normalToWorldBatch, batchCount);
Vector3 cameraPos = instance.CurrentCamera.transform.position;
Matrix4x4 worldToView = LightLoop.WorldToCamera(instance.CurrentCamera);
for (int resultIndex = 0; resultIndex < m_NumResults; resultIndex++)
{
int decalIndex = m_ResultIndices[resultIndex];
// do additional culling based on individual decal draw distances
float distanceToDecal = (cameraPos - m_BoundingSpheres[decalIndex].position).magnitude;
float cullDistance = m_CachedDrawDistances[decalIndex].x + m_BoundingSpheres[decalIndex].radius;
if (distanceToDecal < cullDistance)
{
// d-buffer data
decalToWorldBatch[instanceCount] = m_CachedDecalToWorld[decalIndex];
normalToWorldBatch[instanceCount] = m_CachedNormalToWorld[decalIndex];
float fadeFactor = Mathf.Clamp((cullDistance - distanceToDecal) / (cullDistance * (1.0f - m_CachedDrawDistances[decalIndex].y)), 0.0f, 1.0f);
normalToWorldBatch[instanceCount].m03 = fadeFactor * m_Blend; // vector3 rotation matrix so bottom row and last column can be used for other data to save space
normalToWorldBatch[instanceCount].m13 = m_DiffuseTexIndex; // texture atlas indices needed for clustered
normalToWorldBatch[instanceCount].m23 = m_NormalTexIndex;
normalToWorldBatch[instanceCount].m33 = m_MaskTexIndex;
// clustered forward data
m_DecalDatas[m_DecalDatasCount].worldToDecal = decalToWorldBatch[instanceCount].inverse;
m_DecalDatas[m_DecalDatasCount].normalToWorld = normalToWorldBatch[instanceCount];
GetDecalVolumeDataAndBound(decalToWorldBatch[instanceCount], worldToView);
m_DecalDatasCount++;
instanceCount++;
if (instanceCount == kDrawIndexedBatchSize)
{
instanceCount = 0;
batchCount++;
AssignCurrentBatches(ref decalToWorldBatch, ref normalToWorldBatch, batchCount);
}
}
}
}
public void EndCull()
{
if (m_CullingGroup == null)

}
}
public void Render(ScriptableRenderContext renderContext, HDCamera camera, CommandBuffer cmd)
void UpdateTextureCache(CommandBuffer cmd)
int instanceCount = 0;
Vector3 cameraPos = camera.cameraPos;
for (int resultIndex = 0; resultIndex < m_NumResults; resultIndex++)
if (m_DiffuseTexture != null)
int decalIndex = m_ResultIndices[resultIndex];
// do additional culling based on individual decal draw distances
float distanceToDecal = (cameraPos - m_BoundingSpheres[decalIndex].position).magnitude;
float cullDistance = m_CachedDrawDistances[decalIndex].x + m_BoundingSpheres[decalIndex].radius;
if (distanceToDecal < cullDistance)
{
m_InstanceMatrices[instanceCount] = m_CachedTransforms[decalIndex];
m_InstanceNormalToWorld[instanceCount] = m_CachedNormalToWorld[decalIndex];
float fadeFactor = (cullDistance - distanceToDecal) / (cullDistance * (1.0f - m_CachedDrawDistances[decalIndex].y));
m_InstanceNormalToWorld[instanceCount].m03 = fadeFactor; // rotation only matrix so 3rd column can be used to pass some values
instanceCount++;
if (instanceCount == kDrawIndexedBatchSize)
{
m_PropertyBlock.SetMatrixArray(m_NormalToWorldID, m_InstanceNormalToWorld);
cmd.DrawMeshInstanced(m_DecalMesh, 0, KeyMaterial, 0, m_InstanceMatrices, kDrawIndexedBatchSize, m_PropertyBlock);
instanceCount = 0;
}
}
m_DiffuseTexIndex = instance.TextureAtlas.FetchSlice(cmd, m_DiffuseTexture);
if (instanceCount > 0)
else
m_PropertyBlock.SetMatrixArray(m_NormalToWorldID, m_InstanceNormalToWorld);
cmd.DrawMeshInstanced(m_DecalMesh, 0, KeyMaterial, 0, m_InstanceMatrices, instanceCount, m_PropertyBlock);
m_DiffuseTexIndex = -1;
}
if (m_NormalTexture != null)
{
m_NormalTexIndex = instance.TextureAtlas.FetchSlice(cmd, m_NormalTexture);
}
else
{
m_NormalTexIndex = -1;
}
if (m_MaskTexture != null)
{
m_MaskTexIndex = instance.TextureAtlas.FetchSlice(cmd, m_MaskTexture);
}
else
{
m_MaskTexIndex = -1;
public void RemoveFromTextureCache()
{
if (m_DiffuseTexture != null)
{
instance.TextureAtlas.RemoveEntryFromSlice(m_DiffuseTexture);
}
if (m_NormalTexture != null)
{
instance.TextureAtlas.RemoveEntryFromSlice(m_NormalTexture);
}
if (m_MaskTexture != null)
{
instance.TextureAtlas.RemoveEntryFromSlice(m_MaskTexture);
}
}
public void UpdateCachedMaterialData(CommandBuffer cmd)
{
InitializeMaterialValues(); // refresh in case they changed in the UI
UpdateTextureCache(cmd);
}
public void RenderIntoDBuffer(CommandBuffer cmd)
{
if(m_NumResults == 0)
return;
int batchIndex = 0;
int totalToDraw = m_NumResults;
for (; batchIndex < m_NumResults / kDrawIndexedBatchSize; batchIndex++)
{
m_PropertyBlock.SetMatrixArray(HDShaderIDs._NormalToWorldID, m_NormalToWorld[batchIndex]);
cmd.DrawMeshInstanced(m_DecalMesh, 0, KeyMaterial, 0, m_DecalToWorld[batchIndex], kDrawIndexedBatchSize, m_PropertyBlock);
totalToDraw -= kDrawIndexedBatchSize;
}
if(totalToDraw > 0)
{
m_PropertyBlock.SetMatrixArray(HDShaderIDs._NormalToWorldID, m_NormalToWorld[batchIndex]);
cmd.DrawMeshInstanced(m_DecalMesh, 0, KeyMaterial, 0, m_DecalToWorld[batchIndex], totalToDraw, m_PropertyBlock);
}
}
public Material KeyMaterial
{

}
set
{
this.m_Material = value;
}
}
public int Count

}
}
private List<Matrix4x4[]> m_DecalToWorld = new List<Matrix4x4[]>();
private List<Matrix4x4[]> m_NormalToWorld = new List<Matrix4x4[]>();
private CullingGroup m_CullingGroup = null;
private BoundingSphere[] m_BoundingSpheres = new BoundingSphere[kDecalBlockSize];
private DecalProjectorComponent[] m_Decals = new DecalProjectorComponent[kDecalBlockSize];

private Matrix4x4[] m_CachedTransforms = new Matrix4x4[kDecalBlockSize];
private Matrix4x4[] m_CachedDecalToWorld = new Matrix4x4[kDecalBlockSize];
private Texture m_DiffuseTexture = null;
private Texture m_NormalTexture = null;
private Texture m_MaskTexture = null;
private float m_Blend = 0;
private int m_DiffuseTexIndex = -1;
private int m_NormalTexIndex = -1;
private int m_MaskTexIndex = -1;
public void AddDecal(DecalProjectorComponent decal)
{
if (decal.CullIndex != DecalProjectorComponent.kInvalidIndex) //do not add the same decal more than once

int key = decal.m_Material.GetInstanceID();
if (!m_DecalSets.TryGetValue(key, out decalSet))
{
decalSet = new DecalSet();
decalSet.KeyMaterial = decal.m_Material;
decalSet = new DecalSet(decal.m_Material);
m_DecalSets.Add(key, decalSet);
}
decalSet.AddDecal(decal);

decalSet.RemoveDecal(decal);
if (decalSet.Count == 0)
{
decalSet.RemoveFromTextureCache();
m_DecalSets.Remove(key);
}
}

}
}
public void BeginCull(Camera camera)
public void BeginCull()
pair.Value.BeginCull(camera);
pair.Value.BeginCull();
public int QueryCullResults()
private int QueryCullResults()
{
int totalVisibleDecals = 0;
foreach (var pair in m_DecalSets)

public void EndCull()
{
m_DecalsVisibleThisFrame = QueryCullResults();
foreach (var pair in m_DecalSets)
{
pair.Value.EndCull();

public void Render(ScriptableRenderContext renderContext, HDCamera camera, CommandBuffer cmd)
// need a better way than passing light loop here
public void RenderIntoDBuffer(CommandBuffer cmd)
{
if (m_DecalMesh == null)
m_DecalMesh = CoreUtils.CreateCubeMesh(kMin, kMax);

pair.Value.Render(renderContext, camera, cmd);
}
pair.Value.RenderIntoDBuffer(cmd);
}
}
public void SetAtlas(CommandBuffer cmd)
{
cmd.SetGlobalTexture(HDShaderIDs._DecalAtlasID, TextureAtlas.GetTexCache());
}
// updates textures, texture atlas indices and blend value
public void UpdateCachedMaterialData(CommandBuffer cmd)
{
foreach (var pair in m_DecalSets)
{
pair.Value.UpdateCachedMaterialData(cmd);
}
}
public void CreateDrawData()
{
m_DecalDatasCount = 0;
// reallocate if needed
if (m_DecalsVisibleThisFrame > m_DecalDatas.Length)
{
int newDecalDatasSize = ((m_DecalsVisibleThisFrame + kDecalBlockSize - 1) / kDecalBlockSize) * kDecalBlockSize;
m_DecalDatas = new DecalData[newDecalDatasSize];
m_Bounds = new SFiniteLightBound[newDecalDatasSize];
m_LightVolumes = new LightVolumeData[newDecalDatasSize];
}
foreach (var pair in m_DecalSets)
{
pair.Value.CreateDrawData();
}
}
public void Cleanup()
{
if (m_DecalAtlas != null)
m_DecalAtlas.Release();
CoreUtils.Destroy(m_DecalMesh);
}
}
}

39
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/HDCameraUI.cs


Inspector = new []
{
SectionPrimarySettings,
SectionPhysicalSettings,
SectionCaptureSettings,
SectionOutputSettings,
SectionXRSettings,

CED.Action(Drawer_FieldRenderingPath),
CED.space
);
public static readonly CED.IDrawer SectionPhysicalSettings = CED.FoldoutGroup(
"Physical Settings",
(s, p, o) => s.isSectionExpandedPhysicalSettings,
FoldoutOption.Indent,
CED.Action(Drawer_FieldAperture),
CED.Action(Drawer_FieldShutterSpeed),
CED.Action(Drawer_FieldIso));
public static readonly CED.IDrawer SectionCaptureSettings = CED.FoldoutGroup(
"Capture Settings",

SerializedHDCamera m_SerializedHdCamera;
public AnimBool isSectionExpandedOrthoOptions { get { return m_AnimBools[0]; } }
public AnimBool isSectionExpandedCaptureSettings { get { return m_AnimBools[1]; } }
public AnimBool isSectionExpandedOutputSettings { get { return m_AnimBools[2]; } }
public AnimBool isSectionAvailableRenderLoopSettings { get { return m_AnimBools[3]; } }
public AnimBool isSectionExpandedXRSettings { get { return m_AnimBools[4]; } }
public AnimBool isSectionAvailableXRSettings { get { return m_AnimBools[5]; } }
public AnimBool isSectionExpandedPhysicalSettings { get { return m_AnimBools[1]; } }
public AnimBool isSectionExpandedCaptureSettings { get { return m_AnimBools[2]; } }
public AnimBool isSectionExpandedOutputSettings { get { return m_AnimBools[3]; } }
public AnimBool isSectionAvailableRenderLoopSettings { get { return m_AnimBools[4]; } }
public AnimBool isSectionExpandedXRSettings { get { return m_AnimBools[5]; } }
public AnimBool isSectionAvailableXRSettings { get { return m_AnimBools[6]; } }
public bool canOverrideRenderLoopSettings { get; set; }

: base(6)
: base(7)
{
canOverrideRenderLoopSettings = false;
}

"Clipping Planes",
new[] { p.nearClippingPlane, p.farClippingPlane },
new[] { _.GetContent("Near|The closest point relative to the camera that drawing will occur."), _.GetContent("Far|The furthest point relative to the camera that drawing will occur.\n") });
}
static void Drawer_FieldAperture(HDCameraUI s, SerializedHDCamera p, Editor owner)
{
EditorGUILayout.PropertyField(p.aperture, _.GetContent("Aperture"));
}
static void Drawer_FieldShutterSpeed(HDCameraUI s, SerializedHDCamera p, Editor owner)
{
p.shutterSpeed.floatValue = 1f / p.shutterSpeed.floatValue;
EditorGUILayout.PropertyField(p.shutterSpeed, _.GetContent("Shutter Speed (1 / x)"));
p.shutterSpeed.floatValue = 1f / p.shutterSpeed.floatValue;
}
static void Drawer_FieldIso(HDCameraUI s, SerializedHDCamera p, Editor owner)
{
EditorGUILayout.PropertyField(p.iso, _.GetContent("ISO"));
}
static void Drawer_FieldNormalizedViewPort(HDCameraUI s, SerializedHDCamera p, Editor owner)

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Camera/SerializedHDCamera.cs


public SerializedProperty farClippingPlane;
public SerializedProperty targetEye;
public SerializedProperty aperture;
public SerializedProperty shutterSpeed;
public SerializedProperty iso;
#if ENABLE_MULTIPLE_DISPLAYS
public SerializedProperty targetDisplay;
#endif

targetEye = serializedObject.FindProperty("m_TargetEye");
aperture = serializedAdditionalDataObject.Find((HDAdditionalCameraData d) => d.aperture);
shutterSpeed = serializedAdditionalDataObject.Find((HDAdditionalCameraData d) => d.shutterSpeed);
iso = serializedAdditionalDataObject.Find((HDAdditionalCameraData d) => d.iso);
clearColorMode = serializedAdditionalDataObject.Find((HDAdditionalCameraData d) => d.clearColorMode);
backgroundColorHDR = serializedAdditionalDataObject.Find((HDAdditionalCameraData d) => d.backgroundColorHDR);

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDAssetFactory.cs


newAsset.debugColorPickerShader = Load<Shader>(HDRenderPipelinePath + "Debug/DebugColorPicker.Shader");
newAsset.deferredShader = Load<Shader>(HDRenderPipelinePath + "Lighting/Deferred.Shader");
newAsset.gaussianPyramidCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/ColorPyramid.compute");
newAsset.colorPyramidCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/ColorPyramid.compute");
newAsset.depthPyramidCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/DepthPyramid.compute");
newAsset.copyChannelCS = Load<ComputeShader>(CorePath + "CoreResources/GPUCopy.compute");
newAsset.applyDistortionCS = Load<ComputeShader>(HDRenderPipelinePath + "RenderPipelineResources/ApplyDistorsion.compute");

46
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/HDRenderPipelineMenuItems.cs


public class HDRenderPipelineMenuItems
{
[MenuItem("Internal/HDRenderPipeline/Upgrade Scene Light Intensity to physical light unit", priority = CoreUtils.editMenuPriority2)]
static void UpgradeLightsPLU()
{
Light[] lights = Resources.FindObjectsOfTypeAll<Light>();
foreach (var l in lights)
{
var add = l.GetComponent<HDAdditionalLightData>();
if (add == null)
{
continue;
}
// We only need to update the new intensity parameters on additional data, no need to change intensity
if (add.lightTypeExtent == LightTypeExtent.Punctual)
{
switch (l.type)
{
case LightType.Point:
add.punctualIntensity = l.intensity / LightUtils.ConvertPointLightIntensity(1.0f);
break;
case LightType.Spot:
add.punctualIntensity = l.intensity / LightUtils.ConvertPointLightIntensity(1.0f);
break;
case LightType.Directional:
add.directionalIntensity = l.intensity;
break;
}
}
else if (add.lightTypeExtent == LightTypeExtent.Rectangle)
{
add.areaIntensity = l.intensity / LightUtils.ConvertRectLightIntensity(1.0f, add.shapeWidth, add.shapeHeight);
}
else if (add.lightTypeExtent == LightTypeExtent.Line)
{
add.areaIntensity = l.intensity / LightUtils.calculateLineLightArea(1.0f, add.shapeWidth);
}
}
var scene = SceneManager.GetActiveScene();
EditorSceneManager.MarkSceneDirty(scene);
}
[MenuItem("Internal/HDRenderPipeline/Add \"Additional Light-shadow Data\" (if not present)")]
static void AddAdditionalLightData()
{

12
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.Styles.cs


public readonly GUIContent indirectBounceShadowWarning = new GUIContent("Realtime indirect bounce shadowing is not supported for Spot and Point lights.");
// Additional light data
public readonly GUIContent directionalIntensity = new GUIContent("Intensity (Lux)", "");
public readonly GUIContent punctualIntensity = new GUIContent("Intensity (Lumen)", "");
public readonly GUIContent areaIntensity = new GUIContent("Intensity (Lumen)", "");
public readonly GUIContent maxSmoothness = new GUIContent("Max Smoothness", "Very low cost way of faking spherical area lighting. This will modify the roughness of the material lit. This is useful when the specular highlight is too small or too sharp.");
public readonly GUIContent affectDiffuse = new GUIContent("Affect Diffuse", "This will disable diffuse lighting for this light. Doesn't save performance, diffuse lighting is still computed.");

public readonly GUIContent[] shapeNames;
// Additional shadow data
public readonly GUIContent shadowCascades = new GUIContent("Cascades", "");
public readonly GUIContent shadowCascadeCount = new GUIContent("Cascade Count", "");
public readonly GUIContent[] shadowCascadeRatios = { new GUIContent("Cascade 1"), new GUIContent("Cascade 2"), new GUIContent("Cascade 3") };
public readonly GUIContent contactShadow = new GUIContent("Contact Shadows");
public readonly GUIContent contactShadowLength = new GUIContent("Length", "Length of rays used to gather contact shadows in world units.\nZero will disable the feature.");
public readonly GUIContent contactShadowDistanceScaleFactor = new GUIContent("Distance Scale Factor", "Contact Shadows are scaled up with distance. Use this parameter to dampen this effect.");
public readonly GUIContent contactShadowMaxDistance = new GUIContent("Max Distance", "Distance from the camera in world units at which contact shadows are faded out to zero.");
public readonly GUIContent contactShadowFadeDistance = new GUIContent("Fade Distance", "Distance in world units over which the contact shadows are faded out (see Max Distance).");
public readonly GUIContent contactShadowSampleCount = new GUIContent("Sample Count", "Number of samples when ray casting.");
// Bias control
public readonly GUIContent viewBiasMin = new GUIContent("View Bias");

136
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Lighting/HDLightEditor.cs


{
sealed class SerializedLightData
{
public SerializedProperty directionalIntensity;
public SerializedProperty punctualIntensity;
public SerializedProperty areaIntensity;
public SerializedProperty spotInnerPercent;
public SerializedProperty lightDimmer;
public SerializedProperty fadeDistance;

{
public SerializedProperty dimmer;
public SerializedProperty fadeDistance;
public SerializedProperty cascadeCount;
public SerializedProperty cascadeRatios;
public SerializedProperty cascadeBorders;
public SerializedProperty enableContactShadows;
public SerializedProperty contactShadowLength;
public SerializedProperty contactShadowDistanceScaleFactor;
public SerializedProperty contactShadowMaxDistance;
public SerializedProperty contactShadowFadeDistance;
public SerializedProperty contactShadowSampleCount;
// Bias control
public SerializedProperty viewBiasMin;
public SerializedProperty viewBiasMax;

//Disc,
}
const float k_MinAreaWidth = 0.01f; // Provide a small size of 1cm for line light
// Used for UI only; the processing code must use LightTypeExtent and LightType
LightShape m_LightShape;

using (var o = new PropertyFetcher<HDAdditionalLightData>(m_SerializedAdditionalLightData))
m_AdditionalLightData = new SerializedLightData
{
directionalIntensity = o.Find(x => x.directionalIntensity),
punctualIntensity = o.Find(x => x.punctualIntensity),
areaIntensity = o.Find(x => x.areaIntensity),
spotInnerPercent = o.Find(x => x.m_InnerSpotPercent),
lightDimmer = o.Find(x => x.lightDimmer),
fadeDistance = o.Find(x => x.fadeDistance),

{
dimmer = o.Find(x => x.shadowDimmer),
fadeDistance = o.Find(x => x.shadowFadeDistance),
cascadeCount = o.Find("shadowCascadeCount"),
cascadeRatios = o.Find("shadowCascadeRatios"),
cascadeBorders = o.Find("shadowCascadeBorders"),
enableContactShadows = o.Find(x => x.enableContactShadows),
contactShadowLength = o.Find(x => x.contactShadowLength),
contactShadowDistanceScaleFactor = o.Find(x => x.contactShadowDistanceScaleFactor),
contactShadowMaxDistance = o.Find(x => x.contactShadowMaxDistance),
contactShadowFadeDistance = o.Find(x => x.contactShadowFadeDistance),
contactShadowSampleCount = o.Find(x => x.contactShadowSampleCount),
viewBiasMin = o.Find(x => x.viewBiasMin),
viewBiasMax = o.Find(x => x.viewBiasMax),

{
bool shadowsEnabled = EditorGUILayout.Toggle(CoreEditorUtils.GetContent("Enable Shadows"), settings.shadowsType.enumValueIndex != 0);
settings.shadowsType.enumValueIndex = shadowsEnabled ? (int)LightShadows.Hard : (int)LightShadows.None;
if (settings.lightType.enumValueIndex == (int)LightType.Directional)
{
EditorGUILayout.PropertyField(m_AdditionalShadowData.enableContactShadows, CoreEditorUtils.GetContent("Enable Contact Shadows"));
}
}
EditorGUILayout.PropertyField(m_AdditionalLightData.showAdditionalSettings);

{
EditorGUI.BeginChangeCheck(); // For GI we need to detect any change on additional data and call SetLightDirty + For intensity we need to detect light shape change
EditorGUI.BeginChangeCheck(); // For GI we need to detect any change on additional data and call SetLightDirty
// LightShape is HD specific, it need to drive LightType from the original LightType
// when it make sense, so the GI is still in sync with the light shape
switch (m_LightShape)

m_AdditionalLightData.lightTypeExtent.enumValueIndex = (int)LightTypeExtent.Rectangle;
EditorGUILayout.PropertyField(m_AdditionalLightData.shapeWidth, s_Styles.shapeWidthRect);
EditorGUILayout.PropertyField(m_AdditionalLightData.shapeHeight, s_Styles.shapeHeightRect);
m_AdditionalLightData.shapeWidth.floatValue = Mathf.Max(m_AdditionalLightData.shapeWidth.floatValue, k_MinAreaWidth);
m_AdditionalLightData.shapeHeight.floatValue = Mathf.Max(m_AdditionalLightData.shapeHeight.floatValue, k_MinAreaWidth);
settings.areaSizeX.floatValue = m_AdditionalLightData.shapeWidth.floatValue;
settings.areaSizeY.floatValue = m_AdditionalLightData.shapeHeight.floatValue;
settings.shadowsType.enumValueIndex = (int)LightShadows.None;

settings.lightType.enumValueIndex = (int)LightType.Point;
m_AdditionalLightData.lightTypeExtent.enumValueIndex = (int)LightTypeExtent.Line;
EditorGUILayout.PropertyField(m_AdditionalLightData.shapeWidth, s_Styles.shapeWidthLine);
m_AdditionalLightData.shapeWidth.floatValue = Mathf.Max(m_AdditionalLightData.shapeWidth.floatValue, k_MinAreaWidth);
m_AdditionalLightData.shapeHeight.floatValue = Mathf.Max(m_AdditionalLightData.shapeHeight.floatValue, k_MinAreaWidth);
settings.areaSizeY.floatValue = 0.01f;
settings.areaSizeY.floatValue = k_MinAreaWidth;
settings.shadowsType.enumValueIndex = (int)LightShadows.None;
break;

if (EditorGUI.EndChangeCheck())
{
UpdateLightIntensity();
void UpdateLightIntensity()
{
switch (m_LightShape)
{
case LightShape.Directional:
settings.intensity.floatValue = m_AdditionalLightData.directionalIntensity.floatValue;
break;
case LightShape.Point:
settings.intensity.floatValue = LightUtils.ConvertPointLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue);
break;
case LightShape.Spot:
// Spot should used conversion which take into account the angle, and thus the intensity vary with angle.
// This is not easy to manipulate for lighter, so we simply consider any spot light as just occluded point light. So reuse the same code.
settings.intensity.floatValue = LightUtils.ConvertPointLightIntensity(m_AdditionalLightData.punctualIntensity.floatValue);
// TODO: What to do with box shape ?
// var spotLightShape = (SpotLightShape)m_AdditionalLightData.spotLightShape.enumValueIndex;
break;
case LightShape.Rectangle:
settings.intensity.floatValue = LightUtils.ConvertRectLightIntensity(m_AdditionalLightData.areaIntensity.floatValue, m_AdditionalLightData.shapeWidth.floatValue, m_AdditionalLightData.shapeHeight.floatValue);
break;
case LightShape.Line:
settings.intensity.floatValue = LightUtils.calculateLineLightArea(m_AdditionalLightData.areaIntensity.floatValue, m_AdditionalLightData.shapeWidth.floatValue);
break;
}
}
settings.DrawIntensity();
settings.DrawBounceIntensity();
EditorGUI.BeginChangeCheck();
switch (m_LightShape)
{
case LightShape.Directional:
EditorGUILayout.PropertyField(m_AdditionalLightData.directionalIntensity, s_Styles.directionalIntensity);
break;
case LightShape.Point:
case LightShape.Spot:
EditorGUILayout.PropertyField(m_AdditionalLightData.punctualIntensity, s_Styles.punctualIntensity);
break;
case LightShape.Rectangle:
case LightShape.Line:
EditorGUILayout.PropertyField(m_AdditionalLightData.areaIntensity, s_Styles.areaIntensity);
break;
}
if (EditorGUI.EndChangeCheck())
{
UpdateLightIntensity();
}
settings.DrawLightmapping();
EditorGUI.BeginChangeCheck(); // For GI we need to detect any change on additional data and call SetLightDirty

EditorGUILayout.Slider(m_AdditionalShadowData.viewBiasScale, 0.0f, 15.0f, s_Styles.viewBiasScale);
EditorGUILayout.Slider(settings.shadowsNearPlane, 0.01f, 10f, s_Styles.shadowNearPlane);
if (settings.lightType.enumValueIndex == (int)LightType.Directional)
{
using (var scope = new EditorGUI.ChangeCheckScope())
{
EditorGUILayout.IntSlider(m_AdditionalShadowData.cascadeCount, 1, 4, s_Styles.shadowCascadeCount);
if (scope.changed)
{
int len = m_AdditionalShadowData.cascadeCount.intValue;
m_AdditionalShadowData.cascadeRatios.arraySize = len - 1;
m_AdditionalShadowData.cascadeBorders.arraySize = len;
}
}
EditorGUI.indentLevel++;
int arraySize = m_AdditionalShadowData.cascadeRatios.arraySize;
for (int i = 0; i < arraySize; i++)
EditorGUILayout.Slider(m_AdditionalShadowData.cascadeRatios.GetArrayElementAtIndex(i), 0f, 1f, s_Styles.shadowCascadeRatios[i]);
EditorGUI.indentLevel--;
if(!m_AdditionalShadowData.enableContactShadows.hasMultipleDifferentValues && m_AdditionalShadowData.enableContactShadows.boolValue)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(s_Styles.contactShadow, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_AdditionalShadowData.contactShadowLength, s_Styles.contactShadowLength);
EditorGUILayout.PropertyField(m_AdditionalShadowData.contactShadowDistanceScaleFactor, s_Styles.contactShadowDistanceScaleFactor);
EditorGUILayout.PropertyField(m_AdditionalShadowData.contactShadowMaxDistance, s_Styles.contactShadowMaxDistance);
EditorGUILayout.PropertyField(m_AdditionalShadowData.contactShadowFadeDistance, s_Styles.contactShadowFadeDistance);
EditorGUILayout.PropertyField(m_AdditionalShadowData.contactShadowSampleCount, s_Styles.contactShadowSampleCount);
EditorGUI.indentLevel--;
}
}
if (settings.isBakedOrMixed)
DrawBakedShadowParameters();

EditorGUILayout.Slider(m_AdditionalShadowData.normalBiasMin, 0.0f, 5.0f, s_Styles.normalBiasMin);
if (EditorGUI.EndChangeCheck())
{
// Link min to max and don't expose normalBiasScale (useless when min == max)
// Link min to max and don't expose normalBiasScale (useless when min == max)
m_AdditionalShadowData.normalBiasMax = m_AdditionalShadowData.normalBiasMin;
}
//EditorGUILayout.PropertyField(m_AdditionalShadowData.normalBiasMax, s_Styles.normalBiasMax);

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/LitUI.cs


protected void ShaderSSSAndTransmissionInputGUI(Material material, int layerIndex)
{
var hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (hdPipeline == null)
return;
var diffusionProfileSettings = hdPipeline.diffusionProfileSettings;
if (hdPipeline.IsInternalDiffusionProfile(diffusionProfileSettings))

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Sky/ProceduralSky/ProceduralSkyEditor.cs


EditorGUILayout.Space();
base.CommonSkySettingsGUI();
base.CommonSkySettingsGUI(false);
}
}
}

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Sky/SkySettingsEditor.cs


SerializedDataParameter m_EnvUpdateMode;
SerializedDataParameter m_EnvUpdatePeriod;
SerializedProperty m_UseForBaking;
public override void OnEnable()
{
var o = new PropertyFetcher<SkySettings>(serializedObject);

m_EnvUpdatePeriod = Unpack(o.Find(x => x.updatePeriod));
}
protected void CommonSkySettingsGUI()
protected void CommonSkySettingsGUI(bool enableRotation = true)
PropertyField(m_SkyRotation);
if(enableRotation)
PropertyField(m_SkyRotation);
PropertyField(m_EnvUpdateMode);
if (!m_EnvUpdateMode.value.hasMultipleDifferentValues && m_EnvUpdateMode.value.intValue == (int)EnvironementUpdateMode.Realtime)

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/UpgradeStandardShaderMaterials.cs


static List<MaterialUpgrader> GetHDUpgraders()
{
var upgraders = new List<MaterialUpgrader>();
upgraders.Add(new StandardToHDLitMaterialUpgrader("Standard", "HDRenderPipeline/Lit", LitGUI.SetupMaterialKeywordsAndPass));
upgraders.Add(new StandardSpecularToHDLitMaterialUpgrader("Standard (Specular setup)", "HDRenderPipeline/Lit", LitGUI.SetupMaterialKeywordsAndPass));
upgraders.Add(new StandardsToHDLitMaterialUpgrader("Standard", "HDRenderPipeline/Lit"));
upgraders.Add(new StandardsToHDLitMaterialUpgrader("Standard (Specular setup)", "HDRenderPipeline/Lit"));
upgraders.Add(new StandardsToHDLitMaterialUpgrader("Standard (Roughness setup)", "HDRenderPipeline/Lit"));
upgraders.Add(new UnlitsToHDUnlitUpgrader("Unlit/Color", "HDRenderPipeline/Unlit"));
upgraders.Add(new UnlitsToHDUnlitUpgrader("Unlit/Texture", "HDRenderPipeline/Unlit"));
upgraders.Add(new UnlitsToHDUnlitUpgrader("Unlit/Transparent", "HDRenderPipeline/Unlit"));
upgraders.Add(new UnlitsToHDUnlitUpgrader("Unlit/Transparent Cutout", "HDRenderPipeline/Unlit"));
return upgraders;
}

3
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDCustomSamplerId.cs


DepthPrepass,
TransparentDepthPrepass,
GBuffer,
DBuffer,
DBufferRender,
DBufferPrepareDrawData,
DisplayDebugViewMaterial,
DebugViewMaterialGBuffer,
BlitDebugViewMaterialDebug,

61
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDRenderPipeline.cs


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

m_Asset = asset;
m_GPUCopy = new GPUCopy(asset.renderPipelineResources.copyChannelCS);
m_BufferPyramid = new BufferPyramid(
asset.renderPipelineResources.gaussianPyramidCS,
asset.renderPipelineResources.colorPyramidCS,
asset.renderPipelineResources.depthPyramidCS,
m_GPUCopy);

// For debugging
MousePositionDebug.instance.Cleanup();
DecalSystem.instance.Cleanup();
m_MaterialList.ForEach(material => material.Cleanup());
CoreUtils.Destroy(m_CopyStencilForNoLighting);

if (m_CurrentWidth > 0 && m_CurrentHeight > 0)
m_LightLoop.ReleaseResolutionDependentBuffers();
m_LightLoop.AllocResolutionDependentBuffers(hdCamera.actualWidth, hdCamera.actualHeight);
m_LightLoop.AllocResolutionDependentBuffers((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y, m_FrameSettings.enableStereo);
}
// Warning: (resolutionChanged == false) if you open a new Editor tab of the same size!

public override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
{
base.Render(renderContext, cameras);
RenderPipeline.BeginFrameRendering(cameras);
if (m_FrameCount != Time.frameCount)
{

{
if (camera == null)
continue;
RenderPipeline.BeginCameraRendering(camera);
if (camera.cameraType != CameraType.Reflection)
// TODO: Render only visible probes

Resize(hdCamera);
m_SkyManager.UpdateCurrentSkySettings(hdCamera);
// TODO: Float HDCamera setup higher in order to pass stereo into GetCullingParameters
ScriptableCullingParameters cullingParams;
if (!CullResults.GetCullingParameters(camera, m_FrameSettings.enableStereo, out cullingParams))
{

m_LightLoop.UpdateCullingParameters(ref cullingParams);
hdCamera.UpdateStereoDependentState(m_FrameSettings, ref cullingParams);
#if UNITY_EDITOR
// emit scene view UI

}
#endif
// decal system needs to be updated with current camera
DecalSystem.instance.BeginCull(camera);
{
// decal system needs to be updated with current camera, it needs it to set up culling and light list generation parameters
DecalSystem.instance.CurrentCamera = camera;
DecalSystem.instance.BeginCull();
}
ReflectionSystem.PrepareCull(camera, m_ReflectionProbeCullResults);

m_ReflectionProbeCullResults.Cull();
m_DbufferManager.vsibleDecalCount = 0;
if (m_FrameSettings.enableDBuffer)
using (new ProfilingSample(cmd, "DBufferPrepareDrawData", CustomSamplerId.DBufferPrepareDrawData.GetSampler()))
m_DbufferManager.vsibleDecalCount = DecalSystem.instance.QueryCullResults();
DecalSystem.instance.EndCull();
if (m_FrameSettings.enableDBuffer)
{
DecalSystem.instance.EndCull();
m_DbufferManager.vsibleDecalCount = DecalSystem.m_DecalsVisibleThisFrame;
DecalSystem.instance.UpdateCachedMaterialData(cmd); // textures, alpha or fade distances could've changed
DecalSystem.instance.CreateDrawData(); // prepare data is separate from draw
}
renderContext.SetupCameraProperties(camera, m_FrameSettings.enableStereo);
PushGlobalParams(hdCamera, cmd, diffusionProfileSettings);

RenderObjectsVelocity(m_CullResults, hdCamera, renderContext, cmd);
RenderDBuffer(hdCamera, renderContext, cmd);
RenderDBuffer(hdCamera, cmd);
RenderGBuffer(m_CullResults, hdCamera, enableBakeShadowMask, renderContext, cmd);
RenderGBuffer(m_CullResults, hdCamera, enableBakeShadowMask, renderContext, cmd);
// In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing.
CopyDepthBufferIfNeeded(cmd);

}
}
void RenderDBuffer(HDCamera camera, ScriptableRenderContext renderContext, CommandBuffer cmd)
void RenderDBuffer(HDCamera camera, CommandBuffer cmd)
using (new ProfilingSample(cmd, "DBuffer", CustomSamplerId.DBuffer.GetSampler()))
using (new ProfilingSample(cmd, "DBufferRender", CustomSamplerId.DBufferRender.GetSampler()))
{
// We need to copy depth buffer texture if we want to bind it at this stage
CopyDepthBufferIfNeeded(cmd);

HDUtils.SetRenderTarget(cmd, camera, m_DbufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer); // do not clear anymore
m_DbufferManager.SetHTile(m_DbufferManager.bufferCount, cmd);
DecalSystem.instance.Render(renderContext, camera, cmd);
DecalSystem.instance.RenderIntoDBuffer(cmd);
m_DbufferManager.SetHTileTexture(cmd);
m_DbufferManager.SetHTileTexture(cmd); // mask per 8x8 tile used for optimization when looking up dbuffer values
}
}

// In case of forward SSS we will bind all the required target. It is up to the shader to write into it or not.
if (m_FrameSettings.enableSubsurfaceScattering)
{
RenderTargetIdentifier[] m_MRTWithSSS = new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];
RenderTargetIdentifier[] m_MRTWithSSS =
new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];
m_MRTWithSSS[0] = m_CameraColorBuffer; // Store the specular color
m_MRTWithSSS[1] = m_CameraSssDiffuseLightingBuffer;
for (int i = 0; i < m_SSSBufferManager.sssBufferCount; ++i)

HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer);
}
m_ForwardAndForwardOnlyPassNames[0] = m_ForwardOnlyPassNames[0] = HDShaderPassNames.s_ForwardOnlyName;
m_ForwardAndForwardOnlyPassNames[0] = m_ForwardOnlyPassNames[0] =
HDShaderPassNames.s_ForwardOnlyName;
var passNames = m_FrameSettings.enableForwardRenderingOnly ? m_ForwardAndForwardOnlyPassNames : m_ForwardOnlyPassNames;
var passNames = m_FrameSettings.enableForwardRenderingOnly
? m_ForwardAndForwardOnlyPassNames
: m_ForwardOnlyPassNames;
if (m_FrameSettings.enableDBuffer) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
{
DecalSystem.instance.SetAtlas(cmd); // for clustered decals
}
RenderTransparentRenderList(cullResults, camera, renderContext, cmd, m_AllTransparentPassNames, m_currentRendererConfigurationBakedLighting, pass == ForwardPass.PreRefraction ? HDRenderQueue.k_RenderQueue_PreRefraction : HDRenderQueue.k_RenderQueue_Transparent);
}
}

15
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDStringConstants.cs


public static readonly int g_vBoundsBuffer = Shader.PropertyToID("g_vBoundsBuffer");
public static readonly int _LightVolumeData = Shader.PropertyToID("_LightVolumeData");
public static readonly int g_data = Shader.PropertyToID("g_data");
public static readonly int g_mProjection = Shader.PropertyToID("g_mProjection");
public static readonly int g_mInvProjection = Shader.PropertyToID("g_mInvProjection");
public static readonly int g_mProjectionArr = Shader.PropertyToID("g_mProjectionArr");
public static readonly int g_mInvProjectionArr = Shader.PropertyToID("g_mInvProjectionArr");
public static readonly int g_viDimensions = Shader.PropertyToID("g_viDimensions");
public static readonly int g_vLightList = Shader.PropertyToID("g_vLightList");

public static readonly int _SrcBlend = Shader.PropertyToID("_SrcBlend");
public static readonly int _DstBlend = Shader.PropertyToID("_DstBlend");
public static readonly int _HTile = Shader.PropertyToID("_HTile");
// all decal properties
public static readonly int _NormalToWorldID = Shader.PropertyToID("_NormalToWorld");
public static readonly int _DecalAtlasID = Shader.PropertyToID("_DecalAtlas");
public static readonly int _DecalIndexShift = Shader.PropertyToID("_DecalIndexShift");
public static readonly int _DecalCount = Shader.PropertyToID("_DecalCount");
public static readonly int _DecalDatas = Shader.PropertyToID("_DecalDatas");
public static readonly int _ViewMatrix = Shader.PropertyToID("_ViewMatrix");
public static readonly int _InvViewMatrix = Shader.PropertyToID("_InvViewMatrix");

public static readonly int _TaaFrameIndex = Shader.PropertyToID("_TaaFrameIndex");
public static readonly int _TaaFrameRotation = Shader.PropertyToID("_TaaFrameRotation");
public static readonly int _ViewMatrixStereo = Shader.PropertyToID("_ViewMatrixStereo");
public static readonly int _ViewProjMatrixStereo = Shader.PropertyToID("_ViewProjMatrixStereo");
public static readonly int _InvViewMatrixStereo = Shader.PropertyToID("_InvViewMatrixStereo");
public static readonly int _InvProjMatrixStereo = Shader.PropertyToID("_InvProjMatrixStereo");
public static readonly int _InvViewProjMatrixStereo = Shader.PropertyToID("_InvViewProjMatrixStereo");

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/HDUtils.cs


cmd.Blit(source, destination, new Vector2(camera.scaleBias.x, camera.scaleBias.y), Vector2.zero);
}
// This particular case is for blitting a camera-scaled texture into a non scaling texture. So we setup the full viewport (implicit in cmd.Blit) but have to scale the input UVs.
// This particular case is for blitting a non-scaled texture into a scaled texture. So we setup the partial viewport but don't scale the input UVs.
public static void BlitCameraTexture(CommandBuffer cmd, HDCamera camera, RenderTargetIdentifier source, RTHandle destination)
{
// Will set the correct camera viewport as well.

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/DeferredDirectionalShadow.compute


#include "../ShaderVariables.hlsl"
#include "Lighting.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
//#pragma enable_d3d11_debug_symbols
RWTexture2D<float4> _DeferredShadowTextureUAV;

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDAdditionalLightData.cs


float m_Version = 1.0f;
#pragma warning restore 414
// To be able to have correct default values for our lights and to also control the conversion of intensity from the light editor (so it is compatible with GI)
// we add intensity (for each type of light we want to manage).
public float directionalIntensity = Mathf.PI; // In Lux
public float punctualIntensity = 600.0f; // Light default to 600 lumen, i.e ~48 candela
public float areaIntensity = 200.0f; // Light default to 200 lumen to better match point light
[Range(0.0f, 100.0f)]
public float m_InnerSpotPercent = 0.0f; // To display this field in the UI this need to be public

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Light/HDLightEditorUtilities.cs


{
var RectangleSize = new Vector3(arealight.areaSize.x, arealight.areaSize.y, 0);
Gizmos.matrix = arealight.transform.localToWorldMatrix;
// Remove scale for light, not take into account
var localToWorldMatrix = Matrix4x4.TRS(arealight.transform.position, arealight.transform.rotation, Vector3.one);
Gizmos.matrix = localToWorldMatrix;
Gizmos.DrawWireCube(Vector3.zero, RectangleSize);
Gizmos.matrix = Matrix4x4.identity;
Gizmos.DrawWireSphere(arealight.transform.position, arealight.range);

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/Deferred.compute


#include "../../Debug/DebugDisplay.hlsl"
#include "../../Lighting/Lighting.hlsl" // This include Material.hlsl
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
//-------------------------------------------------------------------------------------
// variable declaration
//-------------------------------------------------------------------------------------

255
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs


scInit.dataSyncer = syncer;
scInit.resourceBinder = binder;
m_ShadowMgr = new ShadowManager(shadowSettings, ref scInit, m_Shadowmaps);
ShadowManager.ShadowBudgets budgets;
budgets.maxPointLights = 6;
budgets.maxSpotLights = 12;
budgets.maxDirectionalLights = 1;
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
bool useGlobalOverrides = true;
m_ShadowMgr.SetGlobalShadowOverride( GPUShadowType.Point , ShadowAlgorithm.PCF, ShadowVariant.V2, ShadowPrecision.High, useGlobalOverrides );

Punctual,
Area,
Env,
Decal,
DensityVolume,
Count
}

Env = 1 << 15,
Sky = 1 << 16,
SSRefraction = 1 << 17,
SSReflection = 1 << 18,
SSReflection = 1 << 18
// If adding more light be sure to not overflow LightDefinitions.s_LightFeatureMaskFlags
}

EnvironmentAndPunctual = 5,
EnvironmentAndArea = 6,
EnvironmentAndAreaAndPunctual = 7,
DensityVolumes = 8
Decal = 8,
DensityVolumes = 9
public const int k_MaxLightsOnScreen = k_MaxDirectionalLightsOnScreen + k_MaxPunctualLightsOnScreen + k_MaxAreaLightsOnScreen;
public const int k_MaxDecalsOnScreen = 512;
public const int k_MaxLightsOnScreen = k_MaxDirectionalLightsOnScreen + k_MaxPunctualLightsOnScreen + k_MaxAreaLightsOnScreen + k_MaxDecalsOnScreen;
static readonly Vector3 k_BoxCullingExtentThreshold = Vector3.one * 0.01f;
public const int k_MaxStereoEyes = 2;
public static readonly Vector3 k_BoxCullingExtentThreshold = Vector3.one * 0.01f;
// Static keyword is required here else we get a "DestroyBuffer can only be called from the main thread"
static ComputeBuffer s_DirectionalLightDatas = null;

static ComputeBuffer s_DecalDatas = null;
static Texture2DArray s_DefaultTexture2DArray;
static Cubemap s_DefaultTextureCube;

public List<SFiniteLightBound> bounds;
public List<LightVolumeData> lightVolumes;
public List<SFiniteLightBound> rightEyeBounds;
public List<LightVolumeData> rightEyeLightVolumes;
public void Clear()
{

bounds.Clear();
lightVolumes.Clear();
rightEyeBounds.Clear();
rightEyeLightVolumes.Clear();
}
public void Allocate()

bounds = new List<SFiniteLightBound>();
lightVolumes = new List<LightVolumeData>();
rightEyeBounds = new List<SFiniteLightBound>();
rightEyeLightVolumes = new List<LightVolumeData>();
}
}

int GetNumTileFtplX(HDCamera hdCamera)
{
return (hdCamera.actualWidth + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
return ((int)hdCamera.screenSize.x + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
return (hdCamera.actualHeight + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
return ((int)hdCamera.screenSize.y + (LightDefinitions.s_TileSizeFptl - 1)) / LightDefinitions.s_TileSizeFptl;
return (hdCamera.actualWidth + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
return ((int)hdCamera.screenSize.x + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
return (hdCamera.actualHeight + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
return ((int)hdCamera.screenSize.y + (LightDefinitions.s_TileSizeClustered - 1)) / LightDefinitions.s_TileSizeClustered;
}
public bool GetFeatureVariantsEnabled()

s_LightDatas = new ComputeBuffer(k_MaxPunctualLightsOnScreen + k_MaxAreaLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightData)));
s_EnvLightDatas = new ComputeBuffer(k_MaxEnvLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(EnvLightData)));
s_shadowDatas = new ComputeBuffer(k_MaxCascadeCount + k_MaxShadowOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(ShadowData)));
s_DecalDatas = new ComputeBuffer(k_MaxDecalsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(DecalData)));
GlobalLightLoopSettings gLightLoopSettings = hdAsset.GetRenderPipelineSettings().lightLoopSettings;
m_CookieTexArray = new TextureCache2D();

s_GenAABBKernel = buildScreenAABBShader.FindKernel("ScreenBoundsAABB");
s_AABBBoundsBuffer = new ComputeBuffer(2 * k_MaxLightsOnScreen, 3 * sizeof(float));
s_ConvexBoundsBuffer = new ComputeBuffer(k_MaxLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SFiniteLightBound)));
s_LightVolumeDataBuffer = new ComputeBuffer(k_MaxLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightVolumeData)));
// The bounds and light volumes are view-dependent, and AABB is additionally projection dependent.
// The view and proj matrices are per eye in stereo. This means we have to double the size of these buffers.
// TODO: Maybe in stereo, we will only support half as many lights total, in order to minimize buffer size waste.
// Alternatively, we could re-size these buffers if any stereo camera is active, instead of unilaterally increasing buffer size.
// TODO: I don't think k_MaxLightsOnScreen corresponds to the actual correct light count for cullable light types (punctual, area, env, decal)
s_AABBBoundsBuffer = new ComputeBuffer(k_MaxStereoEyes * 2 * k_MaxLightsOnScreen, 3 * sizeof(float));
s_ConvexBoundsBuffer = new ComputeBuffer(k_MaxStereoEyes* k_MaxLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SFiniteLightBound)));
s_LightVolumeDataBuffer = new ComputeBuffer(k_MaxStereoEyes* k_MaxLightsOnScreen, System.Runtime.InteropServices.Marshal.SizeOf(typeof(LightVolumeData)));
s_DispatchIndirectBuffer = new ComputeBuffer(LightDefinitions.s_NumFeatureVariants * 3, sizeof(uint), ComputeBufferType.IndirectArguments);
// Cluster

CoreUtils.SafeRelease(s_LightDatas);
CoreUtils.SafeRelease(s_EnvLightDatas);
CoreUtils.SafeRelease(s_shadowDatas);
CoreUtils.SafeRelease(s_DecalDatas);
if (m_ReflectionProbeCache != null)
{

return 8 * (1 << k_Log2NumClusters); // total footprint for all layers of the tile (measured in light index entries)
}
// TODO: Add proper stereo support
public void AllocResolutionDependentBuffers(int width, int height)
public void AllocResolutionDependentBuffers(int width, int height, bool stereoEnabled)
var nrStereoLayers = stereoEnabled ? 2 : 1;
var nrTiles = nrTilesX * nrTilesY;
var nrTiles = nrTilesX * nrTilesY * nrStereoLayers;
s_TileFeatureFlags = new ComputeBuffer(nrTilesX * nrTilesY, sizeof(uint));
s_TileFeatureFlags = new ComputeBuffer(nrTiles, sizeof(uint));
var nrClusterTiles = nrClustersX * nrClustersY;
var nrClusterTiles = nrClustersX * nrClustersY * nrStereoLayers;
s_PerVoxelOffset = new ComputeBuffer((int)LightCategory.Count * (1 << k_Log2NumClusters) * nrClusterTiles, sizeof(uint));
s_PerVoxelLightLists = new ComputeBuffer(NumLightIndicesPerClusteredTile() * nrClusterTiles, sizeof(uint));

{
var nrBigTilesX = (width + 63) / 64;
var nrBigTilesY = (height + 63) / 64;
var nrBigTiles = nrBigTilesX * nrBigTilesY;
var nrBigTiles = nrBigTilesX * nrBigTilesY * nrStereoLayers;
static Matrix4x4 WorldToCamera(Camera camera)
public static Matrix4x4 WorldToCamera(Camera camera)
{
// camera.worldToCameraMatrix is RHS and Unity's transforms are LHS
// We need to flip it to work with transforms

static Matrix4x4 WorldToViewStereo(Camera camera, Camera.StereoscopicEye eyeIndex)
{
return Matrix4x4.Scale(new Vector3(1, 1, -1)) * camera.GetStereoViewMatrix(eyeIndex);
}
// For light culling system, we need non oblique projection matrices
static Matrix4x4 CameraProjectionNonObliqueLHS(HDCamera camera)
{

}
static Matrix4x4 CameraProjectionStereoLHS(Camera camera, Camera.StereoscopicEye eyeIndex)
{
return camera.GetStereoProjectionMatrix(eyeIndex) * Matrix4x4.Scale(new Vector3(1, 1, -1));
}
public Vector3 GetLightColor(VisibleLight light)
{
return new Vector3(light.finalColor.r, light.finalColor.g, light.finalColor.b);

directionalLightData.dynamicShadowCasterOnly = 0;
}
// Fallback to the first non shadow casting directional light.
m_CurrentSunLight = m_CurrentSunLight == null ? light.light : m_CurrentSunLight;
m_lightList.directionalLights.Add(directionalLightData);

// TODO: we should be able to do this calculation only with LightData without VisibleLight light, but for now pass both
public void GetLightVolumeDataAndBound(LightCategory lightCategory, GPULightType gpuLightType, LightVolumeType lightVolumeType,
VisibleLight light, LightData lightData, Vector3 lightDimensions, Matrix4x4 worldToView)
VisibleLight light, LightData lightData, Vector3 lightDimensions, Matrix4x4 worldToView,
Camera.StereoscopicEye eyeIndex = Camera.StereoscopicEye.Left)
{
// Then Culling side
var range = lightDimensions.z;

Debug.Assert(false, "TODO: encountered an unknown GPULightType.");
}
m_lightList.bounds.Add(bound);
m_lightList.lightVolumes.Add(lightVolumeData);
if (eyeIndex == Camera.StereoscopicEye.Left)
{
m_lightList.bounds.Add(bound);
m_lightList.lightVolumes.Add(lightVolumeData);
}
else
{
m_lightList.rightEyeBounds.Add(bound);
m_lightList.rightEyeLightVolumes.Add(lightVolumeData);
}
}

envLightData.proxyPositionWS = proxyToWorld.GetColumn(3);
m_lightList.envLights.Add(envLightData);
public void GetEnvLightVolumeDataAndBound(ProbeWrapper probe, LightVolumeType lightVolumeType, Matrix4x4 worldToView)
public void GetEnvLightVolumeDataAndBound(ProbeWrapper probe, LightVolumeType lightVolumeType, Matrix4x4 worldToView, Camera.StereoscopicEye eyeIndex = Camera.StereoscopicEye.Left)
{
var bound = new SFiniteLightBound();
var lightVolumeData = new LightVolumeData();

}
}
m_lightList.bounds.Add(bound);
m_lightList.lightVolumes.Add(lightVolumeData);
if (eyeIndex == Camera.StereoscopicEye.Left)
{
m_lightList.bounds.Add(bound);
m_lightList.lightVolumes.Add(lightVolumeData);
}
else
{
m_lightList.rightEyeBounds.Add(bound);
m_lightList.rightEyeLightVolumes.Add(lightVolumeData);
}
}
public void AddBoxVolumeDataAndBound(OrientedBBox obb, LightCategory category, LightFeatureFlags featureFlags, Matrix4x4 worldToView)

m_lightList.Clear();
Vector3 camPosWS = camera.transform.position;
var stereoEnabled = m_FrameSettings.enableStereo;
// Note: Light with null intensity/Color are culled by the C++, no need to test it here
if (cullResults.visibleLights.Count != 0 || cullResults.visibleReflectionProbes.Count != 0)

AdditionalShadowData asd = vl.light.GetComponent<AdditionalShadowData>();
if (asd != null && asd.shadowDimmer > 0.0f)
{
// Discover sun light and update cascade info from Volumes
// TODO: This should be moved to GetDirectionalLightData when we merge the two loops here.
// Careful it must still be done BEFORE the call to ProcessShadowRequests
if (vl.lightType == LightType.Directional && m_CurrentSunLight == null)
{
var hdShadowSettings = VolumeManager.instance.stack.GetComponent<HDShadowSettings>();
asd.SetShadowCascades(hdShadowSettings.cascadeShadowSplitCount, hdShadowSettings.cascadeShadowSplits, hdShadowSettings.cascadeShadowBorders );
}
}
uint shadowRequestCount = (uint)m_ShadowRequests.Count;
uint shadowRequestCount = (uint)m_ShadowRequests.Count;
m_ShadowMgr.ProcessShadowRequests(m_FrameId, cullResults, camera, ShaderConfig.s_CameraRelativeRendering != 0, cullResults.visibleLights,
ref shadowRequestCount, shadowRequests, out shadowDataIndices);

// For now we will still apply the maximum of shadow here but we don't apply the sorting by priority + slot allocation yet
// 2. Go through all lights, convert them to GPU format.
// Create simultaneously data for culling (LigthVolumeData and rendering)
// Simultaneously create data for culling (LightVolumeData and SFiniteLightBound)
Vector3 camPosWS = camera.transform.position;
var rightEyeWorldToView = Matrix4x4.identity;
if (stereoEnabled)
{
worldToView = WorldToViewStereo(camera, Camera.StereoscopicEye.Left);
rightEyeWorldToView = WorldToViewStereo(camera, Camera.StereoscopicEye.Right);
}
for (int sortIndex = 0; sortIndex < sortCount; ++sortIndex)
{

// Then culling side. Must be call in this order as we pass the created Light data to the function
GetLightVolumeDataAndBound(lightCategory, gpuLightType, lightVolumeType, light, m_lightList.lights[m_lightList.lights.Count - 1], lightDimensions, worldToView);
if (stereoEnabled)
GetLightVolumeDataAndBound(lightCategory, gpuLightType, lightVolumeType, light, m_lightList.lights[m_lightList.lights.Count - 1], lightDimensions, rightEyeWorldToView, Camera.StereoscopicEye.Right);
// We make the light position camera-relative as late as possible in order
// to allow the preceding code to work with the absolute world space coordinates.

if (GetEnvLightData(cmd, camera, probeWrapper))
{
GetEnvLightVolumeDataAndBound(probeWrapper, lightVolumeType, worldToView);
if (stereoEnabled)
GetEnvLightVolumeDataAndBound(probeWrapper, lightVolumeType, rightEyeWorldToView, Camera.StereoscopicEye.Right);
// We make the light position camera-relative as late as possible in order
// to allow the preceding code to work with the absolute world space coordinates.

Debug.Assert(m_lightCount == m_lightList.bounds.Count);
Debug.Assert(m_lightCount == m_lightList.lightVolumes.Count);
int decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, k_MaxDecalsOnScreen);
if (decalDatasCount > 0)
{
for (int i = 0; i < decalDatasCount; i++)
{
m_lightList.bounds.Add(DecalSystem.m_Bounds[i]);
m_lightList.lightVolumes.Add(DecalSystem.m_LightVolumes[i]);
}
m_lightCount += decalDatasCount;
}
if (stereoEnabled)
{
// TODO: Proper decal + stereo cull management
Debug.Assert(m_lightList.rightEyeBounds.Count == m_lightCount);
Debug.Assert(m_lightList.rightEyeLightVolumes.Count == m_lightCount);
// TODO: GC considerations?
m_lightList.bounds.AddRange(m_lightList.rightEyeBounds);
m_lightList.lightVolumes.AddRange(m_lightList.rightEyeLightVolumes);
}
UpdateDataBuffers();
m_maxShadowDistance = shadowSettings.maxShadowDistance;

cmd.SetComputeBufferParam(buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, HDShaderIDs.g_LayeredSingleIdxBuffer, s_GlobalLightListAtomic);
cmd.DispatchCompute(buildPerVoxelLightListShader, s_ClearVoxelAtomicKernel, 1, 1, 1);
int decalDatasCount = Math.Min(DecalSystem.m_DecalDatasCount, k_MaxDecalsOnScreen);
cmd.SetComputeIntParam(buildPerVoxelLightListShader, HDShaderIDs._DensityVolumeIndexShift, m_lightList.lights.Count + m_lightList.envLights.Count);
cmd.SetComputeIntParam(buildPerVoxelLightListShader, HDShaderIDs._DecalIndexShift, m_lightList.lights.Count + m_lightList.envLights.Count);
cmd.SetComputeIntParam(buildPerVoxelLightListShader, HDShaderIDs._DensityVolumeIndexShift, m_lightList.lights.Count + m_lightList.envLights.Count + decalDatasCount);
cmd.SetComputeIntParam(buildPerVoxelLightListShader, HDShaderIDs.g_iNrVisibLights, m_lightCount);
cmd.SetComputeMatrixParam(buildPerVoxelLightListShader, HDShaderIDs.g_mScrProjection, projscr);
cmd.SetComputeMatrixParam(buildPerVoxelLightListShader, HDShaderIDs.g_mInvScrProjection, invProjscr);

var camera = hdCamera.camera;
cmd.BeginSample("Build Light List");
var w = camera.pixelWidth;
var h = camera.pixelHeight;
var w = (int)hdCamera.screenSize.x;
var h = (int)hdCamera.screenSize.y;
// camera to screen matrix (and it's inverse)
var proj = CameraProjectionNonObliqueLHS(hdCamera);
var projscr = temp * proj;
var invProjscr = projscr.inverse;
// camera to screen matrix (and it's inverse)
var projArr = new Matrix4x4[2];
var projscrArr = new Matrix4x4[2];
var invProjscrArr = new Matrix4x4[2];
if (m_FrameSettings.enableStereo)
{
for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
{
projArr[eyeIndex] = CameraProjectionStereoLHS(hdCamera.camera, (Camera.StereoscopicEye)eyeIndex);
projscrArr[eyeIndex] = temp * projArr[eyeIndex];
invProjscrArr[eyeIndex] = projscrArr[eyeIndex].inverse;
}
}
else
{
projArr[0] = CameraProjectionNonObliqueLHS(hdCamera);
projscrArr[0] = temp * projArr[0];
invProjscrArr[0] = projscrArr[0].inverse;
}
// generate screen-space AABBs (used for both fptl and clustered).
if (m_lightCount != 0)
{

temp.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
var projh = temp * proj;
var invProjh = projh.inverse;
var projhArr = new Matrix4x4[2];
var invProjhArr = new Matrix4x4[2];
if (m_FrameSettings.enableStereo)
{
for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
{
projhArr[eyeIndex] = temp * projArr[eyeIndex];
invProjhArr[eyeIndex] = projhArr[eyeIndex].inverse;
}
}
else
{
projhArr[0] = temp * projArr[0];
invProjhArr[0] = projhArr[0].inverse;
}
// In the stereo case, we have two sets of light bounds to iterate over (bounds are in per-eye view space)
cmd.SetComputeMatrixParam(buildScreenAABBShader, HDShaderIDs.g_mProjection, projh);
cmd.SetComputeMatrixParam(buildScreenAABBShader, HDShaderIDs.g_mInvProjection, invProjh);
cmd.SetComputeMatrixArrayParam(buildScreenAABBShader, HDShaderIDs.g_mProjectionArr, projhArr);
cmd.SetComputeMatrixArrayParam(buildScreenAABBShader, HDShaderIDs.g_mInvProjectionArr, invProjhArr);
// In stereo, we output two sets of AABB bounds
cmd.DispatchCompute(buildScreenAABBShader, s_GenAABBKernel, (m_lightCount + 7) / 8, 1, 1);
int tgY = m_FrameSettings.enableStereo ? 2 : 1;
cmd.DispatchCompute(buildScreenAABBShader, s_GenAABBKernel, (m_lightCount + 7) / 8, tgY, 1);
}
// enable coarse 2D pass on 64x64 tiles (used for both fptl and clustered).

cmd.SetComputeIntParams(buildPerBigTileLightListShader, HDShaderIDs.g_viDimensions, s_TempIntArray);
cmd.SetComputeIntParam(buildPerBigTileLightListShader, HDShaderIDs._EnvLightIndexShift, m_lightList.lights.Count);
cmd.SetComputeIntParam(buildPerBigTileLightListShader, HDShaderIDs._DecalIndexShift, m_lightList.lights.Count + m_lightList.envLights.Count);
cmd.SetComputeMatrixParam(buildPerBigTileLightListShader, HDShaderIDs.g_mScrProjection, projscr);
cmd.SetComputeMatrixParam(buildPerBigTileLightListShader, HDShaderIDs.g_mInvScrProjection, invProjscr);
cmd.SetComputeMatrixParam(buildPerBigTileLightListShader, HDShaderIDs.g_mScrProjection, projscrArr[0]);
cmd.SetComputeMatrixParam(buildPerBigTileLightListShader, HDShaderIDs.g_mInvScrProjection, invProjscrArr[0]);
cmd.SetComputeFloatParam(buildPerBigTileLightListShader, HDShaderIDs.g_fNearPlane, camera.nearClipPlane);
cmd.SetComputeFloatParam(buildPerBigTileLightListShader, HDShaderIDs.g_fFarPlane, camera.farClipPlane);
cmd.SetComputeBufferParam(buildPerBigTileLightListShader, s_GenListPerBigTileKernel, HDShaderIDs.g_vLightList, s_BigTileLightList);

cmd.SetComputeIntParam(buildPerTileLightListShader, HDShaderIDs.g_isOrthographic, isOrthographic ? 1 : 0);
cmd.SetComputeIntParams(buildPerTileLightListShader, HDShaderIDs.g_viDimensions, s_TempIntArray);
cmd.SetComputeIntParam(buildPerTileLightListShader, HDShaderIDs._EnvLightIndexShift, m_lightList.lights.Count);
cmd.SetComputeIntParam(buildPerTileLightListShader, HDShaderIDs._DecalIndexShift, m_lightList.lights.Count + m_lightList.envLights.Count);
cmd.SetComputeIntParam(buildPerTileLightListShader, HDShaderIDs.g_iNrVisibLights, m_lightCount);
cmd.SetComputeBufferParam(buildPerTileLightListShader, s_GenListPerTileKernel, HDShaderIDs.g_vBoundsBuffer, s_AABBBoundsBuffer);

cmd.SetComputeMatrixParam(buildPerTileLightListShader, HDShaderIDs.g_mScrProjection, projscr);
cmd.SetComputeMatrixParam(buildPerTileLightListShader, HDShaderIDs.g_mInvScrProjection, invProjscr);
cmd.SetComputeMatrixParam(buildPerTileLightListShader, HDShaderIDs.g_mScrProjection, projscrArr[0]);
cmd.SetComputeMatrixParam(buildPerTileLightListShader, HDShaderIDs.g_mInvScrProjection, invProjscrArr[0]);
cmd.SetComputeTextureParam(buildPerTileLightListShader, s_GenListPerTileKernel, HDShaderIDs.g_depth_tex, cameraDepthBufferRT);
cmd.SetComputeBufferParam(buildPerTileLightListShader, s_GenListPerTileKernel, HDShaderIDs.g_vLightList, s_LightList);
if (m_FrameSettings.lightLoopSettings.enableBigTilePrepass)

}
// Cluster
VoxelLightListGeneration(cmd, hdCamera, projscr, invProjscr, cameraDepthBufferRT);
VoxelLightListGeneration(cmd, hdCamera, projscrArr[0], invProjscrArr[0], cameraDepthBufferRT);
if (enableFeatureVariants)
{

PushGlobalParams(hdCamera, cmd);
}
private void UpdateDataBuffers()
void UpdateDataBuffers()
s_DecalDatas.SetData(DecalSystem.m_DecalDatas, 0, 0, Math.Min(DecalSystem.m_DecalDatasCount, k_MaxDecalsOnScreen)); // don't add more than the size of the buffer
// These two buffers have been set in Rebuild()
s_ConvexBoundsBuffer.SetData(m_lightList.bounds);

cmd.SetGlobalInt(HDShaderIDs._AreaLightCount, m_areaLightCount);
cmd.SetGlobalBuffer(HDShaderIDs._EnvLightDatas, s_EnvLightDatas);
cmd.SetGlobalInt(HDShaderIDs._EnvLightCount, m_lightList.envLights.Count);
cmd.SetGlobalBuffer(HDShaderIDs._DecalDatas, s_DecalDatas);
cmd.SetGlobalInt(HDShaderIDs._DecalCount, DecalSystem.m_DecalDatasCount);
cmd.SetGlobalBuffer(HDShaderIDs._ShadowDatas, s_shadowDatas);
cmd.SetGlobalInt(HDShaderIDs._NumTileFtplX, GetNumTileFtplX(hdCamera));

using (new ProfilingSample(cmd, "Deferred Directional Shadow", CustomSamplerId.TPDeferredDirectionalShadow.GetSampler()))
{
AdditionalShadowData asd = m_CurrentSunLight.GetComponent<AdditionalShadowData>();
ContactShadows contactShadows = VolumeManager.instance.stack.GetComponent<ContactShadows>();
bool enableContactShadows = m_FrameSettings.enableContactShadows && asd.enableContactShadows && asd.contactShadowLength > 0.0f;
bool enableContactShadows = m_FrameSettings.enableContactShadows && contactShadows.enable && contactShadows.length > 0.0f;
int kernel;
if (enableContactShadows)
kernel = m_FrameSettings.enableForwardRenderingOnly ? s_deferredDirectionalShadow_Contact_Kernel : s_deferredDirectionalShadow_Contact_Normals_Kernel;

if (enableContactShadows)
{
float contactShadowRange = Mathf.Clamp(asd.contactShadowFadeDistance, 0.0f, asd.contactShadowMaxDistance);
float contactShadowFadeEnd = asd.contactShadowMaxDistance;
float contactShadowRange = Mathf.Clamp(contactShadows.fadeDistance, 0.0f, contactShadows.maxDistance);
float contactShadowFadeEnd = contactShadows.maxDistance;
Vector4 contactShadowParams = new Vector4(asd.contactShadowLength, asd.contactShadowDistanceScaleFactor, contactShadowFadeEnd, contactShadowOneOverFadeRange);
Vector4 contactShadowParams = new Vector4(contactShadows.length, contactShadows.distanceScaleFactor, contactShadowFadeEnd, contactShadowOneOverFadeRange);
cmd.SetComputeIntParam(deferredDirectionalShadowComputeShader, HDShaderIDs._DirectionalContactShadowSampleCount, (int)asd.contactShadowSampleCount);
cmd.SetComputeIntParam(deferredDirectionalShadowComputeShader, HDShaderIDs._DirectionalContactShadowSampleCount, contactShadows.sampleCount);
}
cmd.SetComputeIntParam(deferredDirectionalShadowComputeShader, HDShaderIDs._DirectionalShadowIndex, m_CurrentSunLightShadowIndex);

5
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/LightLoop.cs.hlsl


#define LIGHTCATEGORY_PUNCTUAL (0)
#define LIGHTCATEGORY_AREA (1)
#define LIGHTCATEGORY_ENV (2)
#define LIGHTCATEGORY_DENSITY_VOLUME (3)
#define LIGHTCATEGORY_COUNT (4)
#define LIGHTCATEGORY_DECAL (3)
#define LIGHTCATEGORY_DENSITY_VOLUME (4)
#define LIGHTCATEGORY_COUNT (5)
//
// UnityEngine.Experimental.Rendering.HDPipeline.LightFeatureFlags: static fields

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/builddispatchindirect.compute


#pragma kernel BuildDispatchIndirect
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "LightLoop.cs.hlsl"

1
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/cleardispatchindirect.compute


#pragma kernel ClearDispatchIndirect
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
RWBuffer<uint> g_DispatchIndirectBuffer : register( u0 ); // Indirect arguments have to be in a _buffer_, not a structured buffer

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-bigtile.compute


#include "LightingConvexHullUtils.hlsl"
#include "SortingComputeUtils.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
#define EXACT_EDGE_TESTS
#define PERFORM_SPHERICAL_INTERSECTION_TESTS

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild-clustered.compute


#include "SortingComputeUtils.hlsl"
#endif
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
//#define EXACT_EDGE_TESTS
#define PERFORM_SPHERICAL_INTERSECTION_TESTS
#define CONV_HULL_TEST_ENABLED

float4x4 g_mScrProjection;
uint g_isOrthographic;
int _EnvLightIndexShift;
int _DecalIndexShift;
int _DensityVolumeIndexShift;
float g_fClustScale;

InterlockedAdd(g_LayeredSingleIdxBuffer[0], (uint) iSpaceAvail, start); // alloc list memory
}
// All our cull data are in the same list, but at render time envLights are separated so we need to shit the index
// All our cull data are in the same list, but at render time envLights are separated so we need to shift the index
shiftIndex[LIGHTCATEGORY_COUNT - 2] = _EnvLightIndexShift;
shiftIndex[LIGHTCATEGORY_COUNT - 3] = _EnvLightIndexShift;
shiftIndex[LIGHTCATEGORY_COUNT - 2] = _DecalIndexShift;
int categoryListCount[LIGHTCATEGORY_COUNT]; // number of direct lights, reflection probes and density volumes
int categoryListCount[LIGHTCATEGORY_COUNT]; // number of direct lights, reflection probes, decals and density volumes
ZERO_INITIALIZE_ARRAY(int, categoryListCount, LIGHTCATEGORY_COUNT);
uint offs = start;
for(int ll=0; ll<iNrCoarseLights; ll+=4)

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/lightlistbuild.compute


#include "SortingComputeUtils.hlsl"
#endif
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
#define FINE_PRUNING_ENABLED
#define PERFORM_SPHERICAL_INTERSECTION_TESTS

uniform float4x4 g_mScrProjection;
uniform uint g_isOrthographic;
uniform int _EnvLightIndexShift;
uniform int _DecalIndexShift;
uniform uint g_BaseFeatureFlags;
Texture2D g_depth_tex : register( t0 );

// to make it work correctly
int shiftIndex[CATEGORY_LIST_SIZE];
ZERO_INITIALIZE_ARRAY(int, shiftIndex, CATEGORY_LIST_SIZE);
shiftIndex[CATEGORY_LIST_SIZE - 1] = _EnvLightIndexShift;
shiftIndex[CATEGORY_LIST_SIZE - 2] = _EnvLightIndexShift;
shiftIndex[CATEGORY_LIST_SIZE - 1] = _DecalIndexShift;
for(int category=0; category<CATEGORY_LIST_SIZE; category++)
{

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/materialflags.compute


#include "../../Material/Material.hlsl" // This includes Material.hlsl
#include "../../Lighting/LightDefinition.cs.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
#define USE_MATERIAL_FEATURE_FLAGS
#define NR_THREADS 64

26
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightLoop/scrbound.compute


#include "CoreRP/ShaderLibrary/common.hlsl"
#include "LightLoop.cs.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
uniform float4x4 g_mInvProjection;
uniform float4x4 g_mProjection;
uniform float4x4 g_mInvProjectionArr[2];
uniform float4x4 g_mProjectionArr[2];
StructuredBuffer<SFiniteLightBound> g_data : register( t0 );

void ScreenBoundsAABB(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID)
{
uint groupID = u3GroupID.x;
uint eyeIndex = u3GroupID.y; // currently, can only be 0 or 1
// The g_ is preserved in order to make cross-pipeline (FPTL) updates easier
float4x4 g_mInvProjection = g_mInvProjectionArr[eyeIndex];
float4x4 g_mProjection = g_mProjectionArr[eyeIndex];
//uint vindex = groupID * NR_THREADS + threadID;
unsigned int g = groupID;

const int lgtIndex = subLigt+(int) g*8;
const int sideIndex = (int) (t%8);
SFiniteLightBound lgtDat = g_data[lgtIndex];
const int eyeAdjustedLgtIndex = lgtIndex + (eyeIndex * g_iNrVisibLights);
SFiniteLightBound lgtDat = g_data[eyeAdjustedLgtIndex];
const float3 boxX = lgtDat.boxAxisX.xyz;
const float3 boxY = lgtDat.boxAxisY.xyz;

//g_vBoundsBuffer[lgtIndex+g_iNrVisibLights] = float3(0.5*vMax.x+0.5, -0.5*vMin.y+0.5, vMax.z*VIEWPORT_SCALE_Z);
// changed for unity
g_vBoundsBuffer[lgtIndex+0] = float3(0.5*vMin.x+0.5, 0.5*vMin.y+0.5, vMin.z*VIEWPORT_SCALE_Z);
g_vBoundsBuffer[lgtIndex+(int) g_iNrVisibLights] = float3(0.5*vMax.x+0.5, 0.5*vMax.y+0.5, vMax.z*VIEWPORT_SCALE_Z);
// Each light's AABB is represented by two float3s, the min and max of the box.
// And for stereo, we have two sets of lights. Therefore, each eye has a set of mins, followed by
// a set of maxs, and each set is equal to g_iNrVisibLights.
const int eyeBaseIndex = eyeIndex * g_iNrVisibLights * 2;
const int minIndex = eyeBaseIndex + lgtIndex + 0;
const int maxIndex = eyeBaseIndex + lgtIndex + (int)g_iNrVisibLights;
g_vBoundsBuffer[minIndex] = float3(0.5*vMin.x + 0.5, 0.5*vMin.y + 0.5, vMin.z*VIEWPORT_SCALE_Z);
g_vBoundsBuffer[maxIndex] = float3(0.5*vMax.x + 0.5, 0.5*vMax.y + 0.5, vMax.z*VIEWPORT_SCALE_Z);
}
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/Volumetrics/Resources/VolumetricLighting.compute


#include "../../Lighting.hlsl" // Includes Material.hlsl
#include "../../LightEvaluation.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
//--------------------------------------------------------------------------------------------------
// Inputs & outputs
//--------------------------------------------------------------------------------------------------

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.cs


sRGBFlags = m_sRGBFlags;
}
}
// normalToWorld.m03 - total blend factor
// normalToWorld.m13 - diffuse texture index in atlas
// normalToWorld.m23 - normal texture index in atlas
// normalToWorld.m33 - mask texture index in atlas
[GenerateHLSL]
public struct DecalData
{
public Matrix4x4 worldToDecal;
public Matrix4x4 normalToWorld;
};
}

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


uint HTileMask;
};
// Generated from UnityEngine.Experimental.Rendering.HDPipeline.DecalData
// PackingRules = Exact
struct DecalData
{
float4x4 worldToDecal;
float4x4 normalToWorld;
};
//
// Accessors for UnityEngine.Experimental.Rendering.HDPipeline.DecalData
//
float4x4 GetNormalToWorld(DecalData value)
{
return value.normalToWorld;
}
//
// Debug functions
//

10
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/Decal.hlsl


CBUFFER_END
UNITY_INSTANCING_BUFFER_START(Decal)
UNITY_DEFINE_INSTANCED_PROP(float4x4, normalToWorld)
UNITY_DEFINE_INSTANCED_PROP(float4x4, _NormalToWorld)
TEXTURE2D(_DecalHTileTexture);
TEXTURE2D(_DecalHTileTexture);
uint _DecalCount;
StructuredBuffer<DecalData> _DecalDatas;
TEXTURE2D_ARRAY(_DecalAtlas);
SAMPLER(sampler_DecalAtlas);
// Must be in sync with RT declared in HDRenderPipeline.cs ::Rebuild
void EncodeIntoDBuffer( DecalSurfaceData surfaceData,

7
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalData.hlsl


surfaceData.normalWS = float4(0,0,0,0);
surfaceData.mask = float4(0,0,0,0);
surfaceData.HTileMask = 0;
float totalBlend = _DecalBlend * clamp(decalToWorld[0][3], 0.0f, 1.0f);
float totalBlend = clamp(decalToWorld[0][3], 0.0f, 1.0f);
UVMapping texCoord;
ZERO_INITIALIZE(UVMapping, texCoord);
texCoord.uv = texCoordDS.xy;
surfaceData.normalWS.xyz = mul((float3x3)decalToWorld, SAMPLE_UVMAPPING_NORMALMAP(_NormalMap, sampler_NormalMap, texCoord, 1)) * 0.5f + 0.5f;
surfaceData.normalWS.xyz = mul((float3x3)decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoordDS))) * 0.5f + 0.5f;
surfaceData.normalWS.w = totalBlend;
surfaceData.HTileMask |= DBUFFERHTILEBIT_NORMAL;
#endif

96
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Decal/DecalUtilities.hlsl


DECLARE_DBUFFER_TEXTURE(_DBufferTexture);
void AddDecalContribution(uint2 unPositionSS, inout SurfaceData surfaceData)
DecalData FetchDecal(uint start, uint i)
{
#ifdef LIGHTLOOP_TILE_PASS
int j = FetchIndex(start, i);
#else
int j = start + i;
#endif
return _DecalDatas[j];
}
void ApplyBlendNormal(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float3x3 decalToWorld, float blend)
{
float4 src;
src.xyz = mul(decalToWorld, UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D_ARRAY(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex))) * 0.5f + 0.5f;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);
matMask |= mapMask;
}
void ApplyBlendDiffuse(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float blend)
{
float4 src = SAMPLE_TEXTURE2D_ARRAY(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex);
src.w *= blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);
matMask |= mapMask;
}
void ApplyBlendMask(inout float4 dst, inout int matMask, float2 texCoords, int sliceIndex, int mapMask, float blend)
{
float4 src = SAMPLE_TEXTURE2D_ARRAY(_DecalAtlas, sampler_DecalAtlas, texCoords, sliceIndex);
src.z = src.w;
src.w = blend;
dst.xyz = src.xyz * src.w + dst.xyz * (1.0f - src.w);
dst.w = dst.w * (1.0f - src.w);
matMask |= mapMask;
}
void AddDecalContribution(PositionInputs posInput, inout SurfaceData surfaceData)
DecalSurfaceData decalSurfaceData;
int mask = 0;
FETCH_DBUFFER(DBuffer, _DBufferTexture, unPositionSS);
DecalSurfaceData decalSurfaceData;
DECODE_FROM_DBUFFER(DBuffer, decalSurfaceData);
uint mask = UnpackByte(LOAD_TEXTURE2D(_DecalHTileTexture, unPositionSS / 8).x);
FETCH_DBUFFER(DBuffer, _DBufferTexture, posInput.positionSS);
#ifdef _SURFACE_TYPE_TRANSPARENT // forward transparent using clustered decals
uint decalCount, decalStart;
DBuffer0 = float4(0.0f, 0.0f, 0.0f, 1.0f);
DBuffer1 = float4(0.5f, 0.5f, 0.5f, 1.0f);
DBuffer2 = float4(0.0f, 0.0f, 0.0f, 1.0f);
#ifdef LIGHTLOOP_TILE_PASS
GetCountAndStart(posInput, LIGHTCATEGORY_DECAL, decalStart, decalCount);
#else
decalCount = _DecalCount;
decalStart = 0;
#endif
float3 positionWS = GetAbsolutePositionWS(posInput.positionWS);
uint i = 0;
for (i = 0; i < decalCount; i++)
{
DecalData decalData = FetchDecal(decalStart, i);
float3 positionDS = mul(decalData.worldToDecal, float4(positionWS, 1.0)).xyz;
positionDS = positionDS * float3(1.0, -1.0, 1.0) + float3(0.5, 0.0f, 0.5);
float decalBlend = decalData.normalToWorld[0][3];
int diffuseIndex = decalData.normalToWorld[1][3];
int normalIndex = decalData.normalToWorld[2][3];
int maskIndex = decalData.normalToWorld[3][3];
if((all(positionDS.xyz > 0.0f) && all(1.0f - positionDS.xyz > 0.0f))) // clip to decal space
{
if(diffuseIndex != -1)
{
ApplyBlendDiffuse(DBuffer0, mask, positionDS.xz, diffuseIndex, DBUFFERHTILEBIT_DIFFUSE, decalBlend);
}
if(normalIndex != -1)
{
ApplyBlendNormal(DBuffer1, mask, positionDS.xz, normalIndex, DBUFFERHTILEBIT_NORMAL, (float3x3)decalData.normalToWorld, decalBlend);
}
if(maskIndex != -1)
{
ApplyBlendMask(DBuffer2, mask, positionDS.xz, maskIndex, DBUFFERHTILEBIT_MASK, decalBlend);
}
}
}
#else
mask = UnpackByte(LOAD_TEXTURE2D(_DecalHTileTexture, posInput.positionSS / 8));
#endif
DECODE_FROM_DBUFFER(DBuffer, decalSurfaceData);
if(mask & DBUFFERHTILEBIT_NORMAL)
{
surfaceData.normalWS.xyz = normalize(surfaceData.normalWS.xyz * decalSurfaceData.normalWS.w + decalSurfaceData.normalWS.xyz);

}
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/BuildProbabilityTables.compute


#include "CoreRP/ShaderLibrary/ImageBasedLighting.hlsl"
#include "../../ShaderVariables.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
/* --- Input --- */
#define TEXTURE_HEIGHT 256 // Equiareal texture map: cos(theta) = 1.0 - 2.0 * v

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/GGXConvolution/ComputeGgxIblSampleData.compute


#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "CoreRP/ShaderLibrary/ImageBasedLighting.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
#ifdef SHADER_API_MOBILE
#define MAX_IBL_SAMPLE_CNT 34
#else

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/LayeredLit/LayeredLitData.hlsl


#endif
#ifndef _DISABLE_DBUFFER
AddDecalContribution(posInput.positionSS, surfaceData);
AddDecalContribution(posInput, surfaceData);
#endif
#if defined(DEBUG_DISPLAY)

160
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/Lit.hlsl


// Additional bits set in 'bsdfData.materialFeatures' to save registers and simplify feature tracking.
#define MATERIAL_FEATURE_FLAGS_SSS_OUTPUT_SPLIT_LIGHTING ((MATERIAL_FEATURE_MASK_FLAGS + 1) << 0)
#define MATERIAL_FEATURE_FLAGS_SSS_TEXTURING_MODE_OFFSET FastLog2((MATERIAL_FEATURE_MASK_FLAGS + 1) << 1) // 2 bits
#define MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_THIN ((MATERIAL_FEATURE_MASK_FLAGS + 1) << 3)
#define MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_AUTO_THICKNESS ((MATERIAL_FEATURE_MASK_FLAGS + 1) << 3)
uint FeatureFlagsToTileVariant(uint featureFlags)
{

bsdfData.thickness = _ThicknessRemaps[diffusionProfile].x + _ThicknessRemaps[diffusionProfile].y * thickness;
#if SHADEROPTIONS_USE_DISNEY_SSS
bsdfData.transmittance = ComputeTransmittanceDisney( _ShapeParams[diffusionProfile].rgb,
_TransmissionTintsAndFresnel0[diffusionProfile].rgb,
bsdfData.thickness);
#else
bsdfData.transmittance = ComputeTransmittanceJimenez( _HalfRcpVariancesAndWeights[diffusionProfile][0].rgb,
_HalfRcpVariancesAndWeights[diffusionProfile][0].a,
_HalfRcpVariancesAndWeights[diffusionProfile][1].rgb,
_HalfRcpVariancesAndWeights[diffusionProfile][1].a,
_TransmissionTintsAndFresnel0[diffusionProfile].rgb,
bsdfData.thickness);
#endif
// The difference between the thin and the regular (a.k.a. auto-thickness) modes is the following:
// * in the thin object mode, we assume that the geometry is thin enough for us to safely share
// the shadowing information between the front and the back faces;
// * the thin mode uses baked (textured) thickness for all transmission calculations;
// * the thin mode uses wrapped diffuse lighting for the NdotL;
// * the auto-thickness mode uses the baked (textured) thickness to compute transmission from
// indirect lighting and non-shadow-casting lights; for shadowed lights, it calculates
// the thickness using the distance to the closest occluder sampled from the shadow map.
// If the distance is large, it may indicate that the closest occluder is not the back face of
// the current object. That's not a problem, since large thickness will result in low intensity.
bsdfData.materialFeatures |= useThinObjectMode ? MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_THIN : 0;
if (useThinObjectMode)
{
// Apply no displacement.
bsdfData.thickness = 0;
}
else
{
// Compute the thickness in world units along the normal.
float thicknessInMeters = bsdfData.thickness * METERS_PER_MILLIMETER;
float thicknessInUnits = thicknessInMeters * _WorldScales[bsdfData.diffusionProfile].y;
bsdfData.materialFeatures |= useThinObjectMode ? 0 : MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_AUTO_THICKNESS;
bsdfData.thickness = thicknessInUnits;
}
// Compute transmittance using baked thickness here. It may be overridden for direct lighting
// in the auto-thickness mode (but is always be used for indirect lighting).
#if SHADEROPTIONS_USE_DISNEY_SSS
bsdfData.transmittance = ComputeTransmittanceDisney(_ShapeParams[diffusionProfile].rgb,
_TransmissionTintsAndFresnel0[diffusionProfile].rgb,
bsdfData.thickness);
#else
bsdfData.transmittance = ComputeTransmittanceJimenez(_HalfRcpVariancesAndWeights[diffusionProfile][0].rgb,
_HalfRcpVariancesAndWeights[diffusionProfile][0].a,
_HalfRcpVariancesAndWeights[diffusionProfile][1].rgb,
_HalfRcpVariancesAndWeights[diffusionProfile][1].a,
_TransmissionTintsAndFresnel0[diffusionProfile].rgb,
bsdfData.thickness);
#endif
}
// Assume bsdfData.normalWS is init

// - we integrate the diffuse reflectance profile w.r.t. the radius (while also accounting
// for the thickness) to compute the transmittance;
// - we multiply the transmitted radiance by the transmittance.
float3 EvaluateTransmission(BSDFData bsdfData, float NdotL, float NdotV, float attenuation)
float3 EvaluateTransmission(BSDFData bsdfData, float3 transmittance, float NdotL, float NdotV, float attenuation)
bool useThinObjectMode = HasFeatureFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_THIN);
float backNdotL = useThinObjectMode ? wrappedNdotL : negatedNdotL;
bool autoThicknessMode = HasFeatureFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_AUTO_THICKNESS);
float backNdotL = autoThicknessMode ? negatedNdotL : wrappedNdotL;
// Apply BSDF-specific diffuse transmission to attenuation. See also: [SSS-NOTE-TRSM]
// We don't multiply by 'bsdfData.diffuseColor' here. It's done only once in PostEvaluateBSDF().

float intensity = max(0, attenuation * backNdotL); // Warning: attenuation can be greater than 1 due to the inverse square attenuation (when position is close to light)
return intensity * bsdfData.transmittance;
return intensity * transmittance;
}
//-----------------------------------------------------------------------------

float3 L = -lightData.forward; // Lights point backward in Unity
float NdotL = dot(N, L); // Note: Ideally this N here should be vertex normal - use for transmisison
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
float3 transmittance = bsdfData.transmittance;
bool autoThicknessMode = HasFeatureFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_AUTO_THICKNESS);
UNITY_BRANCH
if (autoThicknessMode && NdotL < 0 && lightData.shadowIndex >= 0)
// Compute displacement for fake thickObject transmission
posInput.positionWS += ComputeThicknessDisplacement(bsdfData, L, NdotL);
// TODO: perform bilinear filtering of the shadow map.
// Recompute transmittance using the thickness value computed from the shadow map.
#if 0
// Does not work, I get a compiler crash...
float3 occluderPosWS = EvalShadow_GetClosestSample_Cascade(lightLoopContext.shadowContext, posInput.positionWS, bsdfData.normalWS, lightData.shadowIndex, float4(L, 0));
#else
#define SHADOW_DISPATCH_DIR_TEX 3 // Manually keep it in sync with Shadow.hlsl...
float3 occluderPosWS = EvalShadow_GetClosestSample_Cascade(lightLoopContext.shadowContext, lightLoopContext.shadowContext.tex2DArray[SHADOW_DISPATCH_DIR_TEX], posInput.positionWS, bsdfData.normalWS, lightData.shadowIndex, float4(L, 0));
#endif
float thicknessInUnits = distance(posInput.positionWS, occluderPosWS);
float thicknessInMeters = thicknessInUnits * _WorldScales[bsdfData.diffusionProfile].x;
float thicknessInMillimeters = thicknessInMeters * MILLIMETERS_PER_METER;
// TODO: optimize.
#if SHADEROPTIONS_USE_DISNEY_SSS
transmittance = ComputeTransmittanceDisney(_ShapeParams[bsdfData.diffusionProfile].rgb,
_TransmissionTintsAndFresnel0[bsdfData.diffusionProfile].rgb,
thicknessInMillimeters);
#else
transmittance = ComputeTransmittanceJimenez(_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][0].rgb,
_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][0].a,
_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][1].rgb,
_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][1].a,
_TransmissionTintsAndFresnel0[bsdfData.diffusionProfile].rgb,
thicknessInMillimeters);
#endif
// Make sure we do not sample the shadow map twice.
lightData.shadowIndex = -1;
// Note: we do not modify the distance to the light, or the light angle for the back face.
// This is a performance-saving optimization which makes sense as long as the thickness is small.
}
float3 color;

lighting.specular *= intensity * lightData.specularScale;
}
UNITY_BRANCH if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
// TODO: move this before BSDF() to save VGPRs.
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
lighting.diffuse += EvaluateTransmission(bsdfData, NdotL, ClampNdotV(preLightData.NdotV), attenuation * lightData.diffuseScale);
lighting.diffuse += EvaluateTransmission(bsdfData, transmittance, NdotL, ClampNdotV(preLightData.NdotV), attenuation * lightData.diffuseScale);
}
// Save ALU by applying light and cookie colors only once.

float3 N = bsdfData.normalWS;
float NdotL = dot(N, L);
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
float3 transmittance = bsdfData.transmittance;
bool autoThicknessMode = HasFeatureFlag(bsdfData.materialFeatures, MATERIAL_FEATURE_FLAGS_TRANSMISSION_MODE_AUTO_THICKNESS);
UNITY_BRANCH
if (autoThicknessMode && NdotL < 0 && lightData.shadowIndex >= 0)
// Compute displacement for fake thickObject transmission
// Warning: distances computed above are NOT modified!
// This is not correct, of course, but is done for performance reasons.
posInput.positionWS += ComputeThicknessDisplacement(bsdfData, L, NdotL);
// TODO: perform bilinear filtering of the shadow map.
// Recompute transmittance using the thickness value computed from the shadow map.
#if 0
// Does not work, I get a compiler crash...
float3 occluderPosWS = EvalShadow_GetClosestSample_Punctual(lightLoopContext.shadowContext, posInput.positionWS, lightData.shadowIndex, L);
#else
#define SHADOW_DISPATCH_PUNC_TEX 3 // Manually keep it in sync with Shadow.hlsl...
float3 occluderPosWS = EvalShadow_GetClosestSample_Punctual(lightLoopContext.shadowContext, lightLoopContext.shadowContext.tex2DArray[SHADOW_DISPATCH_PUNC_TEX], posInput.positionWS, lightData.shadowIndex, L);
#endif
float thicknessInUnits = distance(posInput.positionWS, occluderPosWS);
float thicknessInMeters = thicknessInUnits * _WorldScales[bsdfData.diffusionProfile].x;
float thicknessInMillimeters = thicknessInMeters * MILLIMETERS_PER_METER;
// TODO: optimize.
#if SHADEROPTIONS_USE_DISNEY_SSS
transmittance = ComputeTransmittanceDisney(_ShapeParams[bsdfData.diffusionProfile].rgb,
_TransmissionTintsAndFresnel0[bsdfData.diffusionProfile].rgb,
thicknessInMillimeters);
#else
transmittance = ComputeTransmittanceJimenez(_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][0].rgb,
_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][0].a,
_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][1].rgb,
_HalfRcpVariancesAndWeights[bsdfData.diffusionProfile][1].a,
_TransmissionTintsAndFresnel0[bsdfData.diffusionProfile].rgb,
thicknessInMillimeters);
#endif
// Make sure we do not sample the shadow map twice.
lightData.shadowIndex = -1;
// Note: we do not modify the distance to the light, or the light angle for the back face.
// This is a performance-saving optimization which makes sense as long as the thickness is small.
}
float3 color;

lighting.specular *= intensity * lightData.specularScale;
}
UNITY_BRANCH if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
// TODO: move this before BSDF() to save VGPRs.
if (HasFeatureFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_LIT_TRANSMISSION))
lighting.diffuse += EvaluateTransmission(bsdfData, NdotL, ClampNdotV(preLightData.NdotV), attenuation * lightData.diffuseScale);
lighting.diffuse += EvaluateTransmission(bsdfData, transmittance, NdotL, ClampNdotV(preLightData.NdotV), attenuation * lightData.diffuseScale);
}
// Save ALU by applying light and cookie colors only once.

// Save ALU by applying 'lightData.color' only once.
lighting.diffuse *= lightData.color;
lighting.specular *= lightData.color;
#endif // LIT_DISPLAY_REFERENCE_AREA
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)

lighting.diffuse *= PI * lightData.diffuseScale;
}
#endif
#endif // LIT_DISPLAY_REFERENCE_AREA
return lighting;
}

// Save ALU by applying 'lightData.color' only once.
lighting.diffuse *= lightData.color;
lighting.specular *= lightData.color;
#endif // LIT_DISPLAY_REFERENCE_AREA
#ifdef DEBUG_DISPLAY
if (_DebugLightingMode == DEBUGLIGHTINGMODE_LUX_METER)

lighting.diffuse *= PI * lightData.diffuseScale;
}
#endif
#endif // LIT_DISPLAY_REFERENCE_AREA
return lighting;
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/Lit/LitData.hlsl


surfaceData.tangentWS = Orthonormalize(surfaceData.tangentWS, surfaceData.normalWS);
#ifndef _DISABLE_DBUFFER
AddDecalContribution(posInput.positionSS, surfaceData);
AddDecalContribution(posInput, surfaceData);
#endif
#if defined(DEBUG_DISPLAY)

20
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Material/SubsurfaceScattering/SubsurfaceScattering.compute


#include "../../Lighting/LightDefinition.cs.hlsl"
#include "SubsurfaceScattering.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
//--------------------------------------------------------------------------------------------------
// Inputs & outputs
//--------------------------------------------------------------------------------------------------

float3 DisneyProfilePolar(float r, float3 S)
{
#if 0
float3 expOneThird = exp(((-1.0 / 3.0) * r) * S);
float3 expOneThird = exp((-1.0 / 3.0) * r * S);
float3 p = (k * r) * S;
float3 p = (k * S) * r;
float3 expOneThird = exp2(p);
#endif
return expOneThird + expOneThird * expOneThird * expOneThird;

#if SSS_USE_TANGENT_PLANE
// Both 'xy2' and 'z' require conversion to millimeters.
float r = sqrt(xy2 + z * z) * mmPerUnit;
float p = sqrt(xy2) * mmPerUnit;
float p = sqrt(xy2);
#endif
float area = rcpPdf;
#if 0
// Boost the area associated with the sample by the ratio between the sample-center distance
// and its orthogonal projection onto the integration plane (disk).
area *= r / p;
return saturate(DisneyProfilePolar(r, S) * rcpPdf);
return saturate(DisneyProfilePolar(r, S) * area);
return DisneyProfilePolar(r, S) * rcpPdf;
return DisneyProfilePolar(r, S) * area;
#endif
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/ApplyDistorsion.compute


#include "CoreRP/ShaderLibrary/Common.hlsl"
#include "../Material/Builtin/BuiltinData.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
TEXTURE2D(_DistortionTexture);
TEXTURE2D(_GaussianPyramidColorTexture);
RW_TEXTURE2D(float4, _CameraColorTexture);

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/ColorPyramid.compute


#include "CoreRP/ShaderLibrary/Common.hlsl"
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
Texture2D<float4> _Source;
RWTexture2D<float4> _Result;

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/DepthPyramid.compute


#pragma kernel KMain_8 KERNEL_SIZE=8 KERNEL_NAME=KMain_8
#pragma kernel KMain_1 KERNEL_SIZE=1 KERNEL_NAME=KMain_1
#pragma only_renderers d3d11 ps4 xboxone vulkan metal
Texture2D<float> _Source;
RWTexture2D<float> _Result;

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/HDRenderPipelineResources.asset


debugColorPickerShader: {fileID: 4800000, guid: 8137b807709e178498f22ed710864bb0,
type: 3}
deferredShader: {fileID: 4800000, guid: 00dd221e34a6ab349a1196b0f2fab693, type: 3}
gaussianPyramidCS: {fileID: 7200000, guid: 4e3267a1135742441a14298d8dcac04a, type: 3}
colorPyramidCS: {fileID: 7200000, guid: 4e3267a1135742441a14298d8dcac04a, type: 3}
depthPyramidCS: {fileID: 7200000, guid: 64a553bb564274041906f78ffba955e4, type: 3}
copyChannelCS: {fileID: 7200000, guid: a4d45eda75e8e474dbe24a31f741f3b4, type: 3}
applyDistortionCS: {fileID: 7200000, guid: 2fa6c0e3fe6dc3145a4156f21913fe5c, type: 3}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/RenderPipelineResources/RenderPipelineResources.cs


// Lighting resources
public Shader deferredShader;
public ComputeShader gaussianPyramidCS;
public ComputeShader colorPyramidCS;
public ComputeShader depthPyramidCS;
public ComputeShader copyChannelCS;
public ComputeShader applyDistortionCS;

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderPass/ShaderPassDBuffer.hlsl


clip(1.0 - positionDS); // Clip value above one
DecalSurfaceData surfaceData;
float4x4 decalToWorld = UNITY_ACCESS_INSTANCED_PROP(matrix, normalToWorld);
float4x4 decalToWorld = UNITY_ACCESS_INSTANCED_PROP(matrix, _NormalToWorld);
GetSurfaceData(positionDS.xz, decalToWorld, surfaceData);
// have to do explicit test since compiler behavior is not defined for RW resources and discard instructions

4
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariables.hlsl


#if defined(USING_STEREO_MATRICES)
CBUFFER_START(UnityPerPassStereo)
float4x4 _ViewMatrixStereo[2];
// Proj not needed...yet?
float4x4 _ViewProjMatrixStereo[2];
float4x4 _InvViewMatrixStereo[2];
float4x4 _InvProjMatrixStereo[2];
float4x4 _InvViewProjMatrixStereo[2];
CBUFFER_END

6
ScriptableRenderPipeline/HDRenderPipeline/HDRP/ShaderVariablesMatrixDefsHDCamera.hlsl


#define UNITY_MATRIX_M unity_ObjectToWorld
#define UNITY_MATRIX_I_M unity_WorldToObject
#define UNITY_MATRIX_V unity_StereoMatrixV[unity_StereoEyeIndex]
#define UNITY_MATRIX_I_V unity_StereoMatrixInvV[unity_StereoEyeIndex]
#define UNITY_MATRIX_V _ViewMatrixStereo[unity_StereoEyeIndex]
#define UNITY_MATRIX_I_V _InvViewMatrixStereo[unity_StereoEyeIndex]
#define UNITY_MATRIX_VP unity_StereoMatrixVP[unity_StereoEyeIndex]
#define UNITY_MATRIX_VP _ViewProjMatrixStereo[unity_StereoEyeIndex]
#define UNITY_MATRIX_I_VP _InvViewProjMatrixStereo[unity_StereoEyeIndex]
#else

46
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Shadows/HDShadowSettings.cs


[Serializable]
public class HDShadowSettings : VolumeComponent
{
public NoInterpMinFloatParameter maxShadowDistance = new NoInterpMinFloatParameter(500.0f, 0.0f);
float[] m_CascadeShadowSplits = new float[3];
float[] m_CascadeShadowBorders = new float[4];
public float[] cascadeShadowSplits
{
get
{
m_CascadeShadowSplits[0] = cascadeShadowSplit0;
m_CascadeShadowSplits[1] = cascadeShadowSplit1;
m_CascadeShadowSplits[2] = cascadeShadowSplit2;
return m_CascadeShadowSplits;
}
}
public float[] cascadeShadowBorders
{
get
{
m_CascadeShadowBorders[0] = cascadeShadowBorder0;
m_CascadeShadowBorders[1] = cascadeShadowBorder1;
m_CascadeShadowBorders[2] = cascadeShadowBorder2;
m_CascadeShadowBorders[3] = cascadeShadowBorder3;
return m_CascadeShadowBorders;
}
}
[Tooltip("Maximum shadow distance for all light types.")]
public NoInterpMinFloatParameter maxShadowDistance = new NoInterpMinFloatParameter(500.0f, 0.0f);
[Tooltip("Number of splits for cascaded shadow maps.")]
public NoInterpClampedIntParameter cascadeShadowSplitCount = new NoInterpClampedIntParameter(4, 1, 4);
[Tooltip("Ratio of the first split against max shadow distance.")]
public NoInterpClampedFloatParameter cascadeShadowSplit0 = new NoInterpClampedFloatParameter(0.05f, 0.0f, 1.0f);
[Tooltip("Ratio of the second split against max shadow distance.")]
public NoInterpClampedFloatParameter cascadeShadowSplit1 = new NoInterpClampedFloatParameter(0.15f, 0.0f, 1.0f);
[Tooltip("Ratio of the third split against max shadow distance.")]
public NoInterpClampedFloatParameter cascadeShadowSplit2 = new NoInterpClampedFloatParameter(0.3f, 0.0f, 1.0f);
[Tooltip("Border size between first and second split.")]
public NoInterpMinFloatParameter cascadeShadowBorder0 = new NoInterpMinFloatParameter(0.0f, 0.0f);
[Tooltip("Border size between second and third split.")]
public NoInterpMinFloatParameter cascadeShadowBorder1 = new NoInterpMinFloatParameter(0.0f, 0.0f);
[Tooltip("Border size between third and last split.")]
public NoInterpMinFloatParameter cascadeShadowBorder2 = new NoInterpMinFloatParameter(0.0f, 0.0f);
[Tooltip("Border size at the end of last split.")]
public NoInterpMinFloatParameter cascadeShadowBorder3 = new NoInterpMinFloatParameter(0.0f, 0.0f);
}
}

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/HDRISky/HDRISkyRenderer.cs


public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap)
{
m_SkyHDRIMaterial.SetTexture(HDShaderIDs._Cubemap, m_HdriSkyParams.skyHDRI);
m_SkyHDRIMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_HdriSkyParams.exposure, m_HdriSkyParams.multiplier, m_HdriSkyParams.rotation, 0.0f));
m_SkyHDRIMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_HdriSkyParams.exposure, m_HdriSkyParams.multiplier, -m_HdriSkyParams.rotation, 0.0f)); // -rotation to match Legacy...
// This matrix needs to be updated at the draw call frequency.
m_PropertyBlock.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);

2
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/ProceduralSky/ProceduralSkyRenderer.cs


sunDirection = -builtinParams.sunLight.transform.forward;
}
m_SkyProceduralMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_ProceduralSkyParams.exposure, m_ProceduralSkyParams.multiplier, m_ProceduralSkyParams.rotation, 0.0f));
m_SkyProceduralMaterial.SetVector(HDShaderIDs._SkyParam, new Vector4(m_ProceduralSkyParams.exposure, m_ProceduralSkyParams.multiplier, 0.0f, 0.0f));
m_SkyProceduralMaterial.SetFloat(_SunSizeParam, m_ProceduralSkyParams.sunSize);
m_SkyProceduralMaterial.SetFloat(_SunSizeConvergenceParam, m_ProceduralSkyParams.sunSizeConvergence);
m_SkyProceduralMaterial.SetFloat(_AtmoshpereThicknessParam, m_ProceduralSkyParams.atmosphereThickness);

21
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Sky/SkyManager.cs


var visualEnv = stack.GetComponent<VisualEnvironment>();
int skyID = visualEnv.skyType;
Type skyType;
if(m_SkyTypesDict.TryGetValue(skyID, out skyType))
if (skyTypesDict.TryGetValue(skyID, out skyType))
{
return (SkySettings)stack.GetComponent(skyType);
}

static void UpdateSkyTypes()
{
if(m_SkyTypesDict == null)
if (m_SkyTypesDict == null)
foreach(Type skyType in skyTypes)
foreach (Type skyType in skyTypes)
if(uniqueIDs.Length == 0)
if (uniqueIDs.Length == 0)
{
Debug.LogWarningFormat("Missing attribute SkyUniqueID on class {0}. Class won't be registered as an available sky.", skyType);
}

if(uniqueID == 0)
if (uniqueID == 0)
{
Debug.LogWarningFormat("0 is a reserved SkyUniqueID and is used in class {0}. Class won't be registered as an available sky.", skyType);
continue;

if(m_SkyTypesDict.TryGetValue(uniqueID, out value))
if (m_SkyTypesDict.TryGetValue(uniqueID, out value))
{
Debug.LogWarningFormat("SkyUniqueID {0} used in class {1} is already used in class {2}. Class won't be registered as an available sky.", uniqueID, skyType, value);
continue;

}
}
void UpdateCurrentSkySettings(HDCamera camera)
public void UpdateCurrentSkySettings(HDCamera camera)
{
m_VisualSky.skySettings = GetSkySetting(VolumeManager.instance.stack);

m_NeedUpdateRealtimeEnv = false;
}
UpdateSkyTypes();
UpdateCurrentSkySettings(camera);
// For the baking sky, we don't want to take the sun into account because we usually won't include it (this would cause double highlight in the reflection for example).
// So we pass null so that's it doesn't affect the hash and the rendering.
m_NeedUpdateBakingSky = m_BakingSkyRenderingContext.UpdateEnvironment(m_BakingSky, camera, null, m_UpdateRequired, cmd);

result.Apply();
UnityEngine.Graphics.SetRenderTarget(null);
Object.DestroyImmediate(temp);
Object.DestroyImmediate(tempRT);
CoreUtils.Destroy(temp);
CoreUtils.Destroy(tempRT);
return result;
}

6
ScriptableRenderPipeline/HDRenderPipeline/package.json


{
"name": "com.unity.render-pipelines.high-definition",
"description": "HD Render Pipeline for Unity.",
"version": "0.1.32",
"version": "0.1.33",
"com.unity.postprocessing": "0.1.8",
"com.unity.render-pipelines.core": "0.1.32"
"com.unity.postprocessing": "0.2.0",
"com.unity.render-pipelines.core": "0.1.33"
}
}

3
ScriptableRenderPipeline/LightweightPipeline/LWRP/Editor/com.unity.render-pipelines.lightweight.Editor.asmdef


"com.unity.render-pipelines.core.Editor",
"com.unity.render-pipelines.lightweight.Runtime",
"com.unity.postprocessing.Runtime",
"com.unity.postprocessing.Editor"
"com.unity.postprocessing.Editor",
"Unity.ShaderGraph.Editor"
],
"optionalUnityReferences": [],
"includePlatforms": [

24
ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipeline.cs


public override void Render(ScriptableRenderContext context, Camera[] cameras)
{
base.Render(context, cameras);
RenderPipeline.BeginFrameRendering(cameras);
GraphicsSettings.lightsUseLinearIntensity = true;
SetupPerFrameShaderConstants();

foreach (Camera camera in cameras)
{
RenderPipeline.BeginCameraRendering(camera);
var cmd = CommandBufferPool.Get("");
cmd.BeginSample("LightweightPipeline.Render");
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
ScriptableCullingParameters cullingParameters;
if (!CullResults.GetCullingParameters(m_CurrCamera, stereoEnabled, out cullingParameters))

ForwardPass(visibleLights, frameRenderingConfiguration, ref context, ref lightData, stereoEnabled);
var cmd = CommandBufferPool.Get("After Camera Render");
cmd.name = "After Camera Render";
#if UNITY_EDITOR
if (sceneViewCamera)
CopyTexture(cmd, CameraRenderTargetID.depth, BuiltinRenderTextureType.CameraTarget, m_CopyDepthMaterial, true);

cmd.ReleaseTemporaryRT(CameraRenderTargetID.depth);
cmd.ReleaseTemporaryRT(CameraRenderTargetID.color);
cmd.ReleaseTemporaryRT(CameraRenderTargetID.copyColor);
cmd.EndSample("LightweightPipeline.Render");
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);

// SdotL * invAngleRange + (-cosOuterAngle * invAngleRange)
// If we precompute the terms in a MAD instruction
float cosOuterAngle = Mathf.Cos(Mathf.Deg2Rad * lightData.spotAngle * 0.5f);
float cosInneAngle = Mathf.Cos(LightmapperUtils.ExtractInnerCone(lightData.light) * 0.5f);
float smoothAngleRange = Mathf.Max(0.001f, cosInneAngle - cosOuterAngle);
// We neeed to do a null check for particle lights
// This should be changed in the future
// Particle lights will use an inline function
float cosInnerAngle;
if (lightData.light != null)
cosInnerAngle = Mathf.Cos(LightmapperUtils.ExtractInnerCone(lightData.light) * 0.5f);
else
cosInnerAngle = Mathf.Cos((2.0f * Mathf.Atan(Mathf.Tan(lightData.spotAngle * 0.5f * Mathf.Deg2Rad) * (64.0f - 18.0f) / 64.0f)) * 0.5f);
float smoothAngleRange = Mathf.Max(0.001f, cosInnerAngle - cosOuterAngle);
float invAngleRange = 1.0f / smoothAngleRange;
float add = -cosOuterAngle * invAngleRange;
lightSpotAttenuation = new Vector4(invAngleRange, add, 0.0f);

9
ScriptableRenderPipeline/LightweightPipeline/LWRP/LightweightPipelineUtils.cs


{
public bool Equals(VisibleLight x, VisibleLight y)
{
if (x.light == null && y.light == null)
return true;
if (x.light == null || y.light == null)
return false;
if (obj.light == null) // Particle light weirdness
return obj.GetHashCode();
return obj.light.GetInstanceID();
}
}

21
ScriptableRenderPipeline/LightweightPipeline/LWRP/Materials/Lightweight-DefaultParticle.mat


m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lightweight-DefaultParticle
m_Shader: {fileID: 4800000, guid: b7839dad95683814aa64166edc107ae2, type: 3}
m_ShaderKeywords:
m_Shader: {fileID: 4800000, guid: 0406db5a14f94604a8c57ccfbc9f3b46, type: 3}
m_ShaderKeywords: _ALPHABLEND_ON
m_CustomRenderQueue: -1
stringTagMap: {}
m_CustomRenderQueue: 3000
stringTagMap:
RenderType: Transparent
disabledShaderPasses:
- ALWAYS
m_SavedProperties:

- _CameraFadingEnabled: 0
- _CameraFarFadeDistance: 2
- _CameraNearFadeDistance: 1
- _ColorMode: 0
- _Cull: 2
- _Cutoff: 0.5
- _DetailNormalMapScale: 1

- _DistortionStrengthScaled: 0
- _DstBlend: 0
- _DstBlend: 10
- _EmissionEnabled: 0
- _FlipbookMode: 0
- _GlossMapScale: 1

- _LightingEnabled: 1
- _LightingEnabled: 0
- _Mode: 0
- _Mode: 2
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0

- _SpecularHighlights: 1
- _SrcBlend: 1
- _SrcBlend: 5
- _ZWrite: 1
- _ZWrite: 0
- _ColorAddSubDiff: {r: 0, g: 0, b: 0, a: 0}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SoftParticleFadeParams: {r: 0, g: 0, b: 0, a: 0}

10
ScriptableRenderPipeline/LightweightPipeline/LWRP/Shaders/LightweightStandardUnlit.shader


#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON
#pragma multi_compile_instancing
// -------------------------------------
// Unity defined keywords
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile _ LIGHTMAP_ON
// Lighting include is needed because of GI
#include "LWRP/ShaderLibrary/Lighting.hlsl"
#include "LWRP/ShaderLibrary/InputSurface.hlsl"

#if _SAMPLE_GI
OUTPUT_NORMAL(v, o);
half3 normalWS = o.normal;
OUTPUT_SH(normalWS, o.lightmapOrVertexSH);
OUTPUT_SH(o.normal, o.lightmapOrVertexSH);
#endif
return o;
}

#else
half3 normalWS = normalize(IN.normal);
#endif
color += SampleGI(IN.lightmapOrVertexSH, normalWS);
color *= SampleGI(IN.lightmapOrVertexSH, normalWS);
#endif
ApplyFog(color, IN.uv0AndFogCoord.z);

6
ScriptableRenderPipeline/LightweightPipeline/package.json


{
"name": "com.unity.render-pipelines.lightweight",
"description": "Lightweight Render Pipeline for Unity.",
"version": "0.1.32",
"version": "0.1.33",
"com.unity.postprocessing": "0.1.8",
"com.unity.render-pipelines.core": "0.1.32"
"com.unity.postprocessing": "0.2.0",
"com.unity.render-pipelines.core": "0.1.33"
}
}

5
ScriptableRenderPipeline/LightweightPipeline/sub-package.json


"description": "Lightweight Render Pipeline for Unity.",
"subDependencies": [
"com.unity.render-pipelines.core"
]
],
"dependencies": {
"com.unity.shadergraph": "0.1.19"
}
}

4
ScriptableRenderPipeline/master-package.json


{
"version": "0.1.32",
"version": "0.1.33",
"com.unity.postprocessing": "0.1.8"
"com.unity.postprocessing": "0.2.0"
},
"subPackages": [
"Core",

2
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/1xxx_Materials/1201_Lit_Features/Lit_NormalMap_ObjectSpace.mat


m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _NormalMap:
m_Texture: {fileID: 2800000, guid: 72c21bad8ebd4a043882b302f9837ae3, type: 3}
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _NormalMapOS:

76
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/2xxx_Lighting/2004_AnimatedCookie.unity


shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
viewBiasMin: 0.5
viewBiasMax: 10
viewBiasScale: 1
normalBiasMin: 0.2
normalBiasMax: 4
normalBiasScale: 1
sampleBiasScale: 1
edgeLeakFixup: 1
edgeToleranceNormal: 1
edgeTolerance: 1
- 0.2
- 0.15
- 0.2
- 0.2
- 0.2
- 0.2
- 0
- 0
- 0
- 0
shadowAlgorithm: 0
shadowVariant: 3
shadowPrecision: 0

m_Name:
m_EditorClassIdentifier:
m_Version: 1
directionalIntensity: 3.1415927
punctualIntensity: 600
areaIntensity: 200
m_InnerSpotPercent: 0
lightDimmer: 1
fadeDistance: 10000

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
viewBiasMin: 0.5
viewBiasMax: 10
viewBiasScale: 1
normalBiasMin: 0.2
normalBiasMax: 4
normalBiasScale: 1
sampleBiasScale: 1
edgeLeakFixup: 1
edgeToleranceNormal: 1
edgeTolerance: 1
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

m_Name:
m_EditorClassIdentifier:
m_Version: 1
directionalIntensity: 3.1415927
punctualIntensity: 600
areaIntensity: 200
m_InnerSpotPercent: 0
lightDimmer: 1
fadeDistance: 10000

shadowResolution: 512
shadowDimmer: 1
shadowFadeDistance: 10000
enableContactShadows: 0
contactShadowLength: 0
contactShadowDistanceScaleFactor: 0.5
contactShadowMaxDistance: 50
contactShadowFadeDistance: 5
contactShadowSampleCount: 8
viewBiasMin: 0.5
viewBiasMax: 10
viewBiasScale: 1
normalBiasMin: 0.2
normalBiasMax: 4
normalBiasScale: 1
sampleBiasScale: 1
edgeLeakFixup: 1
edgeToleranceNormal: 1
edgeTolerance: 1
shadowCascadeCount: 4
shadowCascadeRatios:
- 0.05

m_Name:
m_EditorClassIdentifier:
m_Version: 1
directionalIntensity: 3.1415927
punctualIntensity: 700
areaIntensity: 200
m_InnerSpotPercent: 0
lightDimmer: 1
fadeDistance: 10000

serializedVersion: 8
m_Type: 2
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_Intensity: 1
m_Intensity: 55.704227
m_Range: 10
m_SpotAngle: 30
m_CookieSize: 10

m_Bias: 0.05
m_NormalBias: 0.4
m_NearPlane: 0.2
m_Cookie: {fileID: 0}
m_Cookie: {fileID: 8600000, guid: b99e10a48bae1014fb3681ddd8a61871, type: 2}
m_DrawHalo: 0
m_Flare: {fileID: 0}
m_RenderMode: 0

type: 2}
propertyPath: width
value: 853
objectReference: {fileID: 0}
- target: {fileID: 114733060649624252, guid: c07ace9ab142ca9469fa377877c2f1e7,
type: 2}
propertyPath: waitForFrames
value: 3
objectReference: {fileID: 0}
m_RemovedComponents: []
m_ParentPrefab: {fileID: 100100000, guid: c07ace9ab142ca9469fa377877c2f1e7, type: 2}

9
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat__N.png.meta


fileFormatVersion: 2
guid: 260e01b71437c7649a10c1dad5b7ca70
guid: 754c4d2de266018488c6400f53842b7b
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

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

spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
textureType: 1
textureType: 0
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0

18
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat_M_AO_D_S.png.meta


fileFormatVersion: 2
guid: e20e6361c7446a1479f49d10c5d054c3
guid: 9fb31f0c9b4bb5045985f56fac81d86e
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

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

spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1

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

18
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat_H.png.meta


fileFormatVersion: 2
guid: c3ec713a6f2b97f4ea724a902595594b
guid: 918d9a75a9ac1754db592f3548a52f7c
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

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

spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1

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

5
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/Scenes/9xxx_Other/9002_Deferred-and-Forward/ComplexMaterial_Flipped/Textures/ComplexMat_BC_A.png.meta


fileFormatVersion: 2
guid: b6df07666246e084ca55b5b8350198d5
guid: 2634cf73e49fcb441be8dd497e2c6e8e
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}

spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spritePixelsToUnits: 100
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1

999
Tests/GraphicsTests/RenderPipeline/HDRenderPipeline/CommonAssets/Materials/ComplexMaterial/Textures/ComplexMat_BC_A.png
文件差异内容过多而无法显示
查看文件

8
ScriptableRenderPipeline/Core/CoreRP/Editor/TextureCombiner.meta


fileFormatVersion: 2
guid: 87845c683f4fa7546a3910e641768da8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

217
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs


using UnityEngine;
using System.Collections.Generic;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
public class StandardsToHDLitMaterialUpgrader : MaterialUpgrader
{
static readonly string Standard = "Standard";
static readonly string Standard_Spec = "Standard (Specular setup)";
static readonly string Standard_Rough = "Standard (Roughness setup)";
public StandardsToHDLitMaterialUpgrader(string sourceShaderName, string destShaderName, MaterialFinalizer finalizer = null)
{
RenameShader(sourceShaderName, destShaderName, finalizer);
RenameTexture("_MainTex", "_BaseColorMap");
RenameColor("_Color", "_BaseColor");
RenameFloat("_Glossiness", "_Smoothness");
RenameTexture("_BumpMap", "_NormalMap");
RenameFloat("_BumpScale", "_NormalScale");
RenameTexture("_ParallaxMap", "_HeightMap");
RenameTexture("_EmissionMap", "_EmissiveColorMap");
RenameTexture("_DetailAlbedoMap", "_DetailMap");
RenameFloat("_UVSec", "_UVDetail");
SetFloat("_LinkDetailsWithBase", 0);
RenameFloat("_DetailNormalMapScale", "_DetailNormalScale");
RenameFloat("_Cutoff", "_AlphaCutoff");
RenameKeywordToFloat("_ALPHATEST_ON", "_AlphaCutoffEnable", 1f, 0f);
if (sourceShaderName == Standard)
{
SetFloat("_MaterialID", 1f);
}
if (sourceShaderName == Standard_Spec)
{
SetFloat("_MaterialID", 4f);
RenameColor("_SpecColor", "_SpecularColor");
RenameTexture("_SpecGlossMap", "_SpecularColorMap");
}
}
public override void Convert(Material srcMaterial, Material dstMaterial)
{
dstMaterial.hideFlags = HideFlags.DontUnloadUnusedAsset;
base.Convert(srcMaterial, dstMaterial);
// ---------- Mask Map ----------
// Metallic
bool hasMetallic = false;
Texture metallicMap;
if ( (srcMaterial.shader.name == Standard) || (srcMaterial.shader.name == Standard_Rough) )
{
hasMetallic = srcMaterial.GetTexture("_MetallicGlossMap") != null;
if (hasMetallic) metallicMap = TextureCombiner.GetTextureSafe(srcMaterial, "_MetallicGlossMap", Color.white);
}
else
metallicMap = Texture2D.blackTexture;
// Occlusion
bool hasOcclusion = srcMaterial.GetTexture("_OcclusionMap") != null;
Texture occlusionMap;
if (hasOcclusion) occlusionMap = TextureCombiner.GetTextureSafe(srcMaterial, "_OcclusionMap", Color.white);
// Detail Mask
bool hasDetailMask = srcMaterial.GetTexture("_DetailMask") != null;
Texture detailMaskMap;
if (hasDetailMask) detailMaskMap = TextureCombiner.GetTextureSafe(srcMaterial, "_DetailMask", Color.white);
// Smoothness
bool hasSmoothness = false;
Texture2D smoothnessMap = TextureCombiner.TextureFromColor(Color.grey);
if (srcMaterial.shader.name == Standard_Rough)
{
hasSmoothness = srcMaterial.GetTexture("_SpecGlossMap") != null;
if (hasSmoothness)
smoothnessMap = (Texture2D)TextureCombiner.GetTextureSafe(srcMaterial, "_SpecGlossMap", Color.grey);
}
else
{
string smoothnessTextureChannel = "_MainTex";
if ( srcMaterial.GetFloat("_SmoothnessTextureChannel") == 0 )
{
if (srcMaterial.shader.name == Standard) smoothnessTextureChannel = "_MetallicGlossMap";
if (srcMaterial.shader.name == Standard_Spec) smoothnessTextureChannel = "_SpecGlossMap";
}
smoothnessMap = (Texture2D) srcMaterial.GetTexture( smoothnessTextureChannel );
if (smoothnessMap != null)
{
hasSmoothness = true;
if (!TextureCombiner.TextureHasAlpha(smoothnessMap))
{
smoothnessMap = TextureCombiner.TextureFromColor(Color.white);
}
}
else
{
smoothnessMap = TextureCombiner.TextureFromColor(Color.white * srcMaterial.GetFloat("_Glossiness"));
}
}
// Build the mask map
if ( hasMetallic || hasOcclusion || hasDetailMask || hasSmoothness )
{
Texture2D maskMap;
TextureCombiner maskMapCombiner = new TextureCombiner(
TextureCombiner.GetTextureSafe(srcMaterial, "_MetallicGlossMap", Color.white), 4, // Metallic
TextureCombiner.GetTextureSafe(srcMaterial, "_OcclusionMap", Color.white), 4, // Occlusion
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailMask", Color.white), 4, // Detail Mask
smoothnessMap, (srcMaterial.shader.name == Standard_Rough)?-4:3 // Smoothness Texture
);
string maskMapPath = AssetDatabase.GetAssetPath(srcMaterial);
maskMapPath = maskMapPath.Remove(maskMapPath.Length-4) + "_MaskMap.png";
maskMap = maskMapCombiner.Combine( maskMapPath );
dstMaterial.SetTexture("_MaskMap", maskMap);
}
dstMaterial.SetFloat("_AORemapMin", 1f - srcMaterial.GetFloat("_OcclusionStrength"));
// Specular Setup Specific
if (srcMaterial.shader.name == Standard_Spec)
{
// if there is a specular map, change the specular color to white
if (srcMaterial.GetTexture("_SpecGlossMap") != null ) dstMaterial.SetColor("_SpecularColor", Color.white);
}
// ---------- Height Map ----------
bool hasHeightMap = srcMaterial.GetTexture("_ParallaxMap") != null;
if (hasHeightMap) // Enable Parallax Occlusion Mapping
{
dstMaterial.SetFloat("_DisplacementMode", 2);
dstMaterial.SetFloat("_HeightPoMAmplitude", srcMaterial.GetFloat("_Parallax") * 2f);
}
// ---------- Detail Map ----------
bool hasDetailAlbedo = srcMaterial.GetTexture("_DetailAlbedoMap") != null;
bool hasDetailNormal = srcMaterial.GetTexture("_DetailNormalMap") != null;
if ( hasDetailAlbedo || hasDetailNormal )
{
Texture2D detailMap;
TextureCombiner detailCombiner = new TextureCombiner(
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailAlbedoMap", Color.grey), 4, // Albedo (overlay)
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailNormalMap", Color.grey), 1, // Normal Y
TextureCombiner.midGrey, 1, // Smoothness
TextureCombiner.GetTextureSafe(srcMaterial, "_DetailNormalMap", Color.grey), 0 // Normal X
);
string detailMapPath = AssetDatabase.GetAssetPath(srcMaterial);
detailMapPath = detailMapPath.Remove(detailMapPath.Length-4) + "_DetailMap.png";
detailMap = detailCombiner.Combine( detailMapPath );
dstMaterial.SetTexture("_DetailMap", detailMap);
}
// Blend Mode
int previousBlendMode = srcMaterial.GetInt("_Mode");
switch (previousBlendMode)
{
case 0: // Opaque
dstMaterial.SetFloat("_SurfaceType", 0);
dstMaterial.SetFloat("_BlendMode", 0);
dstMaterial.SetFloat("_AlphaCutoffEnable", 0);
dstMaterial.SetFloat("_EnableBlendModePreserveSpecularLighting", 1);
break;
case 1: // Cutout
dstMaterial.SetFloat("_SurfaceType", 0);
dstMaterial.SetFloat("_BlendMode", 0);
dstMaterial.SetFloat("_AlphaCutoffEnable", 1);
dstMaterial.SetFloat("_EnableBlendModePreserveSpecularLighting", 1);
break;
case 2: // Fade -> Alpha + Disable preserve specular
dstMaterial.SetFloat("_SurfaceType", 1);
dstMaterial.SetFloat("_BlendMode", 0);
dstMaterial.SetFloat("_AlphaCutoffEnable", 0);
dstMaterial.SetFloat("_EnableBlendModePreserveSpecularLighting", 0);
break;
case 3: // Transparent -> Alpha
dstMaterial.SetFloat("_SurfaceType", 1);
dstMaterial.SetFloat("_BlendMode", 0);
dstMaterial.SetFloat("_AlphaCutoffEnable", 0);
dstMaterial.SetFloat("_EnableBlendModePreserveSpecularLighting", 1);
break;
}
// Emission: Convert the HDR emissive color to ldr color + intensity
Color hdrEmission = srcMaterial.GetColor("_EmissionColor");
float intensity = Mathf.Max(hdrEmission.r, Mathf.Max(hdrEmission.g, hdrEmission.b));
if (intensity > 1f)
{
hdrEmission.r /= intensity;
hdrEmission.g /= intensity;
hdrEmission.b /= intensity;
}
else
intensity = 1f;
intensity = Mathf.Pow(intensity, 2.2f); // Gamma to Linear conversion
dstMaterial.SetColor("_EmissiveColor", hdrEmission);
dstMaterial.SetFloat("_EmissiveIntensity", intensity);
HDEditorUtils.ResetMaterialKeywords(dstMaterial);
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Lit/StandardsToHDLitMaterialUpgrader.cs.meta


fileFormatVersion: 2
guid: 3892a7f1ec73e554fb1bd8be6a6d3400
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

44
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Unlit/UnlitsToHDUnlitUpgrader.cs


using UnityEngine;
using System.Collections.Generic;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
public class UnlitsToHDUnlitUpgrader : MaterialUpgrader
{
string Unlit_Color = "Unlit/Color";
string Unlit_Texture = "Unlit/Texture";
string Unlit_Transparent = "Unlit/Transparent";
string Unlit_Cutout = "Unlit/Transparent Cutout";
public UnlitsToHDUnlitUpgrader(string sourceShaderName, string destShaderName, MaterialFinalizer finalizer = null)
{
RenameShader(sourceShaderName, destShaderName, finalizer);
if (sourceShaderName == Unlit_Color)
RenameColor("_Color", "_UnlitColor");
else // all other unlit have a texture
RenameTexture("_MainTex", "_UnlitColorMap");
if (sourceShaderName == Unlit_Cutout)
{
RenameFloat("_Cutoff", "_AlphaCutoff");
SetFloat("_AlphaCutoffEnable", 1f);
}
else
SetFloat("_AlphaCutoffEnable", 0f);
SetFloat("_SurfaceType", (sourceShaderName == Unlit_Transparent)? 1f : 0f );
}
public override void Convert(Material srcMaterial, Material dstMaterial)
{
//dstMaterial.hideFlags = HideFlags.DontUnloadUnusedAsset;
base.Convert(srcMaterial, dstMaterial);
HDEditorUtils.ResetMaterialKeywords(dstMaterial);
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Material/Unlit/UnlitsToHDUnlitUpgrader.cs.meta


fileFormatVersion: 2
guid: b6a8dfccb93f0a946a7bc1521ab32f43
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

8
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Editor/Shadows.meta


fileFormatVersion: 2
guid: c5d39f83747e41446b413632dde29652
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

67
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtils.cs


using System;
using System.Collections.Generic;
using System.Linq;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
public class LightUtils
{
// Physical light unit helper
// All light unit are in lumen (Luminous power)
// Punctual light (point, spot) are convert to candela (cd = lumens / steradian)
// Area light are convert to luminance (cd/(m^2*steradian)) with the following formulation: Luminous Power / (Area * PI * steradian)
// Ref: Moving Frostbite to PBR
// Also good ref: https://www.radiance-online.org/community/workshops/2004-fribourg/presentations/Wandachowicz_paper.pdf
// convert intensity (lumen) to candela
public static float ConvertPointLightIntensity(float intensity)
{
return intensity / (4.0f * Mathf.PI);
}
// angle is the full angle, not the half angle in radiant
// convert intensity (lumen) to candela
public static float ConvertSpotLightIntensity(float intensity, float angle, bool exact)
{
return exact ? intensity / (2.0f * (1.0f - Mathf.Cos(angle / 2.0f)) * Mathf.PI) : intensity / Mathf.PI;
}
// angleA and angleB are the full opening angle, not half angle
// convert intensity (lumen) to candela
public static float ConvertFrustrumLightIntensity(float intensity, float angleA, float angleB)
{
return intensity / (4.0f * Mathf.Asin(Mathf.Sin(angleA / 2.0f) * Mathf.Sin(angleB / 2.0f)));
}
// convert intensity (lumen) to nits
public static float ConvertSphereLightIntensity(float intensity, float sphereRadius)
{
return intensity / ((4.0f * Mathf.PI * sphereRadius * sphereRadius) * Mathf.PI);
}
// convert intensity (lumen) to nits
public static float ConvertDiscLightIntensity(float intensity, float discRadius)
{
return intensity / ((discRadius * discRadius * Mathf.PI) * Mathf.PI);
}
// convert intensity (lumen) to nits
public static float ConvertRectLightIntensity(float intensity, float width, float height)
{
return intensity / ((width * height) * Mathf.PI);
}
// convert intensity (lumen) to nits
public static float calculateLineLightArea(float intensity, float lineWidth)
{
// The area of a cylinder is this:
// float lineRadius = 0.01f; // 1cm
//return intensity / (2.0f * Mathf.PI * lineRadius * lineWidth * Mathf.PI);
// But with our current line light algorithm we get an insane gap in intensity
// following formula (fully empirical) give a better match to a rect light of 1cm of width.
// It is basically point light intensity / line width.
return intensity / (4.0f * Mathf.PI * lineWidth);
}
}
}

11
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Lighting/LightUtils.cs.meta


fileFormatVersion: 2
guid: 04acc467a6eef0b45b027f43ed25662b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

16
ScriptableRenderPipeline/HDRenderPipeline/HDRP/Shadows/ContactShadows.cs


using System;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[Serializable]
public class ContactShadows : VolumeComponent
{
// Contact shadows
public BoolParameter enable = new BoolParameter(false);
public ClampedFloatParameter length = new ClampedFloatParameter(0.15f, 0.0f, 1.0f);
public ClampedFloatParameter distanceScaleFactor = new ClampedFloatParameter(0.5f, 0.0f, 1.0f);
public MinFloatParameter maxDistance = new MinFloatParameter(50.0f, 0.0f);
public MinFloatParameter fadeDistance = new MinFloatParameter(5.0f, 0.0f);
public NoInterpClampedIntParameter sampleCount = new NoInterpClampedIntParameter(8, 4, 64);
}
}

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

正在加载...
取消
保存