浏览代码

Merge remote-tracking branch 'origin/master' into scriptablerenderloop-materialgraph

/scriptablerenderloop-materialgraph
Paul Demeulenaere 8 年前
当前提交
267b0349
共有 41 个文件被更改,包括 1603 次插入968 次删除
  1. 8
      Assets/BasicRenderLoopTutorial/BasicRenderLoop.cs
  2. 243
      Assets/BasicRenderLoopTutorial/BasicRenderLoopScene.unity
  3. 106
      Assets/ScriptableRenderLoop/HDRenderLoop/Debug/Resources/DebugViewTiles.shader
  4. 32
      Assets/ScriptableRenderLoop/HDRenderLoop/Editor/HDRenderLoopInspector.cs
  5. 1
      Assets/ScriptableRenderLoop/HDRenderLoop/HDRenderLoop.asset
  6. 2
      Assets/ScriptableRenderLoop/HDRenderLoop/HDRenderLoop.asset.meta
  7. 491
      Assets/ScriptableRenderLoop/HDRenderLoop/HDRenderLoop.cs
  8. 16
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/LightDefinition.cs
  9. 52
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/LightDefinition.cs.hlsl
  10. 10
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/Lighting.hlsl
  11. 7
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/Resources/lightlistbuild-bigtile.compute
  12. 23
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/Resources/lightlistbuild-clustered.compute
  13. 46
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/Resources/lightlistbuild.compute
  14. 12
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/ShaderBase.hlsl
  15. 922
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/TilePass.cs
  16. 72
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/TilePass.cs.hlsl
  17. 176
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/TilePass.hlsl
  18. 149
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/TilePassLoop.hlsl
  19. 2
      Assets/ScriptableRenderLoop/HDRenderLoop/Material/LayeredLit/Editor/LayeredLitUI.cs
  20. 12
      Assets/ScriptableRenderLoop/HDRenderLoop/Material/LayeredLit/LayeredLit.shader
  21. 2
      Assets/ScriptableRenderLoop/HDRenderLoop/Material/Lit/Editor/BaseLitUI.cs
  22. 6
      Assets/ScriptableRenderLoop/HDRenderLoop/Material/Lit/Lit.hlsl
  23. 7
      Assets/ScriptableRenderLoop/HDRenderLoop/Material/Lit/Lit.shader
  24. 23
      Assets/ScriptableRenderLoop/HDRenderLoop/Material/Lit/LitSurfaceData.hlsl
  25. 2
      Assets/ScriptableRenderLoop/RenderPasses/ShadowRenderPass.cs
  26. 12
      Assets/ScriptableRenderLoop/common/ShaderBase.h
  27. 2
      Assets/ScriptableRenderLoop/common/TextureSettings.cs
  28. 6
      Assets/ScriptableRenderLoop/fptl/FptlLighting.cs
  29. 24
      Assets/ScriptableRenderLoop/fptl/LightingTemplate.hlsl
  30. 2
      Assets/ScriptableRenderLoop/fptl/StandardTest.shader
  31. 2
      Assets/ScriptableRenderLoop/fptl/lightlistbuild-bigtile.compute
  32. 2
      Assets/ScriptableRenderLoop/fptl/lightlistbuild.compute
  33. 26
      Assets/TestScenes/HDTest/GlobalIlluminationTest.unity
  34. 2
      Assets/BasicRenderLoopTutorial/BasicRenderLoop.asset
  35. 8
      Assets/BasicRenderLoopTutorial/BasicRenderLoop.asset.meta
  36. 34
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/LightLoop.cs
  37. 12
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/LightLoop.cs.meta
  38. 9
      Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/SinglePass.meta
  39. 8
      Assets/basicrenderloop.asset.meta
  40. 0
      /Assets/BasicRenderLoopTutorial/BasicRenderLoop.asset

8
Assets/BasicRenderLoopTutorial/BasicRenderLoop.cs


{
#if UNITY_EDITOR
[UnityEditor.MenuItem("Renderloop/CreateBasicRenderLoop")]
[UnityEditor.MenuItem("Renderloop/Create BasicRenderLoop")]
UnityEditor.AssetDatabase.CreateAsset(instance, "Assets/basicrenderloop.asset");
UnityEditor.AssetDatabase.CreateAsset(instance, "Assets/BasicRenderLoopTutorial/BasicRenderLoop.asset");
}
#endif

// Draw opaque objects using BasicPass shader pass
var settings = new DrawRendererSettings (cull, camera, shaderPassBasic);
settings.sorting.sortOptions = SortOptions.SortByMaterialThenMesh;
settings.sorting.flags = SortFlags.CommonOpaque;
settings.inputFilter.SetQueuesOpaque ();
loop.DrawRenderers (ref settings);

// Draw transparent objects using BasicPass shader pass
settings.sorting.sortOptions = SortOptions.BackToFront; // sort back to front
settings.sorting.flags = SortFlags.CommonTransparent;
settings.inputFilter.SetQueuesTransparent ();
loop.DrawRenderers (ref settings);

243
Assets/BasicRenderLoopTutorial/BasicRenderLoopScene.unity


m_ReflectionIntensity: 0.5
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.09067501, g: 0.11147752, b: 0.14205909, a: 0.5}
m_IndirectSpecularColor: {r: 0.09067552, g: 0.11147809, b: 0.14205924, a: 0.5}
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0

minRegionArea: 2
manualCellSize: 0
cellSize: 0.16666667
manualTileSize: 0
tileSize: 256
accuratePlacement: 0
m_NavMeshData: {fileID: 0}
--- !u!1 &261580742

m_Father: {fileID: 0}
m_RootOrder: 10
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1084503476
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 1084503480}
- component: {fileID: 1084503479}
- component: {fileID: 1084503478}
- component: {fileID: 1084503477}
m_Layer: 5
m_Name: Canvas
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &1084503477
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1084503476}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 1301386320, guid: f70555f144d8491a825f0804e09c671c, type: 3}
m_Name:
m_EditorClassIdentifier:
m_IgnoreReversedGraphics: 1
m_BlockingObjects: 0
m_BlockingMask:
serializedVersion: 2
m_Bits: 4294967295
--- !u!114 &1084503478
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1084503476}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 1980459831, guid: f70555f144d8491a825f0804e09c671c, type: 3}
m_Name:
m_EditorClassIdentifier:
m_UiScaleMode: 1
m_ReferencePixelsPerUnit: 100
m_ScaleFactor: 1
m_ReferenceResolution: {x: 800, y: 600}
m_ScreenMatchMode: 0
m_MatchWidthOrHeight: 0
m_PhysicalUnit: 3
m_FallbackScreenDPI: 96
m_DefaultSpriteDPI: 96
m_DynamicPixelsPerUnit: 1
--- !u!223 &1084503479
Canvas:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1084503476}
m_Enabled: 1
serializedVersion: 2
m_RenderMode: 0
m_Camera: {fileID: 0}
m_PlaneDistance: 100
m_PixelPerfect: 0
m_ReceivesEvents: 1
m_OverrideSorting: 0
m_OverridePixelPerfect: 0
m_SortingBucketNormalizedSize: 0
m_SortingLayerID: 0
m_SortingOrder: 0
m_TargetDisplay: 0
--- !u!224 &1084503480
RectTransform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1084503476}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 0, y: 0, z: 0}
m_Children:
- {fileID: 1177504218}
m_Father: {fileID: 0}
m_RootOrder: 11
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
m_AnchoredPosition: {x: 0, y: 0}
m_SizeDelta: {x: 0, y: 0}
m_Pivot: {x: 0, y: 0}
--- !u!1 &1177504217
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 1177504218}
- component: {fileID: 1177504220}
- component: {fileID: 1177504219}
m_Layer: 5
m_Name: Text
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &1177504218
RectTransform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1177504217}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 1084503480}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0, y: 0}
m_AnchorMax: {x: 0, y: 0}
m_AnchoredPosition: {x: 163, y: 47.8}
m_SizeDelta: {x: 314, y: 82}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!114 &1177504219
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1177504217}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_RaycastTarget: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
m_FontData:
m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0}
m_FontSize: 14
m_FontStyle: 0
m_BestFit: 0
m_MinSize: 10
m_MaxSize: 40
m_Alignment: 6
m_AlignByGeometry: 0
m_RichText: 1
m_HorizontalOverflow: 0
m_VerticalOverflow: 0
m_LineSpacing: 1
m_Text: Select "BasicRenderLoop" as the render pipeline in Edit -> Project Settings
-> Graphics
--- !u!222 &1177504220
CanvasRenderer:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1177504217}
--- !u!1 &1280249095
GameObject:
m_ObjectHideFlags: 0

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1677622456}
m_Enabled: 1
serializedVersion: 7
serializedVersion: 8
m_Type: 0
m_Color: {r: 0.75, g: 1, b: 0.78275865, a: 1}
m_Intensity: 1.5

m_Lightmapping: 4
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_CCT: 6570
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!4 &1677622458

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1900527473}
m_Enabled: 1
serializedVersion: 7
serializedVersion: 8
m_Type: 2
m_Color: {r: 1, g: 0.6911765, b: 0.6911765, a: 1}
m_Intensity: 3

m_Lightmapping: 4
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_CCT: 6570
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!4 &1900527475

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 2011495862}
m_Enabled: 1
serializedVersion: 7
serializedVersion: 8
m_Type: 1
m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1}
m_Intensity: 1

m_Lightmapping: 4
m_AreaSize: {x: 1, y: 1}
m_BounceIntensity: 1
m_CCT: 6570
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!4 &2011495864

m_Father: {fileID: 0}
m_RootOrder: 7
m_LocalEulerAnglesHint: {x: -6.8960004, y: -33.794003, z: -20.829}
--- !u!1 &2054727025
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
serializedVersion: 5
m_Component:
- component: {fileID: 2054727028}
- component: {fileID: 2054727027}
- component: {fileID: 2054727026}
m_Layer: 0
m_Name: EventSystem
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!114 &2054727026
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 2054727025}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 1077351063, guid: f70555f144d8491a825f0804e09c671c, type: 3}
m_Name:
m_EditorClassIdentifier:
m_HorizontalAxis: Horizontal
m_VerticalAxis: Vertical
m_SubmitButton: Submit
m_CancelButton: Cancel
m_InputActionsPerSecond: 10
m_RepeatDelay: 0.5
m_ForceModuleActive: 0
--- !u!114 &2054727027
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 2054727025}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: -619905303, guid: f70555f144d8491a825f0804e09c671c, type: 3}
m_Name:
m_EditorClassIdentifier:
m_FirstSelected: {fileID: 0}
m_sendNavigationEvents: 1
m_DragThreshold: 5
--- !u!4 &2054727028
Transform:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 2054727025}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 12
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}

106
Assets/ScriptableRenderLoop/HDRenderLoop/Debug/Resources/DebugViewTiles.shader


Shader "Hidden/HDRenderLoop/DebugViewTiles"
{
SubShader
{
SubShader
{
Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
HLSLPROGRAM
HLSLPROGRAM
#pragma target 5.0
#pragma only_renderers d3d11 // TEMP: unitl we go futher in dev

#pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST
//-------------------------------------------------------------------------------------
// Include
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
// Include
//-------------------------------------------------------------------------------------
// Note: We have fix as guidelines that we have only one deferred material (with control of GBuffer enabled). Mean a users that add a new
// deferred material must replace the old one here. If in the future we want to support multiple layout (cause a lot of consistency problem),
// the deferred shader will require to use multicompile.
// Note: We have fix as guidelines that we have only one deferred material (with control of GBuffer enabled). Mean a users that add a new
// deferred material must replace the old one here. If in the future we want to support multiple layout (cause a lot of consistency problem),
// the deferred shader will require to use multicompile.
//-------------------------------------------------------------------------------------
// variable declaration
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
// variable declaration
//-------------------------------------------------------------------------------------
uint _ViewTilesFlags;
uint _ViewTilesFlags;
TEXTURE2D(_CameraDepthTexture);
SAMPLER2D(sampler_CameraDepthTexture);

float4 Vert(float3 positionOS : POSITION): SV_POSITION
{
return TransformWorldToHClip(TransformObjectToWorld(positionOS));
}
float4 Vert(float3 positionOS : POSITION): SV_POSITION
{
return TransformWorldToHClip(TransformObjectToWorld(positionOS));
}
float4 OverlayHeatMap(uint2 pixCoord, uint numLights)
{

return color;
}
float4 Frag(float4 positionCS : SV_POSITION) : SV_Target
{
Coordinate coord = GetCoordinate(positionCS.xy, _ScreenSize.zw);
float4 Frag(float4 positionCS : SV_POSITION) : SV_Target
{
Coordinate coord = GetCoordinate(positionCS.xy, _ScreenSize.zw);
#ifdef USE_CLUSTERED_LIGHTLIST
// Perform same calculation than in deferred.shader

float linearDepth = 0.0; // unused
#endif
int n = 0;
if (_ViewTilesFlags & DEBUGVIEWTILESFLAGS_DIRECT_LIGHTING)
{
uint punctualLightStart;
uint punctualLightCount;
GetCountAndStart(coord, DIRECT_LIGHT, linearDepth, punctualLightStart, punctualLightCount);
n += punctualLightCount;
}
int n = 0;
for (int category = 0; category < LIGHTCATEGORY_COUNT; category++)
{
uint mask = 1u << category;
if (mask & _ViewTilesFlags)
{
uint start;
uint count;
GetCountAndStart(coord, category, linearDepth, start, count);
n += count;
}
}
if (n > 0)
{
return OverlayHeatMap(int2(coord.unPositionSS.xy) & 15, n);
}
else
{
return 0.0;
}
}
if (_ViewTilesFlags & DEBUGVIEWTILESFLAGS_REFLECTION)
{
uint envLightStart;
uint envLightCount;
GetCountAndStart(coord, REFLECTION_LIGHT, linearDepth, envLightStart, envLightCount);
n += envLightCount;
}
if (n > 0)
{
return OverlayHeatMap(int2(coord.unPositionSS.xy) & 15, n);
}
else
{
return 0.0;
}
}
ENDHLSL
}
}
Fallback Off
}
ENDHLSL
}
}
Fallback Off
}

32
Assets/ScriptableRenderLoop/HDRenderLoop/Editor/HDRenderLoopInspector.cs


public readonly GUIContent useForwardRenderingOnly = new GUIContent("Use Forward Rendering Only");
public readonly GUIContent useDepthPrepass = new GUIContent("Use Depth Prepass");
public readonly GUIContent useSinglePassLightLoop = new GUIContent("Use single Pass light loop");
public bool isDebugViewMaterialInit = false;
public GUIContent[] debugViewMaterialStrings = null;

public readonly GUIContent shadowsCascades = new GUIContent("Cascade values");
public readonly GUIContent tileLightLoopSettings = new GUIContent("Tile Light Loop settings");
public readonly GUIContent tileLightLoopDebugMode = new GUIContent("Enable Debug mode", "Toggle overheat map mode");
public readonly GUIContent directIndirectSinglePass = new GUIContent("Enable direct and indirect lighting in single pass", "Toggle");
public readonly string[] tileLightLoopDebugTileFlagStrings = new string[] { "Punctual Light", "Area Light", "Env Light"};
public readonly GUIContent splitLightEvaluation = new GUIContent("Split light and reflection evaluation", "Toggle");
public readonly GUIContent disableTileAndCluster = new GUIContent("Disable Tile/clustered", "Toggle");
public readonly GUIContent textureSettings = new GUIContent("texture Settings");

debugParameters.displayTransparentObjects = EditorGUILayout.Toggle(styles.displayTransparentObjects, debugParameters.displayTransparentObjects);
debugParameters.useForwardRenderingOnly = EditorGUILayout.Toggle(styles.useForwardRenderingOnly, debugParameters.useForwardRenderingOnly);
debugParameters.useDepthPrepass = EditorGUILayout.Toggle(styles.useDepthPrepass, debugParameters.useDepthPrepass);
debugParameters.useSinglePassLightLoop = EditorGUILayout.Toggle(styles.useSinglePassLightLoop, debugParameters.useSinglePassLightLoop);
if (EditorGUI.EndChangeCheck())
{

EditorGUILayout.Space();
if (renderLoop.tilePassLightLoop != null)
// TODO: we should call a virtual method or something similar to setup the UI, inspector should not know about it
TilePass.LightLoop tilePass = renderLoop.lightLoop as TilePass.LightLoop;
if (tilePass != null)
renderLoop.tilePassLightLoop.debugViewTilesFlags = (TilePass.DebugViewTilesFlags)EditorGUILayout.EnumMaskField("DebugView Tiles", renderLoop.tilePassLightLoop.debugViewTilesFlags);
renderLoop.tilePassLightLoop.enableDirectIndirectSinglePass = EditorGUILayout.Toggle(styles.directIndirectSinglePass, renderLoop.tilePassLightLoop.enableDirectIndirectSinglePass);
renderLoop.tilePassLightLoop.enableBigTilePrepass = EditorGUILayout.Toggle(styles.bigTilePrepass, renderLoop.tilePassLightLoop.enableBigTilePrepass);
renderLoop.tilePassLightLoop.enableClustered = EditorGUILayout.Toggle(styles.clustered, renderLoop.tilePassLightLoop.enableClustered);
tilePass.enableBigTilePrepass = EditorGUILayout.Toggle(styles.bigTilePrepass, tilePass.enableBigTilePrepass);
tilePass.enableClustered = EditorGUILayout.Toggle(styles.clustered, tilePass.enableClustered);
// If something is chanage on tilePassLightLoop we need to force a OnValidate() OnHDRenderLoop, else change Rebuild() will not be call
// If something is chanage regarding tile/cluster rendering we need to force a OnValidate() OnHDRenderLoop, else change Rebuild() will not be call
}
EditorGUI.BeginChangeCheck();
tilePass.debugViewTilesFlags = EditorGUILayout.MaskField("DebugView Tiles", tilePass.debugViewTilesFlags, styles.tileLightLoopDebugTileFlagStrings);
tilePass.enableSplitLightEvaluation = EditorGUILayout.Toggle(styles.splitLightEvaluation, tilePass.enableSplitLightEvaluation);
tilePass.disableTileAndCluster = EditorGUILayout.Toggle(styles.disableTileAndCluster, tilePass.disableTileAndCluster);
if (EditorGUI.EndChangeCheck())
{
EditorUtility.SetDirty(renderLoop); // Repaint
UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
}
EditorGUI.indentLevel--;
}

1
Assets/ScriptableRenderLoop/HDRenderLoop/HDRenderLoop.asset


spotCookieSize: 128
pointCookieSize: 512
reflectionCubemapSize: 128
m_Dirty: 0

2
Assets/ScriptableRenderLoop/HDRenderLoop/HDRenderLoop.asset.meta


fileFormatVersion: 2
guid: 2400b74f5ce370c4481e5dc417d03703
timeCreated: 1480436907
timeCreated: 1481084818
licenseType: Pro
NativeFormatImporter:
userData:

491
Assets/ScriptableRenderLoop/HDRenderLoop/HDRenderLoop.cs


SkyRenderer m_SkyRenderer = null;
[SerializeField]
SkyParameters m_SkyParameters = new SkyParameters();
public SkyParameters skyParameters
{
get { return m_SkyParameters; }

public bool enableTonemap = true;
public float exposure = 0;
public bool useSinglePassLightLoop = true;
}
DebugParameters m_DebugParameters = new DebugParameters();

return colorMRTs;
}
/*
public void BindBuffers(Material mat)
{

ShadowRenderPass m_ShadowPass;
public const int k_MaxDirectionalLightsOnSCreen = 3;
public const int k_MaxPunctualLightsOnSCreen = 512;
public const int k_MaxAreaLightsOnSCreen = 128;
public const int k_MaxEnvLightsOnSCreen = 64;
public const int k_MaxShadowOnScreen = 16;
public const int k_MaxCascadeCount = 4; //Should be not less than m_Settings.directionalLightCascadeCount;
[SerializeField]
TextureSettings m_TextureSettings = TextureSettings.Default;

RenderTargetIdentifier m_CameraDepthBufferRT;
RenderTargetIdentifier m_VelocityBufferRT;
RenderTargetIdentifier m_DistortionBufferRT;
public class LightList
{
public List<DirectionalLightData> directionalLights;
public List<DirectionalShadowData> directionalShadows;
public List<LightData> punctualLights;
public List<PunctualShadowData> punctualShadows;
public List<LightData> areaLights;
public List<EnvLightData> envLights;
public Vector4[] directionalShadowSplitSphereSqr;
// Index mapping list to go from GPU lights (above) to CPU light (in cullResult)
public List<int> directionalCullIndices;
public List<int> punctualCullIndices;
public List<int> areaCullIndices;
public List<int> envCullIndices;
public void Clear()
{
directionalLights.Clear();
directionalShadows.Clear();
punctualLights.Clear();
punctualShadows.Clear();
areaLights.Clear();
envLights.Clear();
directionalCullIndices.Clear();
punctualCullIndices.Clear();
areaCullIndices.Clear();
envCullIndices.Clear();
}
public void Allocate()
{
directionalLights = new List<DirectionalLightData>();
punctualLights = new List<LightData>();
areaLights = new List<LightData>();
envLights = new List<EnvLightData>();
punctualShadows = new List<PunctualShadowData>();
directionalShadows = new List<DirectionalShadowData>();
directionalShadowSplitSphereSqr = new Vector4[k_MaxCascadeCount];
directionalCullIndices = new List<int>();
punctualCullIndices = new List<int>();
areaCullIndices = new List<int>();
envCullIndices = new List<int>();
}
}
LightList m_lightList;
// TODO: Find a way to automatically create/iterate through lightloop
// This must be init externally else The value can't be set in the inspector... (as it will recreate the class with default value)
SinglePass.LightLoop m_SinglePassLightLoop = new SinglePass.LightLoop();
TilePass.LightLoop m_TilePassLightLoop = new TilePass.LightLoop();
public TilePass.LightLoop tilePassLightLoop
// This must be allocate outside of Rebuild() else the option in the class can't be set in the inspector (as it will in this case recreate the class with default value)
BaseLightLoop m_lightLoop = new TilePass.LightLoop();
public BaseLightLoop lightLoop
get { return m_TilePassLightLoop; }
get { return m_lightLoop; }
}
// TODO: Find a way to automatically create/iterate through deferred material

TextureCacheCubemap m_CubeReflTexArray;
TextureCache2D m_CookieTexArray;
TextureCacheCubemap m_CubeCookieTexArray;
public void OnValidate()
{
// Calling direction Rebuild() here cause this warning:

m_ShadowPass = new ShadowRenderPass(m_ShadowSettings);
// Init Gbuffer description
// Init Gbuffer description
m_gbufferManager.gbufferCount = m_LitRenderLoop.GetMaterialGBufferCount();
RenderTextureFormat[] RTFormat; RenderTextureReadWrite[] RTReadWrite;

m_DistortionBufferRT = new RenderTargetIdentifier(m_DistortionBuffer);
m_LitRenderLoop.Rebuild();
m_CookieTexArray = new TextureCache2D();
m_CookieTexArray.AllocTextureArray(8, m_TextureSettings.spotCookieSize, m_TextureSettings.spotCookieSize, TextureFormat.RGBA32, true);
m_CubeCookieTexArray = new TextureCacheCubemap();
m_CubeCookieTexArray.AllocTextureArray(4, m_TextureSettings.pointCookieSize, TextureFormat.RGBA32, true);
m_CubeReflTexArray = new TextureCacheCubemap();
m_CubeReflTexArray.AllocTextureArray(32, m_TextureSettings.reflectionCubemapSize, TextureFormat.BC6H, true);
// Init various light loop
m_SinglePassLightLoop.Rebuild();
tilePassLightLoop.Rebuild();
m_lightList = new LightList();
m_lightList.Allocate();
m_lightLoop.Rebuild(m_TextureSettings);
m_Dirty = false;
}

public override void Cleanup()
{
m_LitRenderLoop.Cleanup();
m_SinglePassLightLoop.Cleanup();
m_TilePassLightLoop.Cleanup();
m_lightLoop.Cleanup();
if (m_CubeReflTexArray != null)
{
m_CubeReflTexArray.Release();
m_CubeReflTexArray = null;
}
if (m_CookieTexArray != null)
{
m_CookieTexArray.Release();
m_CookieTexArray = null;
}
if (m_CubeCookieTexArray != null)
{
m_CubeCookieTexArray.Release();
m_CubeCookieTexArray = null;
}
if (m_SkyRenderer != null)
{
m_SkyRenderer.Cleanup();

#endif
}
void NewFrame()
{
m_CookieTexArray.NewFrame();
m_CubeCookieTexArray.NewFrame();
m_CubeReflTexArray.NewFrame();
}
// We clear only the depth buffer, no need to clear the various color buffer as we overwrite them.
// Clear depth/stencil and init buffers
// We clear only the depth buffer, no need to clear the various color buffer as we overwrite them.
// Clear depth/stencil and init buffers
cmd.name = "";
cmd.name = "";
// Init buffer
// With scriptable render loop we must allocate ourself depth and color buffer (We must be independent of backbuffer for now, hope to fix that later).

// TEMP: As we are in development and have not all the setup pass we still clear the color in emissive buffer and gbuffer, but this will be removed later.
// Clear HDR target
using (new Utilities.ProfilingSample("Clear HDR target", renderLoop))
using (new Utilities.ProfilingSample("Clear HDR target", renderLoop))
Utilities.SetRenderTarget(renderLoop, m_CameraColorBufferRT, m_CameraDepthBufferRT, ClearFlag.ClearColor, Color.black);
Utilities.SetRenderTarget(renderLoop, m_CameraColorBufferRT, m_CameraDepthBufferRT, ClearFlag.ClearColor, Color.black);
using (new Utilities.ProfilingSample("Clear GBuffer", renderLoop))
using (new Utilities.ProfilingSample("Clear GBuffer", renderLoop))
Utilities.SetRenderTarget(renderLoop, m_gbufferManager.GetGBuffers(), m_CameraDepthBufferRT, ClearFlag.ClearColor, Color.black);
Utilities.SetRenderTarget(renderLoop, m_gbufferManager.GetGBuffers(), m_CameraDepthBufferRT, ClearFlag.ClearColor, Color.black);
}
// END TEMP

var settings = new DrawRendererSettings(cull, camera, new ShaderPassName(passName))
{
rendererConfiguration = rendererConfiguration,
sorting = { sortOptions = SortOptions.SortByMaterialThenMesh }
};
sorting = { flags = SortFlags.CommonOpaque }
};
settings.inputFilter.SetQueuesOpaque();
renderLoop.DrawRenderers(ref settings);
}

var settings = new DrawRendererSettings(cull, camera, new ShaderPassName(passName))
{
rendererConfiguration = rendererConfiguration,
sorting = { sortOptions = SortOptions.BackToFront }
sorting = { flags = SortFlags.CommonTransparent }
};
settings.inputFilter.SetQueuesTransparent();
renderLoop.DrawRenderers(ref settings);

using (new Utilities.ProfilingSample("Depth Prepass", renderLoop))
{
// TODO: Must do opaque then alpha masked for performance!
// TODO: Must do opaque then alpha masked for performance!
// TODO: front to back for opaque and by materal for opaque tested when we split in two
Utilities.SetRenderTarget(renderLoop, m_CameraDepthBufferRT);
RenderOpaqueRenderList(cull, camera, renderLoop, "DepthOnly");

if (debugParameters.useDepthPrepass)
return;
using (new Utilities.ProfilingSample("Depth Prepass", renderLoop))
using (new Utilities.ProfilingSample("Forward opaque depth", renderLoop))
// or use the new MAterial.SetPassEnable ?
Utilities.SetRenderTarget(renderLoop, m_CameraDepthBufferRT);
RenderOpaqueRenderList(cull, camera, renderLoop, "DepthOnly");
}

// Bind material data
m_LitRenderLoop.Bind();
if (debugParameters.useSinglePassLightLoop)
{
m_SinglePassLightLoop.RenderDeferredLighting(camera, renderLoop, m_CameraColorBuffer);
}
else
{
tilePassLightLoop.RenderDeferredLighting(camera, renderLoop, m_CameraColorBufferRT);
}
m_lightLoop.RenderDeferredLighting(camera, renderLoop, m_CameraColorBuffer);
}
void RenderSky(Camera camera, RenderLoop renderLoop)

void RenderForward(CullResults cullResults, Camera camera, RenderLoop renderLoop)
void RenderForward(CullResults cullResults, Camera camera, RenderLoop renderLoop, bool renderOpaque)
// TODO: Currently we can't render opaque object forward when deferred is enabled
// miss option
if (!debugParameters.useForwardRenderingOnly && renderOpaque)
return;
using (new Utilities.ProfilingSample("Forward Pass", renderLoop))
{
// Bind material data

if (debugParameters.useForwardRenderingOnly)
m_lightLoop.RenderForward(camera, renderLoop, renderOpaque);
if (renderOpaque)
RenderTransparentRenderList(cullResults, camera, renderLoop, "Forward", Utilities.kRendererConfigurationBakedLighting);
else
{
RenderTransparentRenderList(cullResults, camera, renderLoop, "Forward", Utilities.kRendererConfigurationBakedLighting);
}
}
}

}
}
void PrepareLightsForGPU(CullResults cullResults, Camera camera, ref ShadowOutput shadowOutput, ref LightList lightList)
void PrepareLightsForGPU(CullResults cullResults, Camera camera, ref ShadowOutput shadowOutput)
lightList.Clear();
for (int lightIndex = 0, numLights = cullResults.visibleLights.Length; lightIndex < numLights; ++lightIndex)
{
var light = cullResults.visibleLights[lightIndex];
// We only process light with additional data
var additionalData = light.light.GetComponent<AdditionalLightData>();
if (additionalData == null)
{
Debug.LogWarning("Light entity detected without additional data, will not be taken into account " + light.light.name);
continue;
}
// Linear intensity calculation (different Unity 5.5)
var lightColorR = light.light.intensity * Mathf.GammaToLinearSpace(light.light.color.r);
var lightColorG = light.light.intensity * Mathf.GammaToLinearSpace(light.light.color.g);
var lightColorB = light.light.intensity * Mathf.GammaToLinearSpace(light.light.color.b);
if (light.lightType == LightType.Directional)
{
if (lightList.directionalLights.Count >= k_MaxDirectionalLightsOnSCreen)
continue;
var directionalLightData = new DirectionalLightData();
// Light direction for directional and is opposite to the forward direction
directionalLightData.direction = -light.light.transform.forward;
directionalLightData.up = light.light.transform.up;
directionalLightData.right = light.light.transform.right;
directionalLightData.positionWS = light.light.transform.position;
directionalLightData.color = new Vector3(lightColorR, lightColorG, lightColorB);
directionalLightData.diffuseScale = additionalData.affectDiffuse ? 1.0f : 0.0f;
directionalLightData.specularScale = additionalData.affectSpecular ? 1.0f : 0.0f;
directionalLightData.invScaleX = 1.0f / light.light.transform.localScale.x;
directionalLightData.invScaleY = 1.0f / light.light.transform.localScale.y;
directionalLightData.cosAngle = 0.0f;
directionalLightData.sinAngle = 0.0f;
directionalLightData.shadowIndex = -1;
directionalLightData.cookieIndex = -1;
if (light.light.cookie != null)
{
directionalLightData.tileCookie = (light.light.cookie.wrapMode == TextureWrapMode.Repeat);
directionalLightData.cookieIndex = m_CookieTexArray.FetchSlice(light.light.cookie);
}
bool hasDirectionalShadows = light.light.shadows != LightShadows.None && shadowOutput.GetShadowSliceCountLightIndex(lightIndex) != 0;
bool hasDirectionalNotReachMaxLimit = lightList.directionalShadows.Count == 0; // Only one cascade shadow allowed
if (hasDirectionalShadows && hasDirectionalNotReachMaxLimit) // Note < MaxShadows should be check at shadowOutput creation
{
// When we have a point light, we assumed that there is 6 consecutive PunctualShadowData
directionalLightData.shadowIndex = 0;
for (int sliceIndex = 0; sliceIndex < shadowOutput.GetShadowSliceCountLightIndex(lightIndex); ++sliceIndex)
{
DirectionalShadowData directionalShadowData = new DirectionalShadowData();
int shadowSliceIndex = shadowOutput.GetShadowSliceIndex(lightIndex, sliceIndex);
directionalShadowData.worldToShadow = shadowOutput.shadowSlices[shadowSliceIndex].shadowTransform.transpose; // Transpose for hlsl reading ?
directionalShadowData.bias = light.light.shadowBias;
lightList.directionalShadows.Add(directionalShadowData);
}
// Fill split information for shaders
for (int s = 0; s < k_MaxCascadeCount; ++s)
{
lightList.directionalShadowSplitSphereSqr[s] = shadowOutput.directionalShadowSplitSphereSqr[s];
}
}
lightList.directionalLights.Add(directionalLightData);
lightList.directionalCullIndices.Add(lightIndex);
continue;
}
// Note: LightType.Area is offline only, use for baking, no need to test it
var lightData = new LightData();
// Test whether we should treat this punctual light as an area light.
// It's a temporary hack until the proper UI support is added.
if (additionalData.archetype != LightArchetype.Punctual)
{
// Early out if we reach the maximum
if (lightList.areaLights.Count >= k_MaxAreaLightsOnSCreen)
continue;
if (additionalData.archetype == LightArchetype.Rectangle)
{
lightData.lightType = GPULightType.Rectangle;
}
else
{
lightData.lightType = GPULightType.Line;
}
}
else
{
if (lightList.punctualLights.Count >= k_MaxPunctualLightsOnSCreen)
continue;
switch (light.lightType)
{
case LightType.Directional: lightData.lightType = GPULightType.Directional; break;
case LightType.Spot: lightData.lightType = GPULightType.Spot; break;
case LightType.Point: lightData.lightType = GPULightType.Point; break;
}
}
lightData.positionWS = light.light.transform.position;
lightData.invSqrAttenuationRadius = 1.0f / (light.range * light.range);
lightData.color = new Vector3(lightColorR, lightColorG, lightColorB);
lightData.forward = light.light.transform.forward; // Note: Light direction is oriented backward (-Z)
lightData.up = light.light.transform.up;
lightData.right = light.light.transform.right;
if (lightData.lightType == GPULightType.Spot)
{
var spotAngle = light.spotAngle;
var innerConePercent = additionalData.GetInnerSpotPercent01();
var cosSpotOuterHalfAngle = Mathf.Clamp(Mathf.Cos(spotAngle * 0.5f * Mathf.Deg2Rad), 0.0f, 1.0f);
var sinSpotOuterHalfAngle = Mathf.Sqrt(1.0f - cosSpotOuterHalfAngle * cosSpotOuterHalfAngle);
var cosSpotInnerHalfAngle = Mathf.Clamp(Mathf.Cos(spotAngle * 0.5f * innerConePercent * Mathf.Deg2Rad), 0.0f, 1.0f); // inner cone
var val = Mathf.Max(0.001f, (cosSpotInnerHalfAngle - cosSpotOuterHalfAngle));
lightData.angleScale = 1.0f / val;
lightData.angleOffset = -cosSpotOuterHalfAngle * lightData.angleScale;
// TODO: find a proper place to store the cotangent.
lightData.size.x = cosSpotOuterHalfAngle / sinSpotOuterHalfAngle;
}
else
{
// 1.0f, 2.0f are neutral value allowing GetAngleAnttenuation in shader code to return 1.0
lightData.angleScale = 1.0f;
lightData.angleOffset = 2.0f;
}
lightData.diffuseScale = additionalData.affectDiffuse ? 1.0f : 0.0f;
lightData.specularScale = additionalData.affectSpecular ? 1.0f : 0.0f;
lightData.shadowDimmer = additionalData.shadowDimmer;
lightData.IESIndex = -1;
lightData.cookieIndex = -1;
lightData.shadowIndex = -1;
if (light.light.cookie != null)
{
// TODO: add texture atlas support for cookie textures.
switch (light.lightType)
{
case LightType.Spot:
lightData.cookieIndex = m_CookieTexArray.FetchSlice(light.light.cookie);
break;
case LightType.Point:
lightData.cookieIndex = m_CubeCookieTexArray.FetchSlice(light.light.cookie);
break;
}
}
// Setup shadow data arrays
bool hasShadows = light.light.shadows != LightShadows.None && shadowOutput.GetShadowSliceCountLightIndex(lightIndex) != 0;
bool hasNotReachMaxLimit = lightList.punctualShadows.Count + (lightData.lightType == GPULightType.Point ? 6 : 1) <= k_MaxShadowOnScreen;
if (hasShadows && hasNotReachMaxLimit) // Note < MaxShadows should be check at shadowOutput creation
{
// When we have a point light, we assumed that there is 6 consecutive PunctualShadowData
lightData.shadowIndex = lightList.punctualShadows.Count;
for (int sliceIndex = 0; sliceIndex < shadowOutput.GetShadowSliceCountLightIndex(lightIndex); ++sliceIndex)
{
PunctualShadowData punctualShadowData = new PunctualShadowData();
int shadowSliceIndex = shadowOutput.GetShadowSliceIndex(lightIndex, sliceIndex);
punctualShadowData.worldToShadow = shadowOutput.shadowSlices[shadowSliceIndex].shadowTransform.transpose; // Transpose for hlsl reading ?
punctualShadowData.lightType = lightData.lightType;
punctualShadowData.bias = light.light.shadowBias;
lightList.punctualShadows.Add(punctualShadowData);
}
}
if (additionalData.archetype == LightArchetype.Punctual)
{
lightList.punctualLights.Add(lightData);
lightList.punctualCullIndices.Add(lightIndex);
}
else
{
lightData.twoSided = additionalData.isDoubleSided;
lightData.size = new Vector2(additionalData.areaLightLength,
additionalData.areaLightWidth);
// Area and line lights are both currently stored as area lights on the GPU.
lightList.areaLights.Add(lightData);
lightList.areaCullIndices.Add(lightIndex);
}
}
for (int probeIndex = 0, numProbes = cullResults.visibleReflectionProbes.Length; probeIndex < numProbes; probeIndex++)
{
var probe = cullResults.visibleReflectionProbes[probeIndex];
// If probe have not been rendered discard
if (probe.texture == null)
continue;
if (lightList.envLights.Count >= k_MaxEnvLightsOnSCreen)
continue;
var envLightData = new EnvLightData();
// CAUTION: localToWorld is the transform for the widget of the reflection probe. i.e the world position of the point use to do the cubemap capture (mean it include the local offset)
envLightData.positionWS = probe.localToWorld.GetColumn(3);
envLightData.envShapeType = EnvShapeType.None;
// TODO: Support sphere in the interface
if (probe.boxProjection != 0)
{
envLightData.envShapeType = EnvShapeType.Box;
}
// remove scale from the matrix (Scale in this matrix is use to scale the widget)
envLightData.right = probe.localToWorld.GetColumn(0);
envLightData.right.Normalize();
envLightData.up = probe.localToWorld.GetColumn(1);
envLightData.up.Normalize();
envLightData.forward = probe.localToWorld.GetColumn(2);
envLightData.forward.Normalize();
// Artists prefer to have blend distance inside the volume!
// So we let the current UI but we assume blendDistance is an inside factor instead
// Blend distance can't be larger than the max radius
// probe.bounds.extents is BoxSize / 2
float maxBlendDist = Mathf.Min(probe.bounds.extents.x, Mathf.Min(probe.bounds.extents.y, probe.bounds.extents.z));
float blendDistance = Mathf.Min(maxBlendDist, probe.blendDistance);
envLightData.innerDistance = probe.bounds.extents - new Vector3(blendDistance, blendDistance, blendDistance);
envLightData.envIndex = m_CubeReflTexArray.FetchSlice(probe.texture);
envLightData.offsetLS = probe.center; // center is misnamed, it is the offset (in local space) from center of the bounding box to the cubemap capture point
envLightData.blendDistance = blendDistance;
lightList.envLights.Add(envLightData);
lightList.envCullIndices.Add(probeIndex);
}
if (debugParameters.useSinglePassLightLoop)
{
m_SinglePassLightLoop.PrepareLightsForGPU(cullResults, camera, m_lightList);
}
else
{
tilePassLightLoop.PrepareLightsForGPU(cullResults, camera, m_lightList);
}
m_lightLoop.PrepareLightsForGPU(cullResults, camera, ref shadowOutput);
}
void Resize(Camera camera)

// the below buffer which is bad. Best is to have a set of buffer for each camera that is persistent and reallocate resource if need
// For now consider we have only one camera that go to this code, the main one.
m_SkyRenderer.Resize(m_SkyParameters); // TODO: Also a bad naming, here we just want to realloc texture if skyparameters change (usefull for lookdev)
if (camera.pixelWidth != m_WidthOnRecord || camera.pixelHeight != m_HeightOnRecord || tilePassLightLoop.NeedResize())
if (camera.pixelWidth != m_WidthOnRecord || camera.pixelHeight != m_HeightOnRecord || m_lightLoop.NeedResize())
tilePassLightLoop.ReleaseResolutionDependentBuffers();
m_lightLoop.ReleaseResolutionDependentBuffers();
tilePassLightLoop.AllocResolutionDependentBuffers(camera.pixelWidth, camera.pixelHeight);
m_lightLoop.AllocResolutionDependentBuffers(camera.pixelWidth, camera.pixelHeight);
// update recorded window resolution
m_WidthOnRecord = camera.pixelWidth;

public void PushGlobalParams(Camera camera, RenderLoop renderLoop, HDRenderLoop.LightList lightList)
public void PushGlobalParams(Camera camera, RenderLoop renderLoop)
Shader.SetGlobalTexture("_CookieTextures", m_CookieTexArray.GetTexCache());
Shader.SetGlobalTexture("_CookieCubeTextures", m_CubeCookieTexArray.GetTexCache());
Shader.SetGlobalTexture("_EnvTextures", m_CubeReflTexArray.GetTexCache());
if (m_SkyRenderer.IsSkyValid(m_SkyParameters))
{
m_SkyRenderer.SetGlobalSkyTexture();

Shader.SetGlobalInt("_EnvLightSkyEnabled", 0);
}
if (debugParameters.useSinglePassLightLoop)
{
m_SinglePassLightLoop.PushGlobalParams(camera, renderLoop, lightList);
}
else
{
tilePassLightLoop.PushGlobalParams(camera, renderLoop, lightList);
}
m_lightLoop.PushGlobalParams(camera, renderLoop);
}
public override void Render(Camera[] cameras, RenderLoop renderLoop)

}
// Do anything we need to do upon a new frame.
NewFrame();
m_lightLoop.NewFrame();
// Set Frame constant buffer
// TODO...

RenderDepthPrepass(cullResults, camera, renderLoop);
RenderGBuffer(cullResults, camera, renderLoop);
RenderGBuffer(cullResults, camera, renderLoop);
// For tile lighting with forward opaque
// Forward opaque with deferred tile require that we fill the depth buffer
// correctly to build the light list.
// TODO: avoid double lighting by tagging stencil or gbuffer that we must not lit.
// TODO: ask Morten why this pass is not before GBuffer ? Will make more sense and avoid
// to do gbuffer pass on unseen mesh.
// TODO: how do we select only the object that must be render forward ?
// this is all object with gbuffer pass disabled ?
//RenderForwardOpaqueDepth(cullResults, camera, renderLoop);
if (debugParameters.debugViewMaterial != 0)

using (new Utilities.ProfilingSample("Build Light list", renderLoop))
{
PrepareLightsForGPU(cullResults, camera, ref shadows, ref m_lightList);
if (!debugParameters.useSinglePassLightLoop)
tilePassLightLoop.BuildGPULightLists(camera, renderLoop, m_lightList, m_CameraDepthBufferRT);
m_lightLoop.PrepareLightsForGPU(cullResults, camera, ref shadows);
m_lightLoop.BuildGPULightLists(camera, renderLoop, m_CameraDepthBufferRT);
PushGlobalParams(camera, renderLoop, m_lightList);
PushGlobalParams(camera, renderLoop);
// TODO: enable this for tile forward opaque
// RenderForward(cullResults, camera, renderLoop, true);
RenderForward(cullResults, camera, renderLoop); // Note: We want to render forward opaque before RenderSky, then RenderTransparent - can only do that once we have material.SetPass feature...
RenderForward(cullResults, camera, renderLoop, false);
RenderVelocity(cullResults, camera, renderLoop); // Note we may have to render velocity earlier if we do temporalAO, temporal volumetric etc... Mean we will not take into account forward opaque in case of deferred rendering ?
RenderVelocity(cullResults, camera, renderLoop); // Note we may have to render velocity earlier if we do temporalAO, temporal volumetric etc... Mean we will not take into account forward opaque in case of deferred rendering ?
// TODO: Check with VFX team.
// Rendering distortion here have off course lot of artifact.

16
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/LightDefinition.cs


[GenerateHLSL]
public struct DirectionalLightData
{
public Vector3 direction;
public Vector3 forward;
public float diffuseScale;
public Vector3 up;

// TODO: we may have to add various parameters here for shadow - was suppose to be coupled with a light loop
// A point light is 6x PunctualShadowData
[GenerateHLSL]
public struct PunctualShadowData
public struct ShadowData
{
// World to ShadowMap matrix
// Include scale and bias for shadow atlas if any

public float bias;
public float quality;
public float unused;
};
[GenerateHLSL]
public struct DirectionalShadowData
{
// World to ShadowMap matrix
// Include scale and bias for shadow atlas if any
public Matrix4x4 worldToShadow;
public float bias;
public float quality;
public Vector2 unused2;
};
[GenerateHLSL]

52
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/LightDefinition.cs.hlsl


// PackingRules = Exact
struct DirectionalLightData
{
float3 direction;
float3 forward;
float diffuseScale;
float3 up;
float invScaleY;

int cookieIndex;
};
// Generated from UnityEngine.Experimental.ScriptableRenderLoop.PunctualShadowData
// Generated from UnityEngine.Experimental.ScriptableRenderLoop.ShadowData
struct PunctualShadowData
struct ShadowData
{
float4x4 worldToShadow;
int lightType;

};
// Generated from UnityEngine.Experimental.ScriptableRenderLoop.DirectionalShadowData
// PackingRules = Exact
struct DirectionalShadowData
{
float4x4 worldToShadow;
float bias;
float quality;
float2 unused2;
};
// Generated from UnityEngine.Experimental.ScriptableRenderLoop.EnvLightData
// PackingRules = Exact
struct EnvLightData

//
// Accessors for UnityEngine.Experimental.ScriptableRenderLoop.DirectionalLightData
//
float3 GetDirection(DirectionalLightData value)
float3 GetForward(DirectionalLightData value)
return value.direction;
return value.forward;
}
float GetDiffuseScale(DirectionalLightData value)
{

}
//
// Accessors for UnityEngine.Experimental.ScriptableRenderLoop.PunctualShadowData
// Accessors for UnityEngine.Experimental.ScriptableRenderLoop.ShadowData
float4x4 GetWorldToShadow(PunctualShadowData value)
float4x4 GetWorldToShadow(ShadowData value)
int GetLightType(PunctualShadowData value)
int GetLightType(ShadowData value)
float GetBias(PunctualShadowData value)
float GetBias(ShadowData value)
float GetQuality(PunctualShadowData value)
float GetQuality(ShadowData value)
float GetUnused(PunctualShadowData value)
float GetUnused(ShadowData value)
}
//
// Accessors for UnityEngine.Experimental.ScriptableRenderLoop.DirectionalShadowData
//
float4x4 GetWorldToShadow(DirectionalShadowData value)
{
return value.worldToShadow;
}
float GetBias(DirectionalShadowData value)
{
return value.bias;
}
float GetQuality(DirectionalShadowData value)
{
return value.quality;
}
float2 GetUnused2(DirectionalShadowData value)
{
return value.unused2;
}
//

10
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/Lighting.hlsl


#define HAS_LIGHTLOOP // Allow to not define LightLoop related function in Material.hlsl
#include "Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/LightDefinition.cs.hlsl"
#ifdef LIGHTLOOP_SINGLE_PASS
#include "Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/SinglePass/SinglePass.hlsl"
#elif defined(LIGHTLOOP_TILE_PASS)
#if defined(LIGHTLOOP_SINGLE_PASS) || defined(LIGHTLOOP_TILE_PASS)
#include "Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/TilePass.hlsl"
#endif

// LightLoop use evaluation BSDF function for light type define in Material.hlsl
#ifdef LIGHTLOOP_SINGLE_PASS
#include "Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/SinglePass/SinglePassLoop.hlsl"
#elif defined(LIGHTLOOP_TILE_PASS)
#if defined(LIGHTLOOP_SINGLE_PASS) || defined(LIGHTLOOP_TILE_PASS)
#include "Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/TilePassLoop.hlsl"
#endif

7
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/Resources/lightlistbuild-bigtile.compute


uniform float4x4 g_mScrProjection;
uniform float g_fNearPlane;
uniform float g_fFarPlane;
uniform int _EnvLightIndexShift;
StructuredBuffer<LightShapeData> _LightShapeData : register(t2);
StructuredBuffer<LightVolumeData> _LightVolumeData : register(t2);
StructuredBuffer<SFiniteLightBound> g_data : register( t3 );

int offs = tileIDX.y*nrBigTilesX + tileIDX.x;
for(i=t; i<(iNrCoarseLights+1); i+=NR_THREADS)
g_vLightList[MAX_NR_BIGTILE_LIGHTS_PLUSONE*offs + i] = t==0 ? iNrCoarseLights : lightsListLDS[i-1];
g_vLightList[MAX_NR_BIGTILE_LIGHTS_PLUSONE*offs + i] = i==0 ? iNrCoarseLights : lightsListLDS[i-1];
}

for(int l=0; l<iNrCoarseLights; l++)
{
const uint idxCoarse = lightsListLDS[l];
[branch]if (idxCoarse<(uint)g_iNrVisibLights && _LightShapeData[idxCoarse].lightType != SPHERE_LIGHT) // don't bother doing edge tests for sphere lights since these have camera aligned bboxes.
[branch]if (idxCoarse<(uint)g_iNrVisibLights && _LightVolumeData[idxCoarse].lightVolume != LIGHTVOLUMETYPE_SPHERE) // don't bother doing edge tests for sphere lights since these have camera aligned bboxes.
{
SFiniteLightBound lgtDat = g_data[idxCoarse];

23
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/Resources/lightlistbuild-clustered.compute


uniform int g_iNrVisibLights;
uniform float4x4 g_mInvScrProjection;
uniform float4x4 g_mScrProjection;
uniform int _EnvLightIndexShift;
uniform float g_fClustScale;
uniform float g_fClustBase;

Texture2D g_depth_tex : register( t0 );
#endif
StructuredBuffer<float3> g_vBoundsBuffer : register( t1 );
StructuredBuffer<LightShapeData> _LightShapeData : register(t2);
StructuredBuffer<LightVolumeData> _LightVolumeData : register(t2);
StructuredBuffer<SFiniteLightBound> g_data : register( t3 );
#ifdef USE_TWO_PASS_TILED_LIGHTING

InterlockedAdd(g_LayeredSingleIdxBuffer[0], (uint) iSpaceAvail, start); // alloc list memory
}
int modelListCount[NR_LIGHT_MODELS]={0,0}; // direct light count and reflection lights
// All our cull data are in the same list, but at render time envLights are separated so we need to shit the index
// to make it work correctly
int shiftIndex[LIGHTCATEGORY_COUNT] = {0, 0, _EnvLightIndexShift}; // 3 for now, will throw an error if we change LIGHTCATEGORY_COUNT
int categoryListCount[LIGHTCATEGORY_COUNT]={0,0,0}; // direct light count and reflection lights
uint offs = start;
for(int ll=0; ll<iNrCoarseLights; ll+=4)
{

{
if(offs<(start+iSpaceAvail) && i<nrClusters && CheckIntersection(l, i, viTilLL.xy, viTilUR.xy, suggestedBase) )
{
uint lightCategory = _LightShapeData[coarseList[l]].lightCategory;
++modelListCount[lightCategory == REFLECTION_LIGHT ? 1 : 0];
g_vLayeredLightList[offs++] = coarseList[l]; // reflection lights will be last since we sorted
uint lightCategory = _LightVolumeData[coarseList[l]].lightCategory;
++categoryListCount[lightCategory];
g_vLayeredLightList[offs++] = coarseList[l] - shiftIndex[lightCategory]; // reflection lights will be last since we sorted
}
}

uint localOffs=0;
offs = i*nrTilesX*nrTilesY + tileIDX.y*nrTilesX + tileIDX.x;
for(int m=0; m<NR_LIGHT_MODELS; m++)
for(int category=0; category<LIGHTCATEGORY_COUNT; category++)
int numLights = min(modelListCount[m],31); // only allow 5 bits
int numLights = min(categoryListCount[category],31); // only allow 5 bits
localOffs += modelListCount[m]; // use unclamped count for localOffs
localOffs += categoryListCount[category]; // use unclamped count for localOffs
}
}

GroupMemoryBarrierWithGroupSync();
#endif
const int idxCoarse = coarseList[l];
[branch]if (_LightShapeData[idxCoarse].lightType != SPHERE_LIGHT) // don't bother doing edge tests for sphere lights since these have camera aligned bboxes.
[branch]if (_LightVolumeData[idxCoarse].lightVolume != LIGHTVOLUMETYPE_SPHERE) // don't bother doing edge tests for sphere lights since these have camera aligned bboxes.
{
SFiniteLightBound lgtDat = g_data[idxCoarse];

46
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/Resources/lightlistbuild.compute


uniform uint2 g_viDimensions;
uniform float4x4 g_mInvScrProjection;
uniform float4x4 g_mScrProjection;
uniform int _EnvLightIndexShift;
StructuredBuffer<LightShapeData> _LightShapeData : register(t2);
StructuredBuffer<LightVolumeData> _LightVolumeData : register(t2);
StructuredBuffer<SFiniteLightBound> g_data : register( t3 );
#ifdef USE_TWO_PASS_TILED_LIGHTING

#endif
groupshared int ldsNrLightsFinal;
groupshared int ldsModelListCount[NR_LIGHT_MODELS]; // since NR_LIGHT_MODELS is 2
groupshared int ldsCategoryListCount[LIGHTCATEGORY_COUNT]; // since LIGHTCATEGORY_COUNT is 3
#ifdef PERFORM_SPHERICAL_INTERSECTION_TESTS
groupshared uint lightOffsSph;

#endif
//
if(t<NR_LIGHT_MODELS) ldsModelListCount[t]=0;
if(t<LIGHTCATEGORY_COUNT) ldsCategoryListCount[t]=0;
#if !defined(SHADER_API_XBOXONE) && !defined(SHADER_API_PSSL)
GroupMemoryBarrierWithGroupSync();

int nrLightsCombinedList = min(ldsNrLightsFinal,MAX_NR_COARSE_ENTRIES);
for(int i=t; i<nrLightsCombinedList; i+=NR_THREADS)
{
InterlockedAdd(ldsModelListCount[_LightShapeData[prunedList[i]].lightCategory], 1);
InterlockedAdd(ldsCategoryListCount[_LightVolumeData[prunedList[i]].lightCategory], 1);
}

int localOffs=0;
int offs = tileIDX.y*nrTilesX + tileIDX.x;
for(int m=0; m<NR_LIGHT_MODELS; m++)
// All our cull data are in the same list, but at render time envLights are separated so we need to shit the index
// to make it work correctly
int shiftIndex[LIGHTCATEGORY_COUNT] = {0, 0, _EnvLightIndexShift}; // 3 for now, will throw an error if we change LIGHTCATEGORY_COUNT
for(int category=0; category<LIGHTCATEGORY_COUNT; category++)
int nrLightsFinal = ldsModelListCount[ m ];
int nrLightsFinal = ldsCategoryListCount[category];
int nrLightsFinalClamped = nrLightsFinal<MAX_NR_PRUNED_ENTRIES ? nrLightsFinal : MAX_NR_PRUNED_ENTRIES;

// We remap the prunedList index to the original LightData / EnvLightData indices
uint uLow = l==0 ? nrLightsFinalClamped : _LightShapeData[prunedList[2*l-1+localOffs]].lightIndex;
uint uHigh = _LightShapeData[prunedList[2 * l + 0 + localOffs]].lightIndex;
uint uLow = l==0 ? nrLightsFinalClamped : prunedList[2*l-1+localOffs] - shiftIndex[category];
uint uHigh = prunedList[2 * l + 0 + localOffs] - shiftIndex[category];
g_vLightList[16*offs + l] = (uLow&0xffff) | (uHigh<<16);
}

for(l=threadID; l<iNrCoarseLights; l+=NR_THREADS)
{
SFiniteLightBound lightData = g_data[coarseList[l]];
SFiniteLightBound lightData = g_data[prunedList[l]];
if( DoesSphereOverlapTile(V, halfTileSizeAtZDistOne, lightData.center.xyz, lightData.radius) )
{

{
// fetch light
int idxCoarse = l<iNrCoarseLights ? coarseList[l] : 0;
uint uLgtType = l<iNrCoarseLights ? _LightShapeData[idxCoarse].lightType : 0;
uint uLightVolume = l<iNrCoarseLights ? _LightVolumeData[idxCoarse].lightVolume : 0;
while(l<iNrCoarseLights && uLgtType==SPOT_LIGHT)
while(l<iNrCoarseLights && uLightVolume==LIGHTVOLUMETYPE_CONE)
LightShapeData lightData = _LightShapeData[idxCoarse];
LightVolumeData lightData = _LightVolumeData[idxCoarse];
// TODO: Change by SebL
const bool bIsSpotDisc = true; // (lightData.flags&IS_CIRCULAR_SPOT_SHAPE) != 0;

uLightsFlags[l<32 ? 0 : 1] |= (uVal<<(l&31));
++l; idxCoarse = l<iNrCoarseLights ? coarseList[l] : 0;
uLgtType = l<iNrCoarseLights ? _LightShapeData[idxCoarse].lightType : 0;
uLightVolume = l<iNrCoarseLights ? _LightVolumeData[idxCoarse].lightVolume : 0;
while(l<iNrCoarseLights && uLgtType==SPHERE_LIGHT)
while(l<iNrCoarseLights && uLightVolume==LIGHTVOLUMETYPE_SPHERE)
LightShapeData lightData = _LightShapeData[idxCoarse];
LightVolumeData lightData = _LightVolumeData[idxCoarse];
// serially check 4 pixels
uint uVal = 0;

uLightsFlags[l<32 ? 0 : 1] |= (uVal<<(l&31));
++l; idxCoarse = l<iNrCoarseLights ? coarseList[l] : 0;
uLgtType = l<iNrCoarseLights ? _LightShapeData[idxCoarse].lightType : 0;
uLightVolume = l<iNrCoarseLights ? _LightVolumeData[idxCoarse].lightVolume : 0;
while(l<iNrCoarseLights && uLgtType==BOX_LIGHT)
while(l<iNrCoarseLights && uLightVolume==LIGHTVOLUMETYPE_BOX)
LightShapeData lightData = _LightShapeData[idxCoarse];
LightVolumeData lightData = _LightVolumeData[idxCoarse];
// serially check 4 pixels
uint uVal = 0;

uLightsFlags[l<32 ? 0 : 1] |= (uVal<<(l&31));
++l; idxCoarse = l<iNrCoarseLights ? coarseList[l] : 0;
uLgtType = l<iNrCoarseLights ? _LightShapeData[idxCoarse].lightType : 0;
uLightVolume = l<iNrCoarseLights ? _LightVolumeData[idxCoarse].lightVolume : 0;
if(uLgtType>=MAX_TYPES) ++l;
if(uLightVolume >=LIGHTVOLUMETYPE_COUNT) ++l;
}
InterlockedOr(ldsDoesLightIntersect[0], uLightsFlags[0]);

12
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/ShaderBase.hlsl


float FetchDepth(Texture2D depthTexture, uint2 pixCoord)
{
return 1.0 - LOAD_TEXTURE2D(depthTexture, pixCoord.xy).x;
float zdpth = LOAD_TEXTURE2D(depthTexture, pixCoord.xy).x;
#if !defined(SHADER_API_GLES3) && !defined(SHADER_API_GLCORE)
zdpth = 1.0 - zdpth;
#endif
return zdpth;
return 1.0 - LOAD_TEXTURE2D_MSAA(depthTexture, pixCoord.xy, sampleIdx).x;
float zdpth = LOAD_TEXTURE2D_MSAA(depthTexture, pixCoord.xy, sampleIdx).x;
#if !defined(SHADER_API_GLES3) && !defined(SHADER_API_GLCORE)
zdpth = 1.0 - zdpth;
#endif
return zdpth;
}
#endif

922
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/TilePass.cs
文件差异内容过多而无法显示
查看文件

72
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/TilePass.cs.hlsl


#ifndef TILEPASS_CS_HLSL
#define TILEPASS_CS_HLSL
//
// UnityEngine.Experimental.ScriptableRenderLoop.TilePass.LightVolumeType: static fields
//
#define LIGHTVOLUMETYPE_CONE (0)
#define LIGHTVOLUMETYPE_SPHERE (1)
#define LIGHTVOLUMETYPE_BOX (2)
#define LIGHTVOLUMETYPE_COUNT (3)
//
// UnityEngine.Experimental.ScriptableRenderLoop.TilePass.LightCategory: static fields
//
#define LIGHTCATEGORY_PUNCTUAL (0)
#define LIGHTCATEGORY_AREA (1)
#define LIGHTCATEGORY_ENV (2)
#define LIGHTCATEGORY_COUNT (3)
//
// UnityEngine.Experimental.ScriptableRenderLoop.TilePass.LightDefinitions: static fields
//
#define MAX_NR_LIGHTS_PER_CAMERA (1024)

#define HAS_COOKIE_TEXTURE (2)
#define IS_BOX_PROJECTED (4)
#define HAS_SHADOW (8)
#define MAX_TYPES (3)
#define SPOT_LIGHT (0)
#define SPHERE_LIGHT (1)
#define BOX_LIGHT (2)
#define DIRECTIONAL_LIGHT (3)
#define NR_LIGHT_MODELS (2)
#define DIRECT_LIGHT (0)
#define REFLECTION_LIGHT (1)
//
// UnityEngine.Experimental.ScriptableRenderLoop.TilePass.DebugViewTilesFlags: static fields
//
#define DEBUGVIEWTILESFLAGS_DIRECT_LIGHTING (1)
#define DEBUGVIEWTILESFLAGS_REFLECTION (2)
// Generated from UnityEngine.Experimental.ScriptableRenderLoop.TilePass.SFiniteLightBound
// PackingRules = Exact

float radius;
};
// Generated from UnityEngine.Experimental.ScriptableRenderLoop.TilePass.LightShapeData
// Generated from UnityEngine.Experimental.ScriptableRenderLoop.TilePass.LightVolumeData
struct LightShapeData
struct LightVolumeData
uint lightIndex;
uint lightVolume;
uint lightType;
uint lightCategory;
uint lightCategory;
float unused;
float3 boxInvRange;
float unused2;
};

}
//
// Accessors for UnityEngine.Experimental.ScriptableRenderLoop.TilePass.LightShapeData
// Accessors for UnityEngine.Experimental.ScriptableRenderLoop.TilePass.LightVolumeData
float3 GetLightPos(LightShapeData value)
float3 GetLightPos(LightVolumeData value)
uint GetLightIndex(LightShapeData value)
uint GetLightVolume(LightVolumeData value)
return value.lightIndex;
return value.lightVolume;
float3 GetLightAxisX(LightShapeData value)
float3 GetLightAxisX(LightVolumeData value)
uint GetLightType(LightShapeData value)
uint GetLightCategory(LightVolumeData value)
return value.lightType;
return value.lightCategory;
float3 GetLightAxisY(LightShapeData value)
float3 GetLightAxisY(LightVolumeData value)
float GetRadiusSq(LightShapeData value)
float GetRadiusSq(LightVolumeData value)
float3 GetLightAxisZ(LightShapeData value)
float3 GetLightAxisZ(LightVolumeData value)
float GetCotan(LightShapeData value)
float GetCotan(LightVolumeData value)
float3 GetBoxInnerDist(LightShapeData value)
float3 GetBoxInnerDist(LightVolumeData value)
uint GetLightCategory(LightShapeData value)
float GetUnused(LightVolumeData value)
return value.lightCategory;
return value.unused;
float3 GetBoxInvRange(LightShapeData value)
float3 GetBoxInvRange(LightVolumeData value)
float GetUnused2(LightShapeData value)
float GetUnused2(LightVolumeData value)
{
return value.unused2;
}

176
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/TilePass.hlsl


uint _UseTileLightList;
//#endif
#ifdef USE_CLUSTERED_LIGHTLIST
//#ifdef USE_CLUSTERED_LIGHTLIST
//#endif
StructuredBuffer<DirectionalLightData> _DirectionalLightDatas;
StructuredBuffer<LightData> _LightDatas;
StructuredBuffer<EnvLightData> _EnvLightDatas;
StructuredBuffer<ShadowData> _ShadowDatas;
// Use texture atlas for shadow map
//TEXTURE2D(_ShadowAtlas);
//SAMPLER2D_SHADOW(sampler_ShadowAtlas);
//SAMPLER2D(sampler_ManualShadowAtlas); // TODO: settings sampler individually is not supported in shader yet...
TEXTURE2D(g_tShadowBuffer) // TODO: No choice, the name is hardcoded in ShadowrenderPass.cs for now. Need to change this!
SAMPLER2D_SHADOW(samplerg_tShadowBuffer);
// Use texture array for IES
TEXTURE2D_ARRAY(_IESArray);
SAMPLER2D(sampler_IESArray);
// Used by directional and spot lights
TEXTURE2D_ARRAY(_CookieTextures);
SAMPLER2D(sampler_CookieTextures);
// Used by point lights
TEXTURECUBE_ARRAY(_CookieCubeTextures);
SAMPLERCUBE(sampler_CookieCubeTextures);
// Use texture array for reflection
TEXTURECUBE_ARRAY(_EnvTextures);
SAMPLERCUBE(sampler_EnvTextures);
TEXTURECUBE(_SkyTexture);
SAMPLERCUBE(sampler_SkyTexture); // NOTE: Sampler could be share here with _EnvTextures. Don't know if the shader compiler will complain...
CBUFFER_START(UnityPerLightLoop)
uint _DirectionalLightCount;
uint _PunctualLightCount;
uint _AreaLightCount;
uint _EnvLightCount;
float4 _DirShadowSplitSpheres[4]; // TODO: share this max between C# and hlsl
int _EnvLightSkyEnabled; // TODO: make it a bool
CBUFFER_END
struct LightLoopContext
{
int sampleShadow;
int sampleReflection;
};
//-----------------------------------------------------------------------------
// Shadow sampling function
// ----------------------------------------------------------------------------
float GetPunctualShadowAttenuation(LightLoopContext lightLoopContext, float3 positionWS, int index, float3 L, float2 unPositionSS)
{
int faceIndex = 0;
if (_ShadowDatas[index].lightType == GPULIGHTTYPE_POINT)
{
GetCubeFaceID(L, faceIndex);
}
ShadowData shadowData = _ShadowDatas[index + faceIndex];
// Note: scale and bias of shadow atlas are included in ShadowTransform but could be apply here.
float4 positionTXS = mul(float4(positionWS, 1.0), shadowData.worldToShadow);
positionTXS.xyz /= positionTXS.w;
// positionTXS.z -= shadowData.bias; // Apply a linear bias
positionTXS.z -= 0.001;
#if UNITY_REVERSED_Z
positionTXS.z = 1.0 - positionTXS.z;
// TODO: Need to correctly define the shadow framework, WIP
#include "../SinglePass/SinglePass.hlsl"
// float3 shadowPosDX = ddx_fine(positionTXS);
// float3 shadowPosDY = ddy_fine(positionTXS);
return SAMPLE_TEXTURE2D_SHADOW(g_tShadowBuffer, samplerg_tShadowBuffer, positionTXS);
}
// Gets the cascade weights based on the world position of the fragment and the positions of the split spheres for each cascade.
// Returns an invalid split index if past shadowDistance (ie 4 is invalid for cascade)
uint GetSplitSphereIndexForDirshadows(float3 positionWS, float4 dirShadowSplitSpheres[4])
{
float3 fromCenter0 = positionWS.xyz - dirShadowSplitSpheres[0].xyz;
float3 fromCenter1 = positionWS.xyz - dirShadowSplitSpheres[1].xyz;
float3 fromCenter2 = positionWS.xyz - dirShadowSplitSpheres[2].xyz;
float3 fromCenter3 = positionWS.xyz - dirShadowSplitSpheres[3].xyz;
float4 distances2 = float4(dot(fromCenter0, fromCenter0), dot(fromCenter1, fromCenter1), dot(fromCenter2, fromCenter2), dot(fromCenter3, fromCenter3));
float4 dirShadowSplitSphereSqRadii;
dirShadowSplitSphereSqRadii.x = dirShadowSplitSpheres[0].w;
dirShadowSplitSphereSqRadii.y = dirShadowSplitSpheres[1].w;
dirShadowSplitSphereSqRadii.z = dirShadowSplitSpheres[2].w;
dirShadowSplitSphereSqRadii.w = dirShadowSplitSpheres[3].w;
float4 weights = float4(distances2 < dirShadowSplitSphereSqRadii);
weights.yzw = saturate(weights.yzw - weights.xyz);
return uint(4.0 - dot(weights, float4(4.0, 3.0, 2.0, 1.0)));
}
float GetDirectionalShadowAttenuation(LightLoopContext lightLoopContext, float3 positionWS, int index, float3 L, float2 unPositionSS)
{
// Note Index is 0 for now, but else we need to provide the correct index in _DirShadowSplitSpheres and _ShadowDatas
uint shadowSplitIndex = GetSplitSphereIndexForDirshadows(positionWS, _DirShadowSplitSpheres);
ShadowData shadowData = _ShadowDatas[shadowSplitIndex];
// Note: scale and bias of shadow atlas are included in ShadowTransform but could be apply here.
float4 positionTXS = mul(float4(positionWS, 1.0), shadowData.worldToShadow);
positionTXS.xyz /= positionTXS.w;
// positionTXS.z -= shadowData.bias; // Apply a linear bias
positionTXS.z -= 0.003;
#if UNITY_REVERSED_Z
positionTXS.z = 1.0 - positionTXS.z;
#endif
// float3 shadowPosDX = ddx_fine(positionTXS);
// float3 shadowPosDY = ddy_fine(positionTXS);
return SAMPLE_TEXTURE2D_SHADOW(g_tShadowBuffer, samplerg_tShadowBuffer, positionTXS);
}
//-----------------------------------------------------------------------------
// Cookie sampling functions
// ----------------------------------------------------------------------------
// Used by directional and spot lights.
// Returns the color in the RGB components, and the transparency (lack of occlusion) in A.
float4 SampleCookie2D(LightLoopContext lightLoopContext, float2 coord, int index)
{
return SAMPLE_TEXTURE2D_ARRAY_LOD(_CookieTextures, sampler_CookieTextures, coord, index, 0);
}
// Used by point lights.
// Returns the color in the RGB components, and the transparency (lack of occlusion) in A.
float4 SampleCookieCube(LightLoopContext lightLoopContext, float3 coord, int index)
{
return SAMPLE_TEXTURECUBE_ARRAY_LOD(_CookieCubeTextures, sampler_CookieCubeTextures, coord, index, 0);
}
//-----------------------------------------------------------------------------
// IES sampling function
// ----------------------------------------------------------------------------
// sphericalTexCoord is theta and phi spherical coordinate
float4 SampleIES(LightLoopContext lightLoopContext, int index, float2 sphericalTexCoord, float lod)
{
return SAMPLE_TEXTURE2D_ARRAY_LOD(_IESArray, sampler_IESArray, sphericalTexCoord, index, 0);
}
//-----------------------------------------------------------------------------
// Reflection proble / Sky sampling function
// ----------------------------------------------------------------------------
#define SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES 0
#define SINGLE_PASS_CONTEXT_SAMPLE_SKY 1
// Note: index is whatever the lighting architecture want, it can contain information like in which texture to sample (in case we have a compressed BC6H texture and an uncompressed for real time reflection ?)
// EnvIndex can also be use to fetch in another array of struct (to atlas information etc...).
float4 SampleEnv(LightLoopContext lightLoopContext, int index, float3 texCoord, float lod)
{
// This code will be inlined as lightLoopContext is hardcoded in the light loop
if (lightLoopContext.sampleReflection == SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES)
{
return SAMPLE_TEXTURECUBE_ARRAY_LOD(_EnvTextures, sampler_EnvTextures, texCoord, index, lod);
}
else // SINGLE_PASS_SAMPLE_SKY
{
return SAMPLE_TEXTURECUBE_LOD(_SkyTexture, sampler_SkyTexture, texCoord, lod);
}
}

149
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/TilePass/TilePassLoop.hlsl


// LightLoop
// ----------------------------------------------------------------------------
#ifdef LIGHTLOOP_TILE_PASS
// Calculate the offset in global light index light for current light category
int GetTileOffset(Coordinate coord, uint lightCategory)
{

{
float3 localDiffuseLighting, localSpecularLighting;
EvaluateBSDF_Directional( context, V, positionWS, prelightData, _DirectionalLightList[i], bsdfData,
EvaluateBSDF_Directional( context, V, positionWS, prelightData, _DirectionalLightDatas[i], bsdfData,
localDiffuseLighting, localSpecularLighting);
diffuseLighting += localDiffuseLighting;

#ifdef PROCESS_PUNCTUAL_LIGHT
// TODO: Convert the for loop below to a while on each type as we know we are sorted!
GetCountAndStart(coord, DIRECT_LIGHT, linearDepth, punctualLightStart, punctualLightCount);
GetCountAndStart(coord, LIGHTCATEGORY_PUNCTUAL, linearDepth, punctualLightStart, punctualLightCount);
EvaluateBSDF_Punctual( context, V, positionWS, prelightData, _PunctualLightList[FetchIndex(punctualLightStart, i)], bsdfData,
EvaluateBSDF_Punctual( context, V, positionWS, prelightData, _LightDatas[FetchIndex(punctualLightStart, i)], bsdfData,
localDiffuseLighting, localSpecularLighting);
diffuseLighting += localDiffuseLighting;

#ifdef PROCESS_AREA_LIGHT
/*
// TODO: Area lights are where the sorting is important (Morten approach with while loop)
// TODO: Convert the for loop below to a while on each type as we know we are sorted!
GetCountAndStart(coord, LightCatergory.AreaLight, linearDepth, areaLightStart, areaLightCount);
GetCountAndStart(coord, LIGHTCATEGORY_AREA, linearDepth, areaLightStart, areaLightCount);
EvaluateBSDF_Area( context, V, positionWS, prelightData, _AreaLightList[FetchIndex(areaLightStart, i)], bsdfData,
localDiffuseLighting, localSpecularLighting);
uint areaIndex = FetchIndex(areaLightStart, i);
if(_LightDatas[areaIndex].lightType == GPULIGHTTYPE_LINE)
{
EvaluateBSDF_Line( context, V, positionWS, prelightData, _LightDatas[areaIndex], bsdfData,
localDiffuseLighting, localSpecularLighting);
}
else
{
EvaluateBSDF_Area( context, V, positionWS, prelightData, _LightDatas[areaIndex], bsdfData,
localDiffuseLighting, localSpecularLighting);
}
*/
uint envLightStart;
uint envLightCount;
GetCountAndStart(coord, REFLECTION_LIGHT, linearDepth, envLightStart, envLightCount);
// Only apply sky IBL if the sky texture is available.
if (_EnvLightSkyEnabled)
{
float3 localDiffuseLighting, localSpecularLighting;
float2 weight;
// The sky is a single cubemap texture separate from the reflection probe texture array (different resolution and compression)
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_SKY;
EnvLightData envLightSky = InitSkyEnvLightData(0); // The sky data are generated on the fly so the compiler can optimize the code
EvaluateBSDF_Env(context, V, positionWS, prelightData, envLightSky, bsdfData, localDiffuseLighting, localSpecularLighting, weight);
iblDiffuseLighting = lerp(iblDiffuseLighting, localDiffuseLighting, weight.x); // Should be remove by the compiler if it is smart as all is constant 0
iblSpecularLighting = lerp(iblSpecularLighting, localSpecularLighting, weight.y);
}
uint envLightStart;
uint envLightCount;
GetCountAndStart(coord, LIGHTCATEGORY_ENV, linearDepth, envLightStart, envLightCount);
EvaluateBSDF_Env(context, V, positionWS, prelightData, _EnvLightList[FetchIndex(envLightStart, i)], bsdfData, localDiffuseLighting, localSpecularLighting, weight);
EvaluateBSDF_Env(context, V, positionWS, prelightData, _EnvLightDatas[FetchIndex(envLightStart, i)], bsdfData, localDiffuseLighting, localSpecularLighting, weight);
iblDiffuseLighting = lerp(iblDiffuseLighting, localDiffuseLighting, weight.x); // Should be remove by the compiler if it is smart as all is constant 0
iblSpecularLighting = lerp(iblSpecularLighting, localSpecularLighting, weight.y);
}

#endif
// Currently do lightmap with indirect specula
// TODO: test what is the most appropriate here...
// TODO: currently apply GI at the same time as reflection
#else // LIGHTLOOP_SINGLE_PASS
// bakeDiffuseLighting is part of the prototype so a user is able to implement a "base pass" with GI and multipass direct light (aka old unity rendering path)
void LightLoop( float3 V, float3 positionWS, Coordinate coord, PreLightData prelightData, BSDFData bsdfData, float3 bakeDiffuseLighting,
out float3 diffuseLighting,
out float3 specularLighting)
{
LightLoopContext context;
ZERO_INITIALIZE(LightLoopContext, context);
diffuseLighting = float3(0.0, 0.0, 0.0);
specularLighting = float3(0.0, 0.0, 0.0);
uint i = 0; // Declare once to avoid the D3D11 compiler warning.
for (i = 0; i < _DirectionalLightCount; ++i)
{
float3 localDiffuseLighting, localSpecularLighting;
EvaluateBSDF_Directional( context, V, positionWS, prelightData, _DirectionalLightDatas[i], bsdfData,
localDiffuseLighting, localSpecularLighting);
diffuseLighting += localDiffuseLighting;
specularLighting += localSpecularLighting;
}
for (i = 0; i < _PunctualLightCount; ++i)
{
float3 localDiffuseLighting, localSpecularLighting;
EvaluateBSDF_Punctual( context, V, positionWS, prelightData, _LightDatas[i], bsdfData,
localDiffuseLighting, localSpecularLighting);
diffuseLighting += localDiffuseLighting;
specularLighting += localSpecularLighting;
}
// Area are store with punctual, just offset the index
for (i = _PunctualLightCount; i < _AreaLightCount + _PunctualLightCount; ++i)
{
float3 localDiffuseLighting, localSpecularLighting;
if (_LightDatas[i].lightType == GPULIGHTTYPE_LINE)
{
EvaluateBSDF_Line( context, V, positionWS, prelightData, _LightDatas[i], bsdfData,
localDiffuseLighting, localSpecularLighting);
}
else
{
EvaluateBSDF_Area( context, V, positionWS, prelightData, _LightDatas[i], bsdfData,
localDiffuseLighting, localSpecularLighting);
}
diffuseLighting += localDiffuseLighting;
specularLighting += localSpecularLighting;
}
// TODO: Check the reflection hierarchy, for the current system (matching legacy unity) we must sort from bigger solid angle to lower (lower override bigger). So begging by sky
// TODO: Change the way it is done by reversing the order, from smaller solid angle to bigger, so we can early out when the weight is 1.
float3 iblDiffuseLighting = float3(0.0, 0.0, 0.0);
float3 iblSpecularLighting = float3(0.0, 0.0, 0.0);
// Only apply sky IBL if the sky texture is available.
if (_EnvLightSkyEnabled)
{
float3 localDiffuseLighting, localSpecularLighting;
float2 weight;
// The sky is a single cubemap texture separate from the reflection probe texture array (different resolution and compression)
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_SKY;
EnvLightData envLightSky = InitSkyEnvLightData(0); // The sky data are generated on the fly so the compiler can optimize the code
EvaluateBSDF_Env(context, V, positionWS, prelightData, envLightSky, bsdfData, localDiffuseLighting, localSpecularLighting, weight);
iblDiffuseLighting = lerp(iblDiffuseLighting, localDiffuseLighting, weight.x); // Should be remove by the compiler if it is smart as all is constant 0
iblSpecularLighting = lerp(iblSpecularLighting, localSpecularLighting, weight.y);
}
for (i = 0; i < _EnvLightCount; ++i)
{
float3 localDiffuseLighting, localSpecularLighting;
float2 weight;
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES;
EvaluateBSDF_Env(context, V, positionWS, prelightData, _EnvLightDatas[i], bsdfData, localDiffuseLighting, localSpecularLighting, weight);
iblDiffuseLighting = lerp(iblDiffuseLighting, localDiffuseLighting, weight.x); // Should be remove by the compiler if it is smart as all is constant 0
iblSpecularLighting = lerp(iblSpecularLighting, localSpecularLighting, weight.y);
}
diffuseLighting += iblDiffuseLighting;
specularLighting += iblSpecularLighting;
// Add indirect diffuse + emissive (if any)
diffuseLighting += bakeDiffuseLighting;
}
#endif

2
Assets/ScriptableRenderLoop/HDRenderLoop/Material/LayeredLit/Editor/LayeredLitUI.cs


public readonly GUIContent layerMapMaskText = new GUIContent("Layer Mask", "Layer mask (multiplied by vertex color if enabled)");
public readonly GUIContent layerMapVertexColorText = new GUIContent("Use Vertex Color", "Layer mask (multiplied by layer mask if enabled)");
public readonly GUIContent layerCountText = new GUIContent("Layer Count", "Number of layers.");
public readonly GUIContent layerTexWorldScaleText = new GUIContent("Tex world scale", "Scale to apply to world position for Planar/Trilinear");
public readonly GUIContent layerTexWorldScaleText = new GUIContent("Tiling", "Tiling factor applied to Planar/Trilinear mapping");
public readonly GUIContent UVBaseText = new GUIContent("Base UV Mapping", "Base UV Mapping mode of the layer.");
public readonly GUIContent UVDetailText = new GUIContent("Detail UV Mapping", "Detail UV Mapping mode of the layer.");
}

12
Assets/ScriptableRenderLoop/HDRenderLoop/Material/LayeredLit/LayeredLit.shader


// All the following properties that concern the UV mapping are the same as in the Lit shader.
// This means that they will get overridden when synchronizing the various layers.
// To avoid this, make sure that all properties here are in the exclusion list in LayeredLitUI.SynchronizeLayerProperties
_TexWorldScale0("Scale to apply on world coordinate", Float) = 1.0
_TexWorldScale1("Scale to apply on world coordinate", Float) = 1.0
_TexWorldScale2("Scale to apply on world coordinate", Float) = 1.0
_TexWorldScale3("Scale to apply on world coordinate", Float) = 1.0
_TexWorldScale0("Tiling", Float) = 1.0
_TexWorldScale1("Tiling", Float) = 1.0
_TexWorldScale2("Tiling", Float) = 1.0
_TexWorldScale3("Tiling", Float) = 1.0
[Enum(UV0, 0, UV1, 1, UV3, 2, Planar, 3, Triplanar, 4)] _UVBase0("UV Set for base0", Float) = 0
[Enum(UV0, 0, UV1, 1, UV3, 2, Planar, 3, Triplanar, 4)] _UVBase1("UV Set for base1", Float) = 0

// Unused but to be able to share litUI.Sahder and layeredUI.Shader
[HideInInspector] _UVBase("UV Set for base", Float) = 0
[HideInInspector] _UVDetail("UV Set for base", Float) = 0
[HideInInspector] _TexWorldScale("Scale to apply on world coordinate", Float) = 1.0
[HideInInspector] _TexWorldScale("Tiling", Float) = 1.0
[HideInInspector] _UVMappingMask("_UVMappingMask", Color) = (1, 0, 0, 0)
[HideInInspector] _UVDetailsMappingMask("_UVDetailsMappingMask", Color) = (1, 0, 0, 0)
}

#define SHADERPASS SHADERPASS_FORWARD
// TEMP until pragma work in include
// #include "../../Lighting/Forward.hlsl"
#pragma multi_compile LIGHTLOOP_SINGLE_PASS
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
#define LAYERED_LIT_SHADER
//#pragma multi_compile SHADOWFILTERING_FIXED_SIZE_PCF

2
Assets/ScriptableRenderLoop/HDRenderLoop/Material/Lit/Editor/BaseLitUI.cs


public static GUIContent smoothnessMapChannelText = new GUIContent("Smoothness Source", "Smoothness texture and channel");
public static GUIContent UVBaseMappingText = new GUIContent("UV set for Base", "");
public static GUIContent texWorldScaleText = new GUIContent("Scale to apply on world coordinate in case of Planar/Triplanar", "");
public static GUIContent texWorldScaleText = new GUIContent("Tiling", "Tiling factor applied to Planar/Trilinear mapping");
public static GUIContent UVBaseDetailMappingText = new GUIContent("UV set for Base and Detail", "");
public static GUIContent normalMapSpaceText = new GUIContent("Normal/Tangent Map space", "");
public static GUIContent heightMapModeText = new GUIContent("Height Map Mode", "");

6
Assets/ScriptableRenderLoop/HDRenderLoop/Material/Lit/Lit.hlsl


// TODO: I haven't configure this sampler in the code, we should be able to do it (but Unity don't allow it for now...)
// By default Unity provide MIG_MAG_LINEAR_POINT sampler, so it fit with our need.
#ifdef LIT_DISPLAY_REFERENCE_IBL
// TODO: to avoid the message Fragment program 'Frag' : sampler 'sampler_PreIntegratedFGD' has no matching texture and will be undefined.
// We need to test this define LIGHTLOOP_TILE_DIRECT, this is a bad workaround but no alternative until we can setup sampler correctly...
#if defined(LIT_DISPLAY_REFERENCE_IBL) || defined(LIGHTLOOP_TILE_DIRECT)
// When reference mode is enabled, then we need to chose another sampler not related to cubemap code...
SAMPLER2D(sampler_LtcGGXMatrix);
#define SRL_BilinearSampler sampler_LtcGGXMatrix // Used for all textures

out float3 diffuseLighting,
out float3 specularLighting)
{
float3 L = lightData.direction;
float3 L = -lightData.forward; // Lights are pointing backward in Unity
float illuminance = saturate(dot(bsdfData.normalWS, L));
diffuseLighting = float3(0.0, 0.0, 0.0);

7
Assets/ScriptableRenderLoop/HDRenderLoop/Material/Lit/Lit.shader


_NormalMap("NormalMap", 2D) = "bump" {}
_HeightMap("HeightMap", 2D) = "black" {}
_HeightScale("Height Scale", Float) = 1
_HeightScale("Height Scale", Float) = 0.01
_HeightBias("Height Bias", Float) = 0
_TangentMap("TangentMap", 2D) = "bump" {}

_DetailMask("DetailMask", 2D) = "white" {}
_DetailAlbedoScale("_DetailAlbedoScale", Range(-2.0, 2.0)) = 1
_DetailNormalScale("_DetailNormalScale", Range(0.0, 2.0)) = 1
_DetailSmoothnessScale("_DetailSmoothnessScale", Range(-2.0, 2.0)) = 1
_DetailSmoothnessScale("_DetailSmoothnessScale", Range(-2.0, 2.0)) = 0.01
_DetailHeightScale("_DetailHeightScale", Range(-2.0, 2.0)) = 1
_DetailAOScale("_DetailAOScale", Range(-2.0, 2.0)) = 1

#define SHADERPASS SHADERPASS_FORWARD
// TEMP until pragma work in include
// #include "../../Lighting/Forward.hlsl"
// LIGHTLOOP_TILE_PASS
#pragma multi_compile LIGHTLOOP_SINGLE_PASS
#pragma multi_compile LIGHTLOOP_SINGLE_PASS LIGHTLOOP_TILE_PASS
//#pragma multi_compile SHADOWFILTERING_FIXED_SIZE_PCF
#include "../../Lighting/Lighting.hlsl"

23
Assets/ScriptableRenderLoop/HDRenderLoop/Material/Lit/LitSurfaceData.hlsl


ADD_IDX(layerTexCoord.base).uv = ADD_IDX(_UVMappingMask).x * input.texCoord0 +
ADD_IDX(_UVMappingMask).y * input.texCoord1 +
ADD_IDX(_UVMappingMask).z * input.texCoord3 +
ADD_IDX(_UVMappingMask).w * position.xz;
ADD_IDX(_UVMappingMask).w * -position.xz;
ADD_IDX(_UVMappingMask).w * position.xz;
ADD_IDX(_UVMappingMask).w * -position.xz;
ADD_IDX(layerTexCoord.details).uv = TRANSFORM_TEX(uvDetails, ADD_IDX(_DetailMap));

ADD_IDX(layerTexCoord.base).uvYZ = position.zy;
ADD_IDX(layerTexCoord.base).uvZX = position.xz;
ADD_IDX(layerTexCoord.base).uvXY = float2(-position.x, position.y);
float3 direction = sign(input.tangentToWorld[2].xyz);
// In triplanar, if we are facing away from the world axis, a different axis will be flipped for each direction.
// This is particularly problematic for tangent space normal maps which need to be in the right direction.
// So we multiplying the offending coordinate by the sign of the normal.
ADD_IDX(layerTexCoord.base).uvYZ = float2(direction.x * position.z, position.y);
ADD_IDX(layerTexCoord.base).uvZX = -float2(position.x, direction.y * position.z);
ADD_IDX(layerTexCoord.base).uvXY = float2(-position.x, direction.z * position.y);
ADD_IDX(layerTexCoord.details).uvYZ = TRANSFORM_TEX(position.zy, ADD_IDX(_DetailMap));
ADD_IDX(layerTexCoord.details).uvZX = TRANSFORM_TEX(position.xz, ADD_IDX(_DetailMap));
ADD_IDX(layerTexCoord.details).uvXY = TRANSFORM_TEX(float2(-position.x, position.y), ADD_IDX(_DetailMap));
ADD_IDX(layerTexCoord.details).uvYZ = TRANSFORM_TEX(ADD_IDX(layerTexCoord.base).uvYZ, ADD_IDX(_DetailMap));
ADD_IDX(layerTexCoord.details).uvZX = TRANSFORM_TEX(ADD_IDX(layerTexCoord.base).uvZX, ADD_IDX(_DetailMap));
ADD_IDX(layerTexCoord.details).uvXY = TRANSFORM_TEX(ADD_IDX(layerTexCoord.base).uvXY, ADD_IDX(_DetailMap));
}
void ADD_IDX(ApplyDisplacement)(inout FragInput input, inout LayerTexCoord layerTexCoord)

#else
surfaceData.perceptualSmoothness = 1.0;
#endif
surfaceData.perceptualSmoothness = ADD_IDX(_Smoothness);
surfaceData.perceptualSmoothness *= ADD_IDX(_Smoothness);
#ifdef _DETAIL_MAP
surfaceData.perceptualSmoothness *= LerpWhiteTo(2.0 * saturate(detailSmoothness * ADD_IDX(_DetailSmoothnessScale)), detailMask);
#endif

2
Assets/ScriptableRenderLoop/RenderPasses/ShadowRenderPass.cs


if (!cullResults.GetShadowCasterBounds(lightIndex, out bounds))
{
Profiler.EndSample();
return;
continue;
}
Profiler.EndSample();

12
Assets/ScriptableRenderLoop/common/ShaderBase.h


float FetchDepth(Texture2D depthTexture, uint2 pixCoord)
{
return 1 - depthTexture.Load(uint3(pixCoord.xy, 0)).x;
float zdpth = depthTexture.Load(uint3(pixCoord.xy, 0)).x;
#if !defined(SHADER_API_GLES3) && !defined(SHADER_API_GLCORE)
zdpth = 1.0 - zdpth;
#endif
return zdpth;
return 1 - depthTexture.Load(uint3(pixCoord.xy, 0), sampleIdx).x;
float zdpth = depthTexture.Load(uint3(pixCoord.xy, 0), sampleIdx).x;
#if !defined(SHADER_API_GLES3) && !defined(SHADER_API_GLCORE)
zdpth = 1.0 - zdpth;
#endif
return zdpth;
}
#endif

2
Assets/ScriptableRenderLoop/common/TextureSettings.cs


namespace UnityEngine.Experimental.ScriptableRenderLoop
{
[System.Serializable]
public struct TextureSettings
public class TextureSettings
{
public int spotCookieSize;
public int pointCookieSize;

6
Assets/ScriptableRenderLoop/fptl/FptlLighting.cs


// render opaque objects using Deferred pass
var settings = new DrawRendererSettings(cull, camera, new ShaderPassName("Deferred"))
{
sorting = {sortOptions = SortOptions.SortByMaterialThenMesh},
sorting = { flags = SortFlags.CommonOpaque },
rendererConfiguration = RendererConfiguration.PerObjectLightmaps
};

// render opaque objects using Deferred pass
var settings = new DrawRendererSettings(cull, camera, new ShaderPassName("ForwardSinglePass"))
{
sorting = { sortOptions = SortOptions.SortByMaterialThenMesh }
sorting = { flags = SortFlags.CommonOpaque }
};
settings.rendererConfiguration = RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe;
if (opaquesOnly) settings.inputFilter.SetQueuesOpaque();

// render opaque objects using Deferred pass
var settings = new DrawRendererSettings(cull, camera, new ShaderPassName("DepthOnly"))
{
sorting = { sortOptions = SortOptions.SortByMaterialThenMesh }
sorting = { flags = SortFlags.CommonOpaque }
};
settings.inputFilter.SetQueuesOpaque();
loop.DrawRenderers(ref settings);

24
Assets/ScriptableRenderLoop/fptl/LightingTemplate.hlsl


StructuredBuffer<DirectionalLight> g_dirLightData;
#define VALVE_DECLARE_SHADOWMAP( tex ) Texture2D tex; SamplerComparisonState sampler##tex
#define VALVE_SAMPLE_SHADOW( tex, coord ) tex.SampleCmpLevelZero( sampler##tex, (coord).xy, (coord).z )
#define DECLARE_SHADOWMAP( tex ) Texture2D tex; SamplerComparisonState sampler##tex
#define SAMPLE_SHADOW( tex, coord ) tex.SampleCmpLevelZero( sampler##tex, (coord).xy, (coord).z )
VALVE_DECLARE_SHADOWMAP(g_tShadowBuffer);
DECLARE_SHADOWMAP(g_tShadowBuffer);
float ComputeShadow_PCF_3x3_Gaussian(float3 vPositionWs, float4x4 matWorldToShadow)
{

float objDepth = saturate(257.0 / 256.0 - vPositionTextureSpace.z);
float4 v20Taps;
v20Taps.x = VALVE_SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms1.xy, objDepth)).x; // 1 1
v20Taps.y = VALVE_SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms1.zy, objDepth)).x; // -1 1
v20Taps.z = VALVE_SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms1.xw, objDepth)).x; // 1 -1
v20Taps.w = VALVE_SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms1.zw, objDepth)).x; // -1 -1
v20Taps.x = SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms1.xy, objDepth)).x; // 1 1
v20Taps.y = SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms1.zy, objDepth)).x; // -1 1
v20Taps.z = SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms1.xw, objDepth)).x; // 1 -1
v20Taps.w = SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms1.zw, objDepth)).x; // -1 -1
float flSum = dot(v20Taps.xyzw, float4(0.25, 0.25, 0.25, 0.25));
if ((flSum == 0.0) || (flSum == 1.0))
return flSum;

v33Taps.x = VALVE_SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms2.xz, objDepth)).x; // 1 0
v33Taps.y = VALVE_SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms3.xz, objDepth)).x; // -1 0
v33Taps.z = VALVE_SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms3.zy, objDepth)).x; // 0 -1
v33Taps.w = VALVE_SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms2.zy, objDepth)).x; // 0 1
v33Taps.x = SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms2.xz, objDepth)).x; // 1 0
v33Taps.y = SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms3.xz, objDepth)).x; // -1 0
v33Taps.z = SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms3.zy, objDepth)).x; // 0 -1
v33Taps.w = SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy + g_vShadow3x3PCFTerms2.zy, objDepth)).x; // 0 1
flSum += VALVE_SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy, objDepth)).x * g_vShadow3x3PCFTerms0.z;
flSum += SAMPLE_SHADOW(g_tShadowBuffer, float3(shadowMapCenter.xy, objDepth)).x * g_vShadow3x3PCFTerms0.z;
return flSum;
}

2
Assets/ScriptableRenderLoop/fptl/StandardTest.shader


#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED DIRLIGHTMAP_SEPARATE
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile_fog
#pragma multi_compile TILED_FORWARD REGULAR_FORWARD
#pragma vertex vertForward
#pragma fragment fragForward

#pragma multi_compile DIRLIGHTMAP_OFF DIRLIGHTMAP_COMBINED DIRLIGHTMAP_SEPARATE
#pragma multi_compile DYNAMICLIGHTMAP_OFF DYNAMICLIGHTMAP_ON
#pragma multi_compile_fog
#pragma multi_compile TILED_FORWARD REGULAR_FORWARD
#pragma vertex vertForward
#pragma fragment fragNoLight

2
Assets/ScriptableRenderLoop/fptl/lightlistbuild-bigtile.compute


int offs = tileIDX.y*nrBigTilesX + tileIDX.x;
for(int i=t; i<(iNrCoarseLights+1); i+=NR_THREADS)
g_vLightList[MAX_NR_BIGTILE_LIGHTS_PLUSONE*offs + i] = t==0 ? iNrCoarseLights : lightsListLDS[i-1];
g_vLightList[MAX_NR_BIGTILE_LIGHTS_PLUSONE*offs + i] = i==0 ? iNrCoarseLights : lightsListLDS[i-1];
}

2
Assets/ScriptableRenderLoop/fptl/lightlistbuild.compute


for(int l=threadID; l<iNrCoarseLights; l+=NR_THREADS)
{
SFiniteLightBound lightData = g_data[coarseList[l]];
SFiniteLightBound lightData = g_data[prunedList[l]];
if( DoesSphereOverlapTile(V, halfTileSizeAtZDistOne, lightData.center.xyz, lightData.radius) )
{

26
Assets/TestScenes/HDTest/GlobalIlluminationTest.unity


m_ReflectionIntensity: 1
m_CustomReflection: {fileID: 0}
m_Sun: {fileID: 0}
m_IndirectSpecularColor: {r: 0.5456174, g: 0.39782104, b: 0.24038851, a: 1}
m_IndirectSpecularColor: {r: 0.6238628, g: 0.56322443, b: 0.5425187, a: 1}
--- !u!157 &3
LightmapSettings:
m_ObjectHideFlags: 0

m_Component:
- component: {fileID: 565152815}
- component: {fileID: 565152816}
- component: {fileID: 565152817}
m_Layer: 0
m_Name: Spotlight
m_TagString: Untagged

m_BounceIntensity: 1
m_ShadowRadius: 0
m_ShadowAngle: 0
--- !u!114 &565152817
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 565152814}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 7a68c43fe1f2a47cfa234b5eeaa98012, type: 3}
m_Name:
m_EditorClassIdentifier:
shadowResolution: 512
shadowDimmer: 1
affectDiffuse: 1
affectSpecular: 1
archetype: 0
isDoubleSided: 0
areaLightLength: 0
areaLightWidth: 0
--- !u!1 &841702834
GameObject:
m_ObjectHideFlags: 0

shadowDimmer: 1
affectDiffuse: 1
affectSpecular: 1
treatAsAreaLight: 0
archetype: 0
isDoubleSided: 0
areaLightLength: 0
areaLightWidth: 0

m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 1543726725}
m_LocalRotation: {x: -0, y: -0, z: -0, w: 1}
m_LocalPosition: {x: -6.33, y: 0.428, z: -5.0499997}
m_LocalPosition: {x: -6.33, y: 0.428, z: -4.84}
m_LocalScale: {x: 1.6119599, y: 1.6119599, z: 1.6119599}
m_Children: []
m_Father: {fileID: 1027688891}

2
Assets/BasicRenderLoopTutorial/BasicRenderLoop.asset


m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 22228a1bd982b864ea6c84db2fc11dd1, type: 3}
m_Name: basicrenderloop
m_Name: BasicRenderLoop
m_EditorClassIdentifier:

8
Assets/BasicRenderLoopTutorial/BasicRenderLoop.asset.meta


fileFormatVersion: 2
guid: b03c9b2b48c84914e93527b52d6044cb
timeCreated: 1481014594
licenseType: Pro
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

34
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/LightLoop.cs


using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering;
using System;
namespace UnityEngine.Experimental.ScriptableRenderLoop
{
public class BaseLightLoop
{
// TODO: We should rather put the texture settings in LightLoop, but how do we serialize it ?
public virtual void Rebuild(TextureSettings textureSettings) {}
public virtual void Cleanup() {}
public virtual bool NeedResize() { return false; }
public virtual void AllocResolutionDependentBuffers(int width, int height) { }
public virtual void ReleaseResolutionDependentBuffers() {}
public virtual void NewFrame() {}
public virtual void PrepareLightsForGPU(CullResults cullResults, Camera camera, ref ShadowOutput shadowOutput) { }
// TODO: this should not be aprt of the interface but for now make something working
public virtual void BuildGPULightLists(Camera camera, RenderLoop loop, RenderTargetIdentifier cameraDepthBufferRT) { }
public virtual void PushGlobalParams(Camera camera, RenderLoop loop) {}
public virtual void RenderDeferredLighting(Camera camera, RenderLoop renderLoop, RenderTargetIdentifier cameraColorBufferRT) {}
public virtual void RenderForward(Camera camera, RenderLoop renderLoop, bool renderOpaque) {}
}
}

12
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/LightLoop.cs.meta


fileFormatVersion: 2
guid: 1669ef5a164969c4c90cd3509b01123d
timeCreated: 1481066258
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

9
Assets/ScriptableRenderLoop/HDRenderLoop/Lighting/SinglePass.meta


fileFormatVersion: 2
guid: dfb6e7f2aee22e147834de3e01b7c03c
folderAsset: yes
timeCreated: 1477266406
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

8
Assets/basicrenderloop.asset.meta


fileFormatVersion: 2
guid: f77fc78803cb35147ab3c0811feb562d
timeCreated: 1480085360
licenseType: Pro
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

/Assets/basicrenderloop.asset → /Assets/BasicRenderLoopTutorial/BasicRenderLoop.asset

正在加载...
取消
保存