diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Serialization.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Serialization.cs
index a83ed59c3ef..0c80beb3645 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Serialization.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Serialization.cs
@@ -683,6 +683,8 @@ static void ExtractBakingCells()
foreach (var data in loadedSceneDataList)
{
var cells = m_BakingSet.GetSceneCellIndexList(data.sceneGUID);
+ if (cells == null)
+ continue;
var numberOfCells = cells.Count;
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileEditor.cs b/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileEditor.cs
index ff76aa7d16f..222f9baffe6 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileEditor.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeProfileEditor.cs
@@ -18,21 +18,6 @@ public sealed class VolumeProfileEditor : Editor
void OnEnable()
{
componentList = new VolumeComponentListEditor(this);
- if (VolumeManager.instance.isInitialized)
- Init();
- }
-
- void Init()
- {
- var volumeProfile = target as VolumeProfile;
-
- if (volumeProfile == VolumeManager.instance.globalDefaultProfile)
- {
- componentList.SetIsGlobalDefaultVolumeProfile(true);
- VolumeProfileUtils.EnsureAllOverridesForDefaultProfile(volumeProfile);
- }
-
- componentList.Init(volumeProfile, serializedObject);
}
void OnDisable()
@@ -43,15 +28,32 @@ void OnDisable()
///
public override void OnInspectorGUI()
{
- if (componentList == null || componentList.asset == null)
+ if (!VolumeManager.instance.isInitialized)
+ {
+ EditorGUILayout.HelpBox("Volume Profiles require an active Scriptable Render Pipeline, but nothing has been rendered. Make sure Scene or Game View is in focus and no debug modes are active.", MessageType.Warning);
+ return; // Defer initialization until VolumeManager is initialized
+ }
+
+ if (componentList == null)
+ componentList = new VolumeComponentListEditor(this);
+
+ var volumeProfile = target as VolumeProfile;
+
+ bool isDefaultVolumeProfile = volumeProfile == VolumeManager.instance.globalDefaultProfile;
+
+
+ bool initNeeded = componentList.asset == null ||
+ (isDefaultVolumeProfile && (componentList.asset.components == null || componentList.asset.components.Count == 0));
+
+ if (initNeeded)
{
- if (!VolumeManager.instance.isInitialized)
+ if (isDefaultVolumeProfile)
{
- EditorGUILayout.HelpBox("Volume Profiles require an active Scriptable Render Pipeline, but nothing has been rendered. Make sure Scene or Game View is in focus and no debug modes are active.", MessageType.Warning);
- return; // Defer initialization until VolumeManager is initialized
+ componentList.SetIsGlobalDefaultVolumeProfile(true);
+ VolumeProfileUtils.EnsureAllOverridesForDefaultProfile(volumeProfile);
}
- Init();
+ componentList.Init(volumeProfile, serializedObject);
}
serializedObject.Update();
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs
index cec9d44ee3e..da3a6bfa523 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUI.Fields.cs
@@ -289,8 +289,8 @@ public class IntField : Field
/// Validated value.
public override int ValidateValue(int value)
{
- if (min != null) value = Mathf.Max(value, min());
- if (max != null) value = Mathf.Min(value, max());
+ if (min != null) value = Math.Max(value, min());
+ if (max != null) value = Math.Min(value, max());
return value;
}
@@ -386,8 +386,8 @@ public class UIntField : Field
/// Validated value.
public override uint ValidateValue(uint value)
{
- if (min != null) value = (uint)Mathf.Max(value, min());
- if (max != null) value = (uint)Mathf.Min(value, max());
+ if (min != null) value = Math.Max(value, min());
+ if (max != null) value = Math.Min(value, max());
return value;
}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.cs
index 1744612318a..b72c3b29c42 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.cs
@@ -987,7 +987,19 @@ internal void RegisterBakingSet(ProbeVolumePerSceneData data)
internal void UnloadBakingSet()
{
// Need to make sure everything is unloaded before killing the baking set ref (we need it to unload cell CPU data).
+#if UNITY_EDITOR
+ m_IsUnloadingBakingSet = true;
+ try
+ {
+ PerformPendingOperations();
+ }
+ finally
+ {
+ m_IsUnloadingBakingSet = false;
+ }
+#else
PerformPendingOperations();
+#endif
if (m_CurrentBakingSet != null)
m_CurrentBakingSet.Cleanup();
@@ -1643,13 +1655,14 @@ public void PerformPendingOperations()
#if UNITY_EDITOR
Scene m_TrackedActiveScene;
+ bool m_IsUnloadingBakingSet;
// Keeps the current baking set in sync with the active scene. Skipped while a bake is running, since the
// current set is owned by EnsureCurrentBakingSet for its duration; the mismatch is picked up again once the
// bake ends, on whichever call to PerformPendingOperations comes first.
internal void TrackActiveScene()
{
- if (Application.isPlaying || UnityEditor.Lightmapping.isRunning || isBakingAdaptiveProbeVolumes)
+ if (m_IsUnloadingBakingSet || Application.isPlaying || UnityEditor.Lightmapping.isRunning || isBakingAdaptiveProbeVolumes)
return;
var activeScene = SceneManager.GetActiveScene();
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs
index 20ac14a1d9f..6d44d3d1878 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs
@@ -618,8 +618,10 @@ internal void EnsurePerSceneData(Scene scene, string sceneGUID)
{
GameObject go = new GameObject("ProbeVolumePerSceneData");
go.hideFlags |= HideFlags.HideInHierarchy;
- var perSceneData = go.AddComponent();
+
+ // Move before adding the component so OnEnable picks up the GUID of the target scene
SceneManager.MoveGameObjectToScene(go, scene);
+ go.AddComponent();
}
}
}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeScratchBufferPool.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeScratchBufferPool.cs
index 8782e495dd6..884bea0eec2 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeScratchBufferPool.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeScratchBufferPool.cs
@@ -70,7 +70,7 @@ public ProbeVolumeScratchBufferPool(ProbeVolumeBakingSet bakingSet, ProbeVolumeS
m_ValidityLayerCount = bakingSet.bakedMaskCount;
m_SkyOcclusionSize = bakingSet.sharedSkyOcclusionL0L1ChunkSize;
m_SkyShadingDirectionSize = bakingSet.sharedSkyShadingDirectionIndicesChunkSize;
- m_L2Size = bakingSet.L2TextureChunkSize;
+ m_L2Size = shBands == ProbeVolumeSHBands.SphericalHarmonicsL2 ? bakingSet.L2TextureChunkSize : 0;
m_ProbeOcclusionSize = bakingSet.ProbeOcclusionChunkSize;
}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/HandleSet.cs b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/HandleSet.cs
index 8e63249f99f..5c335a26064 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/HandleSet.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/HandleSet.cs
@@ -5,7 +5,7 @@
namespace UnityEngine.PathTracing.Core
{
// The type parameter T is only used as a tag, preventing different kinds of handles from being mixed together.
- internal readonly struct Handle
+ internal readonly struct Handle : IEquatable>
{
public readonly UInt64 Value;
@@ -27,6 +27,7 @@ internal int ToInt()
}
// Value type semantics
+ public bool Equals(Handle other) => other.Value == Value;
public override int GetHashCode() => Value.GetHashCode();
public override bool Equals(object obj) => obj is Handle other && other.Value == Value;
public override string ToString() => $"Handle<{typeof(T).Name}>({Value})";
@@ -50,7 +51,7 @@ public Handle Add()
public void Remove(Handle handle)
{
- Debug.Assert(!_freeHandles.Contains(handle));
+ Debug.Assert(handle.Value < _nextHandleIndex, "Removed handle was never allocated by this set.");
_freeHandles.Push(handle);
}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/ProbeOcclusionLightIndexMapping.compute b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/ProbeOcclusionLightIndexMapping.compute
index 6ff80b1f591..bb7983dd6db 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/ProbeOcclusionLightIndexMapping.compute
+++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/ProbeOcclusionLightIndexMapping.compute
@@ -12,7 +12,7 @@ uint g_ProbeCount;
[numthreads(64,1,1)]
void MapIndices(uint3 id : SV_DispatchThreadID)
{
- if (id.x >= g_MaxLightsPerProbe * g_ProbeCount)
+ if (id.x >= g_ProbeCount)
return;
for (uint i = 0; i < g_MaxLightsPerProbe; i++)
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/Utilities/BlockAllocator.cs b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/Utilities/BlockAllocator.cs
index d18097f3b94..8d9b6001cf1 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/Utilities/BlockAllocator.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/Utilities/BlockAllocator.cs
@@ -29,6 +29,8 @@ public struct Allocation
private NativeList m_freeBlocks;
private NativeList m_usedBlocks;
private NativeList m_freeSlots;
+ private NativeHashMap m_freeBlockStarts;
+ private NativeHashMap m_freeBlockEnds;
public int freeElementsCount => m_FreeElementCount;
public int freeBlocks => m_freeBlocks.Length;
@@ -44,7 +46,19 @@ public void Initialize(int maxElementCounts)
m_freeBlocks = new NativeList(Allocator.Persistent);
else
m_freeBlocks.Clear();
- m_freeBlocks.Add(new Block() { offset = 0, count = m_FreeElementCount });
+
+ if (!m_freeBlockStarts.IsCreated)
+ m_freeBlockStarts = new NativeHashMap(64, Allocator.Persistent);
+ else
+ m_freeBlockStarts.Clear();
+
+ if (!m_freeBlockEnds.IsCreated)
+ m_freeBlockEnds = new NativeHashMap(64, Allocator.Persistent);
+ else
+ m_freeBlockEnds.Clear();
+
+ if (m_FreeElementCount > 0)
+ AddFreeBlockEntry(new Block() { offset = 0, count = m_FreeElementCount });
if (!m_usedBlocks.IsCreated)
m_usedBlocks = new NativeList(Allocator.Persistent);
@@ -90,20 +104,21 @@ public int Grow(int newDesiredCapacity, int maxAllowedCapacity = Int32.MaxValue)
m_FreeElementCount += addedElements;
m_MaxElementCount = newCapacity;
- int blockToMerge = m_freeBlocks.Length;
- m_freeBlocks.Add(new Block() { offset = oldCapacity, count = addedElements });
-
- while (blockToMerge != -1)
- blockToMerge = MergeBlockFrontBack(blockToMerge);
+ AddAndCoalesceFreeBlock(new Block() { offset = oldCapacity, count = addedElements });
return m_MaxElementCount;
}
+ private int TailFreeBlockCount()
+ {
+ return m_freeBlockEnds.TryGetValue(m_MaxElementCount, out int index) ? m_freeBlocks[index].count : 0;
+ }
+
public bool GetExpectedGrowthToFitAllocation(int elementCounts, int maxAllowedCapacity, out int newCapacity)
{
newCapacity = 0;
- var additionalRequiredElements = m_freeBlocks.IsEmpty ? elementCounts : math.max(elementCounts - m_freeBlocks[m_freeBlocks.Length - 1].count, 0);
+ var additionalRequiredElements = math.max(elementCounts - TailFreeBlockCount(), 0);
if (maxAllowedCapacity < capacity || (maxAllowedCapacity - capacity) < additionalRequiredElements)
return false;
@@ -120,7 +135,7 @@ public Allocation GrowAndAllocate(int elementCounts, int maxAllowedCapacity, out
{
oldCapacity = capacity;
- var additionalRequiredElements = m_freeBlocks.IsEmpty ? elementCounts : math.max(elementCounts - m_freeBlocks[m_freeBlocks.Length - 1].count, 0);
+ var additionalRequiredElements = math.max(elementCounts - TailFreeBlockCount(), 0);
if (maxAllowedCapacity < capacity || (maxAllowedCapacity - capacity) < additionalRequiredElements)
{
newCapacity = capacity;
@@ -145,11 +160,21 @@ public void Dispose()
m_usedBlocks.Dispose();
if (m_freeSlots.IsCreated)
m_freeSlots.Dispose();
+ if (m_freeBlockStarts.IsCreated)
+ m_freeBlockStarts.Dispose();
+ if (m_freeBlockEnds.IsCreated)
+ m_freeBlockEnds.Dispose();
}
public Allocation Allocate(int elementCounts)
{
- if (elementCounts > m_FreeElementCount || m_freeBlocks.IsEmpty)
+ if (elementCounts < 0 || elementCounts > m_FreeElementCount)
+ return Allocation.Invalid;
+
+ if (elementCounts == 0)
+ return new Allocation() { handle = AllocateHandle(Block.Invalid), block = Block.Invalid };
+
+ if (m_freeBlocks.IsEmpty)
return Allocation.Invalid;
int selectedBlock = -1;
@@ -163,6 +188,9 @@ public Allocation Allocate(int elementCounts)
{
currentBlockCount = block.count;
selectedBlock = b;
+
+ if (block.count == elementCounts)
+ break;
}
}
@@ -177,58 +205,30 @@ public Allocation Allocate(int elementCounts)
allocationBlock.count = elementCounts;
if (split.count > 0)
- m_freeBlocks[selectedBlock] = split;
+ SetFreeBlock(selectedBlock, split);
else
- m_freeBlocks.RemoveAtSwapBack(selectedBlock);
+ RemoveFreeBlockAt(selectedBlock);
+ m_FreeElementCount -= elementCounts;
+ return new Allocation() { handle = AllocateHandle(allocationBlock), block = allocationBlock };
+ }
+
+ private int AllocateHandle(in Block block)
+ {
int allocationHandle;
if (m_freeSlots.IsEmpty)
{
allocationHandle = m_usedBlocks.Length;
- m_usedBlocks.Add(allocationBlock);
+ m_usedBlocks.Add(block);
}
else
{
allocationHandle = m_freeSlots[m_freeSlots.Length - 1];
m_freeSlots.RemoveAtSwapBack(m_freeSlots.Length - 1);
- m_usedBlocks[allocationHandle] = allocationBlock;
- }
-
- m_FreeElementCount -= elementCounts;
- return new Allocation() { handle = allocationHandle, block = allocationBlock };
- }
-
- private int MergeBlockFrontBack(int freeBlockId)
- {
- Block targetBlock = m_freeBlocks[freeBlockId];
- for (int i = 0; i < m_freeBlocks.Length; ++i)
- {
- if (i == freeBlockId)
- continue;
-
- Block freeBlock = m_freeBlocks[i];
- bool mergeTargetBlock = false;
- if (targetBlock.offset == (freeBlock.offset + freeBlock.count))
- {
- freeBlock.count += targetBlock.count;
- mergeTargetBlock = true;
- }
- else if (freeBlock.offset == (targetBlock.offset + targetBlock.count))
- {
- freeBlock.offset = targetBlock.offset;
- freeBlock.count += targetBlock.count;
- mergeTargetBlock = true;
- }
-
- if (mergeTargetBlock)
- {
- m_freeBlocks[i] = freeBlock;
- m_freeBlocks.RemoveAtSwapBack(freeBlockId);
- return i == m_freeBlocks.Length ? freeBlockId : i;
- }
+ m_usedBlocks[allocationHandle] = block;
}
- return -1;
+ return allocationHandle;
}
public void FreeAllocation(in Allocation allocation)
@@ -238,11 +238,8 @@ public void FreeAllocation(in Allocation allocation)
m_freeSlots.Add(allocation.handle);
m_usedBlocks[allocation.handle] = Block.Invalid;
- int blockToMerge = m_freeBlocks.Length;
- m_freeBlocks.Add(allocation.block);
-
- while (blockToMerge != -1)
- blockToMerge = MergeBlockFrontBack(blockToMerge);
+ if (allocation.block.count > 0)
+ AddAndCoalesceFreeBlock(allocation.block);
m_FreeElementCount += allocation.block.count;
}
@@ -261,24 +258,99 @@ public Allocation[] SplitAllocation(in Allocation allocation, int count)
for (int i = 1; i < count; ++i)
{
Block block = new Block { offset = allocation.block.offset + i * newAllocsSize, count = newAllocsSize };
+ newAllocs[i] = new Allocation() { handle = AllocateHandle(block), block = block };
+ }
- int allocationHandle;
- if (m_freeSlots.IsEmpty)
- {
- allocationHandle = m_usedBlocks.Length;
- m_usedBlocks.Add(block);
- }
- else
- {
- allocationHandle = m_freeSlots[m_freeSlots.Length - 1];
- m_freeSlots.RemoveAtSwapBack(m_freeSlots.Length - 1);
- m_usedBlocks[allocationHandle] = block;
- }
+ return newAllocs;
+ }
+
+ private static int BlockEnd(in Block block)
+ {
+ return block.offset + block.count;
+ }
+
+ private void AddAndCoalesceFreeBlock(Block block)
+ {
+ if (m_freeBlockEnds.TryGetValue(block.offset, out int predecessorIndex))
+ {
+ Block predecessor = m_freeBlocks[predecessorIndex];
+ RemoveFreeBlockAt(predecessorIndex);
+ block.offset = predecessor.offset;
+ block.count += predecessor.count;
+ }
- newAllocs[i] = new Allocation() { handle = allocationHandle, block = block };
+ if (m_freeBlockStarts.TryGetValue(BlockEnd(block), out int successorIndex))
+ {
+ Block successor = m_freeBlocks[successorIndex];
+ RemoveFreeBlockAt(successorIndex);
+ block.count += successor.count;
}
- return newAllocs;
+ AddFreeBlockEntry(block);
+ }
+
+ private void AddFreeBlockEntry(in Block block)
+ {
+ m_freeBlockStarts.Add(block.offset, m_freeBlocks.Length);
+ m_freeBlockEnds.Add(BlockEnd(block), m_freeBlocks.Length);
+ m_freeBlocks.Add(block);
+ }
+
+ private void SetFreeBlock(int index, in Block newBlock)
+ {
+ Block oldBlock = m_freeBlocks[index];
+ m_freeBlockStarts.Remove(oldBlock.offset);
+ m_freeBlockEnds.Remove(BlockEnd(oldBlock));
+ m_freeBlockStarts.Add(newBlock.offset, index);
+ m_freeBlockEnds.Add(BlockEnd(newBlock), index);
+ m_freeBlocks[index] = newBlock;
+ }
+
+ private void RemoveFreeBlockAt(int index)
+ {
+ Block removed = m_freeBlocks[index];
+ m_freeBlockStarts.Remove(removed.offset);
+ m_freeBlockEnds.Remove(BlockEnd(removed));
+
+ int last = m_freeBlocks.Length - 1;
+ if (index != last)
+ {
+ Block moved = m_freeBlocks[last];
+ m_freeBlockStarts[moved.offset] = index;
+ m_freeBlockEnds[BlockEnd(moved)] = index;
+ }
+
+ m_freeBlocks.RemoveAtSwapBack(index);
+ }
+
+#if UNITY_EDITOR || UNITY_ENABLE_CHECKS
+ internal void ValidateInvariants()
+ {
+ if (m_freeBlockStarts.Count != m_freeBlocks.Length || m_freeBlockEnds.Count != m_freeBlocks.Length)
+ throw new InvalidOperationException($"Boundary map counts ({m_freeBlockStarts.Count}, {m_freeBlockEnds.Count}) do not match free block count ({m_freeBlocks.Length}).");
+
+ int totalFreeCount = 0;
+ for (int i = 0; i < m_freeBlocks.Length; ++i)
+ {
+ Block block = m_freeBlocks[i];
+
+ if (block.count <= 0)
+ throw new InvalidOperationException($"Free block {i} has non-positive count {block.count}.");
+ if (block.offset < 0 || BlockEnd(block) > m_MaxElementCount)
+ throw new InvalidOperationException($"Free block {i} [{block.offset}, {BlockEnd(block)}) is outside capacity {m_MaxElementCount}.");
+ if (!m_freeBlockStarts.TryGetValue(block.offset, out int startIndex) || startIndex != i)
+ throw new InvalidOperationException($"Start map entry for free block {i} is missing or stale.");
+ if (!m_freeBlockEnds.TryGetValue(BlockEnd(block), out int endIndex) || endIndex != i)
+ throw new InvalidOperationException($"End map entry for free block {i} is missing or stale.");
+ if (m_freeBlockStarts.ContainsKey(BlockEnd(block)))
+ throw new InvalidOperationException($"Free block {i} is adjacent to an unmerged free block.");
+
+ totalFreeCount += block.count;
+ }
+
+ if (totalFreeCount != m_FreeElementCount)
+ throw new InvalidOperationException($"Sum of free block counts ({totalFreeCount}) does not match freeElementsCount ({m_FreeElementCount}).");
}
+#endif
}
}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscale.compute b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscale.compute
new file mode 100644
index 00000000000..a7c0a235412
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscale.compute
@@ -0,0 +1,360 @@
+#pragma kernel UpscaleAlphaAndMergeColor
+
+#pragma multi_compile _ DISABLE_TEXTURE2D_X_ARRAY
+#pragma multi_compile _ DIRECT_STENCIL_SAMPLE REACTIVE_MASK
+
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2 glcore webgpu
+
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl"
+
+// Include TextureXR.hlsl for XR macros
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/TextureXR.hlsl"
+
+#if UNITY_REVERSED_Z
+ #define COMPARE_DEPTH(a, b) step(b, a)
+#else
+ #define COMPARE_DEPTH(a, b) step(a, b)
+#endif
+
+TEXTURE2D_X(_UpscaledColor);
+// Pre-upscale color at rendering resolution. Only the alpha channel is read.
+TEXTURE2D_X(_PreUpscaleAlpha);
+
+// Depth at rendering resolution, used to dilate the motion vectors at silhouettes.
+TEXTURE2D_X(_DepthTexture);
+// Motion vectors at rendering resolution, in UV space (current - previous frame position).
+TEXTURE2D_X(_MotionVectorTexture);
+// Post-upscale alpha accumulated over the previous frames.
+TEXTURE2D_X(_AlphaHistory);
+
+#if defined(DIRECT_STENCIL_SAMPLE)
+// Stencil at rendering resolution: pixels whose stencil equals _ExcludeTAABit skip the temporal
+// accumulation, matching the TAA exclusion of FragTAA.
+TYPED_TEXTURE2D_X(uint2, _StencilTexture);
+uint _ExcludeTAABit;
+#endif
+
+#if defined(REACTIVE_MASK)
+TEXTURE2D_X(_ReactiveMaskTexture);
+#endif
+
+RW_TEXTURE2D_X(float4, _OutputTexture);
+RW_TEXTURE2D_X(float, _AlphaHistoryOutput);
+
+SAMPLER(s_linear_clamp_sampler);
+SAMPLER(s_point_clamp_sampler);
+
+// xy: input (pre-upscale) viewport size in pixels, zw: rcp of the input texture size
+float4 _AlphaUpscaleParams0;
+// xy: output viewport size in pixels, zw: camera jitter of the current frame in input pixels
+float4 _AlphaUpscaleParams1;
+// x: history blend weight (0 disables the temporal accumulation for this frame),
+// y: history buffers available (0 disables the history read and write entirely),
+// zw: rcp of the history texture size
+float4 _AlphaUpscaleParams2;
+
+// ------------------------------------------------------------------------------------------------
+// Scalar port of the TAA_UPSAMPLE path of HDRP's TAA, applied to the alpha channel only.
+// Differences from HDRP's TAA:
+// - The alpha value replaces the color luma in the luma-driven heuristics.
+// - Color-only logic is not ported: YCoCg/tonemap/perceptual weighting, the upsample confidence
+// and final blend-factor clamp, and the ENABLE_ALPHA color guards.
+// - Fixed to a default TAAU camera configuration: bilinear history resampling, no
+// history-contrast anti-flicker, no velocity rejection.
+// ------------------------------------------------------------------------------------------------
+
+// output over input scale and its inverse
+#define _TAAUScale (_AlphaUpscaleParams1.x / _AlphaUpscaleParams0.x)
+#define _TAAURenderScale (_AlphaUpscaleParams0.x / _AlphaUpscaleParams1.x)
+// The current frame weight
+#define _BaseBlendFactor (1.0 - _AlphaUpscaleParams2.x)
+// Input and history viewport sizes and their reciprocals
+#define _InputSize float4(_AlphaUpscaleParams0.xy, rcp(_AlphaUpscaleParams0.xy))
+#define _TaaHistorySize float4(_AlphaUpscaleParams1.xy, rcp(_AlphaUpscaleParams1.xy))
+// The camera jitter in input pixels (xy) and input UV (zw)
+#define _TaaJitterStrength float4(_AlphaUpscaleParams1.zw, _AlphaUpscaleParams1.zw * rcp(_AlphaUpscaleParams0.xy))
+// The RTHandle scales: viewport over physical texture size
+#define _RTHandleScaleForTAA (_AlphaUpscaleParams0.xy * _AlphaUpscaleParams0.zw)
+#define _RTHandleScaleForTAAHistory (_AlphaUpscaleParams1.xy * _AlphaUpscaleParams2.zw)
+
+// _AntiFlickerIntensity / _ContrastForMaxAntiFlicker: PrepareTAAPassData values for the default
+// camera taaAntiFlicker of 0.5: lerp(0, 3.5, 0.5) and 0.7 - lerp(0, 0.3, SmoothStep(0.5, 1, 0.5))
+#define _AntiFlickerIntensity 1.75
+#define _ContrastForMaxAntiFlicker 0.7
+
+#define NEIGHBOUR_COUNT 8
+#define SAMPLE_COUNT (NEIGHBOUR_COUNT + 1)
+
+static const int2 NeighbourOffsets[NEIGHBOUR_COUNT] =
+{
+ int2(0, 1), int2(1, 0), int2(-1, 0), int2(0, -1),
+ int2(-1, 1), int2(1, -1), int2(1, 1), int2(-1, -1)
+};
+
+struct NeighbourhoodSamples
+{
+ float neighbours[NEIGHBOUR_COUNT];
+ float central;
+ float minNeighbour;
+ float maxNeighbour;
+};
+
+// ------------------------------------------------------------------------------------------------
+// Input tile cached in groupshared memory: all alpha and depth taps land on input-resolution
+// texel centers, so the threads of a group cooperatively load the input footprint of their
+// output tile once (each texel fetched by one thread) instead of tapping the textures per pixel. Tap values match the direct taps, with the borders clamped
+// to the input viewport. Since the pass only upscales, the footprint of GROUP_SIZE output
+// pixels stays within GROUP_SIZE input texels, plus the one-texel neighbourhood/dilation border.
+// ------------------------------------------------------------------------------------------------
+
+#define GROUP_SIZE 16
+#define TILE_BORDER 1
+#define TILE_SIZE (GROUP_SIZE + 2 * TILE_BORDER)
+
+groupshared float gs_TileAlpha[TILE_SIZE * TILE_SIZE];
+groupshared float gs_TileDepth[TILE_SIZE * TILE_SIZE];
+
+float TileAlpha(int2 tileCoord)
+{
+ return gs_TileAlpha[tileCoord.y * TILE_SIZE + tileCoord.x];
+}
+
+float TileDepth(int2 tileCoord)
+{
+ return gs_TileDepth[tileCoord.y * TILE_SIZE + tileCoord.x];
+}
+
+// The input texel containing the dejittered position of the group's first output pixel, minus the border.
+int2 GetTileOrigin(uint2 groupOrigin)
+{
+ float2 firstPixInInput = (((float2)groupOrigin + 0.5) / _AlphaUpscaleParams1.xy) * _InputSize.xy - _TaaJitterStrength.xy;
+ return int2(floor(firstPixInInput)) - TILE_BORDER;
+}
+
+void LoadInputTile(int2 tileOrigin, uint groupIndex)
+{
+ const int2 maxCoord = int2(_InputSize.xy) - 1;
+ const uint tileSize = TILE_SIZE;
+
+ for (uint i = groupIndex; i < tileSize * tileSize; i += GROUP_SIZE * GROUP_SIZE)
+ {
+ int2 coord = clamp(tileOrigin + int2(i % tileSize, i / tileSize), 0, maxCoord);
+ gs_TileAlpha[i] = LOAD_TEXTURE2D_X_LOD(_PreUpscaleAlpha, coord, 0).a;
+ gs_TileDepth[i] = LOAD_TEXTURE2D_X_LOD(_DepthTexture, coord, 0).r;
+ }
+}
+
+float FetchHistory(float2 coords, float2 scale)
+{
+ return SAMPLE_TEXTURE2D_X_LOD(_AlphaHistory, s_linear_clamp_sampler, coords * scale, 0).x;
+}
+
+float2 GetClosestFragmentOffset(int2 tileCoord)
+{
+ float center = TileDepth(tileCoord);
+
+ int2 offset0 = int2( 1, 1);
+ int2 offset1 = int2(-1, 1);
+ int2 offset2 = int2( 1, -1);
+ int2 offset3 = int2(-1, -1);
+
+ float s3 = TileDepth(tileCoord + offset3);
+ float s2 = TileDepth(tileCoord + offset2);
+ float s1 = TileDepth(tileCoord + offset1);
+ float s0 = TileDepth(tileCoord + offset0);
+
+ float3 closest = float3(0.0, 0.0, center);
+ closest = COMPARE_DEPTH(s0, closest.z) ? float3(offset0, s0) : closest;
+ closest = COMPARE_DEPTH(s3, closest.z) ? float3(offset3, s3) : closest;
+ closest = COMPARE_DEPTH(s2, closest.z) ? float3(offset2, s2) : closest;
+ closest = COMPARE_DEPTH(s1, closest.z) ? float3(offset1, s1) : closest;
+
+ return closest.xy;
+}
+
+float2 GetMotionVector(float2 uv, int2 tileCoord, float2 inputTexelSize, float2 inputScale)
+{
+ float2 closestOffset = GetClosestFragmentOffset(tileCoord);
+
+ float2 motionVector = SAMPLE_TEXTURE2D_X_LOD(_MotionVectorTexture, s_point_clamp_sampler, (uv + closestOffset * inputTexelSize) * inputScale, 0).xy;
+ return motionVector.x > 1.0 ? 0.0 : motionVector;
+}
+
+void GatherNeighbourhood(int2 tileCoord, float centralAlpha, out NeighbourhoodSamples samples)
+{
+ ZERO_INITIALIZE(NeighbourhoodSamples, samples);
+
+ samples.central = centralAlpha;
+
+ [unroll]
+ for (int i = 0; i < NEIGHBOUR_COUNT; ++i)
+ {
+ samples.neighbours[i] = TileAlpha(tileCoord + NeighbourOffsets[i]);
+ }
+}
+
+void VarianceNeighbourhood(inout NeighbourhoodSamples samples, float historyAlpha, float filteredAlpha, float2 antiFlickerParams, float motionVecLenInPixels, float downsampleFactor)
+{
+ float moment1 = 0.0;
+ float moment2 = 0.0;
+
+ [unroll]
+ for (int i = 0; i < NEIGHBOUR_COUNT; ++i)
+ {
+ moment1 += samples.neighbours[i];
+ moment2 += samples.neighbours[i] * samples.neighbours[i];
+ }
+
+ moment1 += samples.central;
+ moment2 += samples.central * samples.central;
+
+ moment1 *= rcp(SAMPLE_COUNT);
+ moment2 *= rcp(SAMPLE_COUNT);
+
+ float stdDev = sqrt(abs(moment2 - moment1 * moment1));
+
+ float stDevMultiplier = 1.5;
+
+ float aggressiveStdDev = stdDev * 0.5;
+ float aggressiveClampedHistory = clamp(historyAlpha, moment1 - aggressiveStdDev, moment1 + aggressiveStdDev);
+
+ const float maxFactorScale = 2.25f; // when stationary
+ const float minFactorScale = 0.8f; // when moving more than slightly
+
+ float localizedAntiFlicker = lerp(antiFlickerParams.x * minFactorScale, antiFlickerParams.x * maxFactorScale, saturate(1.0f - 2.0f * (motionVecLenInPixels)));
+
+ float temporalContrast = saturate(abs(filteredAlpha - aggressiveClampedHistory) / Max3(0.15, filteredAlpha, aggressiveClampedHistory));
+ stDevMultiplier += lerp(0.0, localizedAntiFlicker, smoothstep(0.05, antiFlickerParams.y, temporalContrast));
+
+ stDevMultiplier = lerp(stDevMultiplier, 0.75, saturate(motionVecLenInPixels / 50.0f));
+
+ // We shrink the bounding box when upscaling as ghosting is more likely.
+ stDevMultiplier = lerp(0.9f, stDevMultiplier, saturate(downsampleFactor));
+
+ samples.minNeighbour = moment1 - stdDev * stDevMultiplier;
+ samples.maxNeighbour = moment1 + stdDev * stDevMultiplier;
+}
+
+// Polynomial approximation of the Gaussian sample weight in the following link.
+// https://www.desmos.com/calculator/g2hr2hzj84
+float GetSampleWeight(float2 offsets, float4 filterParameters)
+{
+ const float2 inputToOutputVec = filterParameters.zw;
+ const float resolutionScale2 = filterParameters.y * filterParameters.y;
+ float2 d = offsets - inputToOutputVec;
+
+ float x2 = saturate(resolutionScale2 * dot(d, d));
+ float f = 0.9656852 * x2 - 1;
+ return f * f;
+}
+
+float FilterCentralColor(NeighbourhoodSamples samples, float4 filterParameters)
+{
+ float totalWeight = GetSampleWeight(0, filterParameters); // center
+ float filtered = samples.central * totalWeight;
+
+ [unroll]
+ for (int i = 0; i < NEIGHBOUR_COUNT; ++i)
+ {
+ float w = GetSampleWeight(NeighbourOffsets[i], filterParameters);
+ filtered += samples.neighbours[i] * w;
+ totalWeight += w;
+ }
+ filtered *= rcp(totalWeight);
+ return filtered;
+}
+
+[numthreads(GROUP_SIZE, GROUP_SIZE, 1)]
+void UpscaleAlphaAndMergeColor(uint3 groupId : SV_GroupID, uint groupIndex : SV_GroupIndex, uint3 dispatchThreadId : SV_DispatchThreadID)
+{
+ UNITY_XR_ASSIGN_VIEW_INDEX(dispatchThreadId.z);
+
+ int2 tileOrigin = GetTileOrigin(groupId.xy * GROUP_SIZE);
+ LoadInputTile(tileOrigin, groupIndex);
+ GroupMemoryBarrierWithGroupSync();
+
+ uint2 pos = dispatchThreadId.xy;
+ if (any(pos >= uint2(_AlphaUpscaleParams1.xy)))
+ return;
+
+ float3 color = LOAD_TEXTURE2D_X(_UpscaledColor, pos).rgb;
+
+ // The output pixel's dejittered position in the input,
+ // with the tap UV snapped to the center of the containing input texel (the sub-texel
+ // part goes into the filter weights below).
+ float2 outputUV = ((float2)pos + 0.5) / _AlphaUpscaleParams1.xy;
+ float2 outputPixInInput = outputUV * _InputSize.xy - _TaaJitterStrength.xy;
+ float2 uv = _InputSize.zw * (0.5f + floor(outputPixInInput));
+
+ // The containing texel in tile coordinates.
+ int2 tileCoord = clamp(int2(floor(outputPixInInput)) - tileOrigin, TILE_BORDER, TILE_SIZE - 1 - TILE_BORDER);
+
+ bool excludeTAABit = false;
+#if DIRECT_STENCIL_SAMPLE
+ uint stencil = GetStencilValue(LOAD_TEXTURE2D_X(_StencilTexture, int2(outputPixInInput)));
+ excludeTAABit = (stencil == _ExcludeTAABit);
+#endif
+
+#if REACTIVE_MASK
+ float reactiveMask = LOAD_TEXTURE2D_X(_ReactiveMaskTexture, int2(outputPixInInput)).x;
+#endif
+
+ // --------------- Get closest motion vector ---------------
+ float2 motionVector = GetMotionVector(uv, tileCoord, _InputSize.zw, _RTHandleScaleForTAA);
+
+ // --------------- Get resampled history ---------------
+ float2 prevUV = outputUV - motionVector;
+
+ float history = FetchHistory(prevUV, _RTHandleScaleForTAAHistory);
+ bool offScreen = any(abs(prevUV * 2 - 1) >= (1.0f - (1.0 * _TaaHistorySize.zw)));
+
+ // --------------- Gather neigbourhood data ---------------
+ float alpha = TileAlpha(tileCoord);
+
+ if (!excludeTAABit)
+ {
+ NeighbourhoodSamples samples;
+ GatherNeighbourhood(tileCoord, alpha, samples);
+
+ // --------------- Filter central sample ---------------
+ float4 filterParams = 0;
+ filterParams.y = _TAAUScale;
+ filterParams.zw = outputPixInInput - (floor(outputPixInInput) + 0.5f);
+
+ float filteredAlpha = FilterCentralColor(samples, filterParams);
+
+ if (offScreen)
+ history = filteredAlpha;
+
+ // --------------- Get neighbourhood information and clamp history ---------------
+ float motionVectorLenInPixels = length(motionVector) * length(_InputSize.xy);
+
+ VarianceNeighbourhood(samples, history, filteredAlpha, float2(_AntiFlickerIntensity, _ContrastForMaxAntiFlicker), motionVectorLenInPixels, _TAAURenderScale);
+
+ // GetClippedHistory with DIRECT_CLIP reduces to a clamp for a scalar
+ history = clamp(history, samples.minNeighbour, samples.maxNeighbour);
+
+ // --------------- Compute blend factor for history ---------------
+ // On a history reset, and in the spatial-only mode (no history buffers provided, dummy
+ // textures bound), the history weight is 0, so the blend factor is 1 and the result falls
+ // through to the filtered alpha.
+ float blendFactor = _BaseBlendFactor;
+ // BLEND_FACTOR_MV_TUNE
+ blendFactor = lerp(blendFactor, saturate(2.0f * blendFactor), saturate(motionVectorLenInPixels / 50.0f));
+
+#if REACTIVE_MASK
+ blendFactor = lerp(blendFactor, 1.0f, reactiveMask);
+#endif
+
+ // --------------- Alpha handling ---------------
+ alpha = lerp(history, filteredAlpha, blendFactor);
+ }
+ // Keep NaNs out of the history feedback loop, where they would otherwise persist.
+ alpha = saturate(alpha);
+
+ if (_AlphaUpscaleParams2.y != 0.0)
+ _AlphaHistoryOutput[COORD_TEXTURE2D_X(pos)] = alpha;
+
+ _OutputTexture[COORD_TEXTURE2D_X(pos)] = float4(color, alpha);
+}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscale.compute.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscale.compute.meta
new file mode 100644
index 00000000000..de8a816ec5e
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscale.compute.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: f10c23179af641eea368ee165b2e97cf
+ComputeShaderImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscaler.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscaler.cs
new file mode 100644
index 00000000000..2ce132136f3
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscaler.cs
@@ -0,0 +1,291 @@
+using System;
+using UnityEngine.Experimental.Rendering;
+using UnityEngine.Rendering.RenderGraphModule;
+
+namespace UnityEngine.Rendering
+{
+ ///
+ /// Utility pass that rebuilds the alpha channel of an image produced by a color-only upscaler.
+ ///
+ public static class AlphaUpscaler
+ {
+ ///
+ /// Input textures and parameters for the alpha upscale pass.
+ ///
+ public struct Config
+ {
+ /// Color at rendering resolution, before upscaling. Only the alpha channel is read.
+ public TextureHandle preUpscaleAlpha;
+
+ /// Upscaled color whose alpha channel is undefined. Only the RGB channels are read.
+ public TextureHandle upscaledColor;
+
+ /// Size of the rendered viewport of preUpscaleAlpha, in pixels.
+ public Vector2Int preUpscaleSize;
+
+ ///
+ /// Physical (allocation) size of preUpscaleAlpha when it is larger than preUpscaleSize,
+ /// e.g. with viewport-based dynamic resolution inside a larger texture. Leave zero when
+ /// the texture is allocated at exactly preUpscaleSize.
+ ///
+ public Vector2Int preUpscalePhysicalSize;
+
+ /// Size of the upscaled output, in pixels.
+ public Vector2Int postUpscaleSize;
+
+ /// Sub-pixel camera jitter applied to the pre-upscale frame, in pixels at the rendering resolution.
+ public Vector2 jitter;
+
+ /// Indicates whether the textures are 2D texture arrays, as used by XR single-pass rendering.
+ public bool enableTexArray;
+
+ /// Number of views to process.
+ public int viewCount;
+
+ ///
+ /// Motion vectors at rendering resolution, in viewport UV space. Along with the depth and
+ /// the two history textures, this enables the temporal accumulation; leave invalid for a
+ /// spatial-only upsample.
+ ///
+ public TextureHandle motionVectors;
+
+ /// Depth at rendering resolution, for the motion vector dilation at silhouettes.
+ public TextureHandle cameraDepth;
+
+ ///
+ /// Reactive mask at rendering resolution, or leave invalid to disable.
+ ///
+ public TextureHandle reactiveMask;
+
+ /// Stencil value that marks the excluded pixels when reactiveMask is a stencil buffer.
+ public int stencilExcludeBit;
+
+ /// Single-channel alpha history accumulated over the previous frames.
+ public TextureHandle prevAlphaHistory;
+
+ /// Single-channel alpha history the pass writes this frame.
+ public TextureHandle nextAlphaHistory;
+
+ ///
+ /// Blend weight of the reprojected history. Use 0 when the history content is invalid (e.g. on a
+ /// history reset): the frame falls back to the spatial upsample but still initializes the history.
+ ///
+ public float historyBlendFactor;
+ }
+
+ /// Default history blend weight of the temporal alpha accumulation.
+ public const float defaultHistoryBlendFactor = 0.85f;
+
+ ///
+ /// Contains the compute shader used by the alpha upscale pass
+ ///
+ [Serializable]
+ [SupportedOnRenderPipeline]
+ [Categorization.CategoryInfo(Name = "R: Alpha Upscaler", Order = 1000)]
+ [Categorization.ElementInfo(Order = 0), HideInInspector]
+ internal class RuntimeResources : IRenderPipelineResources
+ {
+ public int version => 0;
+
+ bool IRenderPipelineGraphicsSettings.isAvailableInPlayerBuild => true;
+
+ [SerializeField, ResourcePath("Runtime/Upscaling/AlphaUpscale.compute")]
+ private ComputeShader m_AlphaUpscaleCS;
+
+ public ComputeShader alphaUpscaleCS
+ {
+ get => m_AlphaUpscaleCS;
+ set => this.SetValueAndNotify(ref m_AlphaUpscaleCS, value);
+ }
+ }
+
+ static class ShaderResources
+ {
+ public static readonly int _UpscaledColor = Shader.PropertyToID("_UpscaledColor");
+ public static readonly int _PreUpscaleAlpha = Shader.PropertyToID("_PreUpscaleAlpha");
+ public static readonly int _MotionVectorTexture = Shader.PropertyToID("_MotionVectorTexture");
+ public static readonly int _DepthTexture = Shader.PropertyToID("_DepthTexture");
+ public static readonly int _StencilTexture = Shader.PropertyToID("_StencilTexture");
+ public static readonly int _ExcludeTAABit = Shader.PropertyToID("_ExcludeTAABit");
+ public static readonly int _ReactiveMaskTexture = Shader.PropertyToID("_ReactiveMaskTexture");
+ public static readonly int _AlphaHistory = Shader.PropertyToID("_AlphaHistory");
+ public static readonly int _AlphaHistoryOutput = Shader.PropertyToID("_AlphaHistoryOutput");
+ public static readonly int _OutputTexture = Shader.PropertyToID("_OutputTexture");
+ public static readonly int _AlphaUpscaleParams0 = Shader.PropertyToID("_AlphaUpscaleParams0");
+ public static readonly int _AlphaUpscaleParams1 = Shader.PropertyToID("_AlphaUpscaleParams1");
+ public static readonly int _AlphaUpscaleParams2 = Shader.PropertyToID("_AlphaUpscaleParams2");
+ }
+
+ static class ShaderKeywords
+ {
+ public static readonly string DisableTexture2DXArray = "DISABLE_TEXTURE2D_X_ARRAY";
+ public static readonly string DirectStencilSample = "DIRECT_STENCIL_SAMPLE";
+ public static readonly string ReactiveMask = "REACTIVE_MASK";
+ }
+
+ enum ReactiveMaskMode
+ {
+ None,
+ Stencil,
+ Color
+ }
+
+ class PassData
+ {
+ public ComputeShader cs;
+ public int kernelIndex;
+ public Vector2Int dispatchSize;
+ public int viewCount;
+ public Vector2Int preUpscaleSize;
+ public Vector2Int preUpscalePhysicalSize;
+ public Vector4 params1;
+ public float historyBlend;
+ public bool useHistory;
+ public ReactiveMaskMode reactiveMaskMode;
+ public int stencilExcludeBit;
+
+ public TextureHandle preUpscaleAlpha;
+ public TextureHandle upscaledColor;
+ public TextureHandle motionVectors;
+ public TextureHandle cameraDepth;
+ public TextureHandle reactiveMask;
+ public TextureHandle prevAlphaHistory;
+ public TextureHandle nextAlphaHistory;
+ public TextureHandle destination;
+ }
+
+ static readonly ProfilingSampler k_AlphaUpscale = new ProfilingSampler("AlphaUpscale");
+
+ ///
+ /// Executes the alpha upscale pass using the provided configuration in the target render graph
+ ///
+ /// render graph to execute the pass within
+ /// configuration parameters for the pass
+ /// Texture handle that contains the upscaled color with a valid alpha channel
+ public static TextureHandle Execute(RenderGraph renderGraph, ref Config config)
+ {
+ var runtimeResources = GraphicsSettings.GetRenderPipelineSettings();
+
+ using (var builder = renderGraph.AddComputePass("Upscale Alpha And Merge Color", out var passData, k_AlphaUpscale))
+ {
+ passData.cs = runtimeResources.alphaUpscaleCS;
+ passData.cs.shaderKeywords = null;
+
+ if (!config.enableTexArray)
+ passData.cs.EnableKeyword(ShaderKeywords.DisableTexture2DXArray);
+
+ var maskMode = ReactiveMaskMode.None;
+ if (config.reactiveMask.IsValid())
+ maskMode = config.stencilExcludeBit != 0 ? ReactiveMaskMode.Stencil : ReactiveMaskMode.Color;
+ passData.reactiveMaskMode = maskMode;
+
+ if (maskMode != ReactiveMaskMode.None)
+ {
+ passData.cs.EnableKeyword(maskMode == ReactiveMaskMode.Stencil
+ ? ShaderKeywords.DirectStencilSample : ShaderKeywords.ReactiveMask);
+ passData.stencilExcludeBit = config.stencilExcludeBit;
+ passData.reactiveMask = config.reactiveMask;
+ builder.UseTexture(passData.reactiveMask, AccessFlags.Read);
+ }
+
+ passData.kernelIndex = passData.cs.FindKernel("UpscaleAlphaAndMergeColor");
+ passData.viewCount = config.viewCount;
+
+ // Must match GROUP_SIZE in AlphaUpscale.compute
+ const int groupSize = 16;
+ passData.dispatchSize = new Vector2Int(
+ CoreUtils.DivRoundUp(config.postUpscaleSize.x, groupSize),
+ CoreUtils.DivRoundUp(config.postUpscaleSize.y, groupSize)
+ );
+
+ passData.preUpscaleSize = config.preUpscaleSize;
+ passData.preUpscalePhysicalSize = (config.preUpscalePhysicalSize.x > 0 && config.preUpscalePhysicalSize.y > 0)
+ ? config.preUpscalePhysicalSize : config.preUpscaleSize;
+ passData.params1 = new Vector4(config.postUpscaleSize.x, config.postUpscaleSize.y, config.jitter.x, config.jitter.y);
+
+ passData.preUpscaleAlpha = config.preUpscaleAlpha;
+ builder.UseTexture(passData.preUpscaleAlpha, AccessFlags.Read);
+ passData.upscaledColor = config.upscaledColor;
+ builder.UseTexture(passData.upscaledColor, AccessFlags.Read);
+
+ var destinationDesc = config.upscaledColor.GetDescriptor(renderGraph);
+ destinationDesc.name = "UpscaledColorWithAlpha";
+ destinationDesc.enableRandomWrite = true;
+ destinationDesc.clearBuffer = false;
+ passData.destination = renderGraph.CreateTexture(destinationDesc);
+ builder.UseTexture(passData.destination, AccessFlags.WriteAll);
+
+ bool useHistory = config.motionVectors.IsValid() && config.cameraDepth.IsValid() && config.prevAlphaHistory.IsValid() && config.nextAlphaHistory.IsValid();
+ passData.useHistory = useHistory;
+ passData.historyBlend = config.historyBlendFactor;
+
+ if (useHistory)
+ {
+ passData.motionVectors = config.motionVectors;
+ passData.cameraDepth = config.cameraDepth;
+ passData.prevAlphaHistory = config.prevAlphaHistory;
+ passData.nextAlphaHistory = config.nextAlphaHistory;
+ }
+ else
+ {
+ // The kernel never touches the history in this mode, but the bindings must still be valid.
+ passData.motionVectors = renderGraph.defaultResources.blackTextureXR;
+ passData.cameraDepth = renderGraph.defaultResources.blackTextureXR;
+ passData.prevAlphaHistory = renderGraph.defaultResources.blackTextureXR;
+ passData.nextAlphaHistory = renderGraph.CreateTexture(new TextureDesc(1, 1, false, config.enableTexArray)
+ {
+ name = "AlphaHistoryUnused",
+ format = GraphicsFormat.R16_SFloat,
+ enableRandomWrite = true
+ });
+ }
+
+ builder.UseTexture(passData.motionVectors, AccessFlags.Read);
+ builder.UseTexture(passData.cameraDepth, AccessFlags.Read);
+ builder.UseTexture(passData.prevAlphaHistory, AccessFlags.Read);
+ builder.UseTexture(passData.nextAlphaHistory, AccessFlags.Write);
+
+ builder.SetRenderFunc(
+ static (PassData data, ComputeGraphContext ctx) =>
+ {
+ var params0 = new Vector4(data.preUpscaleSize.x, data.preUpscaleSize.y, 1.0f / data.preUpscalePhysicalSize.x, 1.0f / data.preUpscalePhysicalSize.y);
+
+ // zw: the history RTHandle can be larger than the post-upscale viewport,
+ // so the kernel samples it with the physical texture size.
+ var params2 = Vector4.zero;
+ if (data.useHistory)
+ {
+ var historyTexture = (RenderTexture)data.nextAlphaHistory;
+ params2 = new Vector4(data.historyBlend, 1.0f, 1.0f / historyTexture.width, 1.0f / historyTexture.height);
+ }
+
+ ctx.cmd.SetComputeVectorParam(data.cs, ShaderResources._AlphaUpscaleParams0, params0);
+ ctx.cmd.SetComputeVectorParam(data.cs, ShaderResources._AlphaUpscaleParams1, data.params1);
+ ctx.cmd.SetComputeVectorParam(data.cs, ShaderResources._AlphaUpscaleParams2, params2);
+
+ ctx.cmd.SetComputeTextureParam(data.cs, data.kernelIndex, ShaderResources._PreUpscaleAlpha, data.preUpscaleAlpha);
+ ctx.cmd.SetComputeTextureParam(data.cs, data.kernelIndex, ShaderResources._UpscaledColor, data.upscaledColor);
+ ctx.cmd.SetComputeTextureParam(data.cs, data.kernelIndex, ShaderResources._MotionVectorTexture, data.motionVectors);
+ ctx.cmd.SetComputeTextureParam(data.cs, data.kernelIndex, ShaderResources._DepthTexture, data.cameraDepth);
+
+ if (data.reactiveMaskMode == ReactiveMaskMode.Stencil)
+ {
+ ctx.cmd.SetComputeTextureParam(data.cs, data.kernelIndex, ShaderResources._StencilTexture, data.reactiveMask, 0, RenderTextureSubElement.Stencil);
+ ctx.cmd.SetComputeIntParam(data.cs, ShaderResources._ExcludeTAABit, data.stencilExcludeBit);
+ }
+ else if (data.reactiveMaskMode == ReactiveMaskMode.Color)
+ {
+ ctx.cmd.SetComputeTextureParam(data.cs, data.kernelIndex, ShaderResources._ReactiveMaskTexture, data.reactiveMask);
+ }
+ ctx.cmd.SetComputeTextureParam(data.cs, data.kernelIndex, ShaderResources._AlphaHistory, data.prevAlphaHistory);
+ ctx.cmd.SetComputeTextureParam(data.cs, data.kernelIndex, ShaderResources._AlphaHistoryOutput, data.nextAlphaHistory);
+ ctx.cmd.SetComputeTextureParam(data.cs, data.kernelIndex, ShaderResources._OutputTexture, data.destination);
+
+ ctx.cmd.DispatchCompute(data.cs, data.kernelIndex, data.dispatchSize.x, data.dispatchSize.y, data.viewCount);
+ });
+
+ return passData.destination;
+ }
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscaler.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscaler.cs.meta
new file mode 100644
index 00000000000..182863ea5cf
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/AlphaUpscaler.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 2762c3adff164eee9cb41d3a0b52d5d1
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscaler.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscaler.cs
index 4e9bcf41ad3..d2a86fd4233 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscaler.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscaler.cs
@@ -177,6 +177,11 @@ public interface IUpscaler : IRenderGraphRecorder
///
bool supportsSharpening { get; }
+ ///
+ /// Returns true if the alpha channel of the upscaler's output is valid.
+ ///
+ bool supportsAlphaUpscaling { get; }
+
///
/// Returns true if the upscaler exposes a quality mode that can dictate the render resolution (e.g. the
/// DLSS/FSR presets). When false, the upscaler has no opinion on resolution and the pipeline drives the render
@@ -267,6 +272,9 @@ public abstract class AbstractUpscaler : IUpscaler
///
public abstract bool supportsSharpening { get; }
+ ///
+ public virtual bool supportsAlphaUpscaling => false;
+
///
public virtual bool hasQualityMode => false;
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Debugging/DebugUITests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/Debugging/DebugUITests.cs
index bb87bff1bee..d182a190c1e 100644
--- a/Packages/com.unity.render-pipelines.core/Tests/Editor/Debugging/DebugUITests.cs
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Debugging/DebugUITests.cs
@@ -1,3 +1,6 @@
+#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
+#define ENABLE_RENDERING_DEBUGGER_UI
+#endif
#if ENABLE_RENDERING_DEBUGGER_UI
using NUnit.Framework;
using UnityEngine.Rendering;
@@ -63,6 +66,51 @@ public void RoundToPrecision_WithLargeValueAndRefValue_HandlesCorrectly()
float result = DebugUI.DebugUIStepperHelper.RoundToPrecision(12345.0f, 100.0f);
Assert.AreEqual(12345.0f, result, 0.01f);
}
+
+ [TestCase(-5, ExpectedResult = 10)]
+ [TestCase(15, ExpectedResult = 15)]
+ [TestCase(25, ExpectedResult = 20)]
+ public int IntField_ValidateValue_ClampsToMinMax(int value)
+ {
+ var field = new DebugUI.IntField { min = () => 10, max = () => 20 };
+ return field.ValidateValue(value);
+ }
+
+ [TestCase(int.MinValue, ExpectedResult = int.MinValue)]
+ [TestCase(int.MaxValue, ExpectedResult = int.MaxValue)]
+ [TestCase(123456789, ExpectedResult = 123456789)]
+ public int IntField_ValidateValue_PreservesValueWithinFullRange(int value)
+ {
+ var field = new DebugUI.IntField { min = () => int.MinValue, max = () => int.MaxValue };
+ return field.ValidateValue(value);
+ }
+
+ [TestCase(5u, ExpectedResult = 10u)]
+ [TestCase(15u, ExpectedResult = 15u)]
+ [TestCase(25u, ExpectedResult = 20u)]
+ public uint UIntField_ValidateValue_ClampsToMinMax(uint value)
+ {
+ var field = new DebugUI.UIntField { min = () => 10u, max = () => 20u };
+ return field.ValidateValue(value);
+ }
+
+ [TestCase(0u, ExpectedResult = 0u)]
+ [TestCase(uint.MaxValue, ExpectedResult = uint.MaxValue)]
+ [TestCase(123456789u, ExpectedResult = 123456789u)]
+ public uint UIntField_ValidateValue_PreservesValueWithinFullRange(uint value)
+ {
+ var field = new DebugUI.UIntField { min = () => 0u, max = () => uint.MaxValue };
+ return field.ValidateValue(value);
+ }
+
+ [TestCase(-5f, ExpectedResult = 10f)]
+ [TestCase(15.5f, ExpectedResult = 15.5f)]
+ [TestCase(25f, ExpectedResult = 20f)]
+ public float FloatField_ValidateValue_ClampsToMinMax(float value)
+ {
+ var field = new DebugUI.FloatField { min = () => 10f, max = () => 20f };
+ return field.ValidateValue(value);
+ }
}
}
#endif
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/GPUDriven/GPUDrivenRenderingTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/GPUDriven/GPUDrivenRenderingTests.cs
index f44722274ff..24b71d0c93e 100644
--- a/Packages/com.unity.render-pipelines.core/Tests/Editor/GPUDriven/GPUDrivenRenderingTests.cs
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/GPUDriven/GPUDrivenRenderingTests.cs
@@ -1219,6 +1219,56 @@ SpeedTreeWindAsset CreateDummySpeedTreeWindAsset(params object[] args)
ShutdownGPUResidentDrawer();
dummyWindAsset = null;
}
+
+ [Test, ConditionalIgnore("IgnoreGfxAPI", "Graphics API Not Supported.")]
+ public void TestRendererReparentedUnderInactiveParentIsRemovedAndRestored()
+ {
+ InitializeGPUResidentDrawer();
+
+ var simpleDotsMat = new Material(Shader.Find("Unlit/SimpleDots"));
+ var activeParent = new GameObject("ActiveParent");
+ var inactiveParent = new GameObject("InactiveParent");
+ inactiveParent.SetActive(false);
+
+ var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
+ var renderer = cube.GetComponent();
+ renderer.material = simpleDotsMat;
+ cube.transform.SetParent(activeParent.transform);
+
+ var instanceIDs = new NativeArray(1, Allocator.TempJob);
+ instanceIDs[0] = renderer.GetEntityId();
+ var instances = new NativeArray(1, Allocator.TempJob);
+ instances[0] = InstanceHandle.Invalid;
+
+ m_GPUResidentDrawer.m_WorldProcessor.Update();
+ m_InstanceDataSystem.QueryRendererInstances(instanceIDs, instances);
+ Assert.IsTrue(instances[0].isValid, "Renderer under an active parent should be registered in GRD.");
+
+ cube.transform.SetParent(inactiveParent.transform);
+ Assert.IsTrue(cube.activeSelf);
+ Assert.IsFalse(cube.activeInHierarchy);
+ instances[0] = InstanceHandle.Invalid;
+
+ m_GPUResidentDrawer.m_WorldProcessor.Update();
+ m_InstanceDataSystem.QueryRendererInstances(instanceIDs, instances);
+ Assert.IsFalse(instances[0].isValid, "Renderer reparented under an inactive parent should be removed from GRD.");
+
+ cube.transform.SetParent(activeParent.transform);
+ instances[0] = InstanceHandle.Invalid;
+
+ m_GPUResidentDrawer.m_WorldProcessor.Update();
+ m_InstanceDataSystem.QueryRendererInstances(instanceIDs, instances);
+
+ Assert.IsTrue(instances[0].isValid, "Renderer reparented back under an active parent should be registered again.");
+
+ instances.Dispose();
+ instanceIDs.Dispose();
+ GameObject.DestroyImmediate(cube);
+ GameObject.DestroyImmediate(activeParent);
+ GameObject.DestroyImmediate(inactiveParent);
+ Object.DestroyImmediate(simpleDotsMat);
+ ShutdownGPUResidentDrawer();
+ }
}
}
#endif
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/BlockAllocatorTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/BlockAllocatorTests.cs
index 465169c0563..13c85fd5da2 100644
--- a/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/BlockAllocatorTests.cs
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/BlockAllocatorTests.cs
@@ -15,23 +15,30 @@ public void GrowAndAllocate_NotEnoughSpace_ShouldFail()
{
var allocator = new BlockAllocator();
allocator.Initialize(500);
- for (int i = 0; i < 50; i++)
+ try
{
- var a = allocator.Allocate(2);
- Assert.IsTrue(a.valid);
- }
+ for (int i = 0; i < 50; i++)
+ {
+ var a = allocator.Allocate(2);
+ Assert.IsTrue(a.valid);
+ }
- int oldCapacity;
- int newCapacity;
+ int oldCapacity;
+ int newCapacity;
- var alloc = allocator.GrowAndAllocate(500, 300, out oldCapacity, out newCapacity);
- Assert.IsFalse(alloc.valid);
+ var alloc = allocator.GrowAndAllocate(500, 300, out oldCapacity, out newCapacity);
+ Assert.IsFalse(alloc.valid);
- alloc = allocator.GrowAndAllocate(500, 600, out oldCapacity, out newCapacity);
- Assert.IsTrue(alloc.valid);
+ alloc = allocator.GrowAndAllocate(500, 600, out oldCapacity, out newCapacity);
+ Assert.IsTrue(alloc.valid);
- alloc = allocator.GrowAndAllocate(2, 600, out oldCapacity, out newCapacity);
- Assert.IsFalse(alloc.valid);
+ alloc = allocator.GrowAndAllocate(2, 600, out oldCapacity, out newCapacity);
+ Assert.IsFalse(alloc.valid);
+ }
+ finally
+ {
+ allocator.Dispose();
+ }
}
[Test]
@@ -39,16 +46,261 @@ public void GrowAndAllocate_NotEnoughSpaceMaxInt_ShouldFail()
{
var allocator = new BlockAllocator();
allocator.Initialize(int.MaxValue);
- var a = allocator.Allocate(int.MaxValue / 2);
+ try
+ {
+ var a = allocator.Allocate(int.MaxValue / 2);
+
+ int oldCapacity;
+ int newCapacity;
+
+ var alloc = allocator.GrowAndAllocate(3, int.MaxValue, out oldCapacity, out newCapacity);
+ Assert.IsTrue(alloc.valid);
+
+ alloc = allocator.GrowAndAllocate(int.MaxValue / 2, int.MaxValue, out oldCapacity, out newCapacity);
+ Assert.IsFalse(alloc.valid);
+ }
+ finally
+ {
+ allocator.Dispose();
+ }
+ }
+
+ [Test]
+ public void FreeAllocation_ShuffledSingleElementFrees_CoalescesToOneBlock()
+ {
+ const int count = 4096;
+ var allocator = new BlockAllocator();
+ allocator.Initialize(count);
+ try
+ {
+ var allocations = new BlockAllocator.Allocation[count];
+ for (int i = 0; i < count; i++)
+ {
+ allocations[i] = allocator.Allocate(1);
+ Assert.IsTrue(allocations[i].valid);
+ }
+
+ foreach (int i in ShuffledIndices(count, seed: 1234))
+ allocator.FreeAllocation(allocations[i]);
+
+ allocator.ValidateInvariants();
+ Assert.AreEqual(1, allocator.freeBlocks, "Shuffled frees should coalesce back to a single free block.");
+ Assert.AreEqual(count, allocator.freeElementsCount);
+ Assert.IsTrue(allocator.Allocate(count).valid, "The coalesced block should satisfy a full-capacity allocation.");
+ }
+ finally
+ {
+ allocator.Dispose();
+ }
+ }
+
+ [Test]
+ public void FreeAllocation_EveryOtherFree_MaxFragmentationThenFullCoalesce()
+ {
+ const int count = 1024;
+ var allocator = new BlockAllocator();
+ allocator.Initialize(count);
+ try
+ {
+ var allocations = new BlockAllocator.Allocation[count];
+ for (int i = 0; i < count; i++)
+ allocations[i] = allocator.Allocate(1);
+
+ for (int i = 0; i < count; i += 2)
+ allocator.FreeAllocation(allocations[i]);
+
+ allocator.ValidateInvariants();
+ Assert.AreEqual(count / 2, allocator.freeBlocks, "Non-adjacent frees should not coalesce.");
+
+ for (int i = 1; i < count; i += 2)
+ allocator.FreeAllocation(allocations[i]);
+
+ allocator.ValidateInvariants();
+ Assert.AreEqual(1, allocator.freeBlocks);
+ Assert.AreEqual(count, allocator.freeElementsCount);
+ }
+ finally
+ {
+ allocator.Dispose();
+ }
+ }
+
+ [Test]
+ public void FreeAllocation_MixedSizesShuffled_CoalescesAndReuses()
+ {
+ var allocator = new BlockAllocator();
+ allocator.Initialize(10000);
+ try
+ {
+ var random = new System.Random(5678);
+ var allocations = new System.Collections.Generic.List();
+ while (true)
+ {
+ var allocation = allocator.Allocate(random.Next(1, 18));
+ if (!allocation.valid)
+ break;
+ allocations.Add(allocation);
+ }
+
+ allocator.ValidateInvariants();
+
+ foreach (int i in ShuffledIndices(allocations.Count, seed: 42))
+ allocator.FreeAllocation(allocations[i]);
+
+ allocator.ValidateInvariants();
+ Assert.AreEqual(1, allocator.freeBlocks, "Mixed-size shuffled frees should coalesce back to a single free block.");
+ Assert.AreEqual(10000, allocator.freeElementsCount);
+
+ Assert.IsTrue(allocator.Allocate(10000).valid);
+ }
+ finally
+ {
+ allocator.Dispose();
+ }
+ }
+
+ [Test]
+ public void SplitAllocation_FreedPartsShuffled_Coalesce()
+ {
+ var allocator = new BlockAllocator();
+ allocator.Initialize(256);
+ try
+ {
+ var block = allocator.Allocate(64);
+ var parts = allocator.SplitAllocation(block, 64);
- int oldCapacity;
- int newCapacity;
+ foreach (int i in ShuffledIndices(parts.Length, seed: 99))
+ allocator.FreeAllocation(parts[i]);
- var alloc = allocator.GrowAndAllocate(3, int.MaxValue, out oldCapacity, out newCapacity);
- Assert.IsTrue(alloc.valid);
+ allocator.ValidateInvariants();
+ Assert.AreEqual(1, allocator.freeBlocks, "Freed split parts should coalesce with the remaining free space.");
+ Assert.AreEqual(256, allocator.freeElementsCount);
+ }
+ finally
+ {
+ allocator.Dispose();
+ }
+ }
+
+ [Test]
+ public void GrowAndAllocate_LastFreeListEntryIsNotTailBlock_GrowsEnough()
+ {
+ // The required growth must be computed from the free block adjacent to the capacity end, not from
+ // whichever block happens to be last in the free list.
+ var allocator = new BlockAllocator();
+ allocator.Initialize(100);
+ try
+ {
+ var a = allocator.Allocate(60);
+ var b = allocator.Allocate(40);
+ Assert.IsTrue(a.valid && b.valid);
+ allocator.FreeAllocation(a); // free list holds only the interior block [0, 60); the tail is fully allocated
+
+ var alloc = allocator.GrowAndAllocate(200, 1000, out _, out _);
+ allocator.ValidateInvariants();
+ Assert.IsTrue(alloc.valid);
+ Assert.AreEqual(200, alloc.block.count);
+ }
+ finally
+ {
+ allocator.Dispose();
+ }
+ }
+
+ [Test]
+ public void FreeAllocation_ManyShuffledFrees_CompletesQuickly()
+ {
+ const int count = 100000;
+ var allocator = new BlockAllocator();
+ allocator.Initialize(count);
+ try
+ {
+ var allocations = new BlockAllocator.Allocation[count];
+ for (int i = 0; i < count; i++)
+ allocations[i] = allocator.Allocate(1);
+
+ var stopwatch = System.Diagnostics.Stopwatch.StartNew();
+ foreach (int i in ShuffledIndices(count, seed: 7))
+ allocator.FreeAllocation(allocations[i]);
+ stopwatch.Stop();
+
+ allocator.ValidateInvariants();
+ Assert.AreEqual(1, allocator.freeBlocks);
+ // O(n^2) coalescing took minutes at this size; the bound is generous to stay robust on slow agents.
+ Assert.Less(stopwatch.ElapsedMilliseconds, 5000, "Mass freeing regressed to super-linear behavior.");
+ }
+ finally
+ {
+ allocator.Dispose();
+ }
+ }
+
+ [Test]
+ public void Allocate_ZeroElementsFromZeroCapacityAllocator_ReturnsValidEmptyAllocation()
+ {
+ var allocator = new BlockAllocator();
+ allocator.Initialize(0);
+ try
+ {
+ var allocation = allocator.Allocate(0);
+ Assert.IsTrue(allocation.valid, "A zero-element allocation should succeed on an empty, growable allocator.");
+ Assert.AreEqual(0, allocation.block.count);
+
+ var grown = allocator.GrowAndAllocate(0, out _, out _);
+ Assert.IsTrue(grown.valid, "GrowAndAllocate of zero elements should succeed on an empty allocator.");
+
+ Assert.IsFalse(allocator.Allocate(1).valid);
+
+ allocator.FreeAllocation(allocation);
+ allocator.FreeAllocation(grown);
+ allocator.ValidateInvariants();
+ }
+ finally
+ {
+ allocator.Dispose();
+ }
+ }
+
+ [Test]
+ public void Allocate_ZeroElements_ReturnsValidEmptyAllocation()
+ {
+ var allocator = new BlockAllocator();
+ allocator.Initialize(64);
+ try
+ {
+ var allocation = allocator.Allocate(0);
+ Assert.IsTrue(allocation.valid, "A zero-element allocation should succeed like any other.");
+ Assert.AreEqual(0, allocation.block.count);
+ Assert.AreEqual(64, allocator.freeElementsCount, "A zero-element allocation should not consume space.");
+ Assert.AreEqual(1, allocator.freeBlocks);
+
+ allocator.FreeAllocation(allocation);
+ allocator.ValidateInvariants();
+ Assert.AreEqual(64, allocator.freeElementsCount);
+ Assert.AreEqual(1, allocator.freeBlocks);
+
+ Assert.IsTrue(allocator.Allocate(64).valid);
+ }
+ finally
+ {
+ allocator.Dispose();
+ }
+ }
+
+ static int[] ShuffledIndices(int count, int seed)
+ {
+ var indices = new int[count];
+ for (int i = 0; i < count; i++)
+ indices[i] = i;
+
+ var random = new System.Random(seed);
+ for (int i = count - 1; i > 0; i--)
+ {
+ int j = random.Next(i + 1);
+ (indices[i], indices[j]) = (indices[j], indices[i]);
+ }
- alloc = allocator.GrowAndAllocate(int.MaxValue / 2, int.MaxValue, out oldCapacity, out newCapacity);
- Assert.IsFalse(alloc.valid);
+ return indices;
}
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md
index c9a62c95c4e..96783b8da15 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md
@@ -16,7 +16,7 @@ Use the **Flares** settings to control regular flares, reversed flares and warpe
| ----------------------- | ----------------- | ------------------------------------------------------------ |
| **Regular Multiplier** | | Set the strength of regular flares. If the value is 0, HDRP doesn't calculate or render regular flares. The default is 1. |
| **Reversed Multiplier** | | Set the strength of reversed flares. If the value is 0, HDRP doesn't calculate or render reversed flares. The default is 1. |
-| **Warped Multipler** | | Set the strength of warped flares. If the value is 0, HDRP doesn't calculate or render warped flares. The default is 1. |
+| **Warped Multiplier** | | Set the strength of warped flares. If the value is 0, HDRP doesn't calculate or render warped flares. The default is 1. |
| | **Scale** | Scale the width (**x**) and height (**y**) of warped flares. The defaults are 1. This property only appears if you open the **More** (ā®) menu and select **Show Additional Properties**. |
| **Samples** | | Set the number of times HDRP repeats the regular, reversed and warped flares. The range is 1 through 3. The default is 1. Increasing **Samples** has a big impact on performance. |
| | **Sample Dimmer** | Set the strength of the lens flares HDRP adds if you set **Samples** to 2 or 3. The higher the value, the less intense the flares. This property only appears if you open the **More** (ā®) menu and select **Show Additional Properties**. |
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCameraFrameHistoryType.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCameraFrameHistoryType.cs
index 331874f6975..a2e3cbab3c1 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCameraFrameHistoryType.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCameraFrameHistoryType.cs
@@ -69,6 +69,8 @@ public enum HDCameraFrameHistoryType
PathTracingVolumetricFogDenoised,
/// Variable rate shading.
Vrs,
+ /// Alpha channel history used to accumulate the upscaled alpha alongside color-only upscalers (DLSS, FSR2, STP).
+ AlphaUpscale,
// For retro compatibility
/// Main path tracing output buffer. It is recommended to use the PathTracingOutput enum value instead.
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs
index a37771f8ac3..893abf58e51 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs
@@ -622,11 +622,50 @@ public bool PerformsAntiAliasing()
return null;
}
+ TextureHandle DoAlphaUpscaling(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle preUpscaleColor, TextureHandle upscaledColor,
+ in TextureHandle depthBuffer, in TextureHandle motionVectors, in TextureHandle stencilBuffer, bool isTemporalUpscaler)
+ {
+ AlphaUpscaler.Config config = default;
+ config.preUpscaleAlpha = preUpscaleColor;
+ config.upscaledColor = upscaledColor;
+ config.preUpscaleSize = new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight);
+ // HDRP color textures are allocated at the maximum RTHandle size and rendered into a
+ // viewport-sized sub-rect; with hardware DRS the allocation itself is scaled as well.
+ var preUpscalePhysicalSize = new Vector2Int(RTHandles.maxWidth, RTHandles.maxHeight);
+ if (DynamicResolutionHandler.instance.HardwareDynamicResIsEnabled())
+ preUpscalePhysicalSize = DynamicResolutionHandler.instance.ApplyScalesOnSize(preUpscalePhysicalSize);
+ config.preUpscalePhysicalSize = preUpscalePhysicalSize;
+ config.postUpscaleSize = new Vector2Int(Mathf.RoundToInt(hdCamera.finalViewport.width), Mathf.RoundToInt(hdCamera.finalViewport.height));
+ config.jitter = new Vector2(hdCamera.taaJitter.x, hdCamera.taaJitter.y);
+ config.enableTexArray = TextureXR.useTexArray;
+ config.viewCount = hdCamera.viewCount;
+
+ // Spatial upscalers render without jitter, so there is no per-frame phase
+ // variance to accumulate away; the default config (no motion vectors, depth,
+ // stencil or history) runs the spatial-only reconstruction.
+ if (isTemporalUpscaler)
+ {
+ bool validHistory = GrabPostProcessHistoryTextures(hdCamera, HDCameraFrameHistoryType.AlphaUpscale, "Alpha Upscale History", GraphicsFormat.R16_SFloat, out var prevAlphaHistory, out var nextAlphaHistory);
+
+ config.motionVectors = motionVectors;
+ config.cameraDepth = depthBuffer;
+ config.reactiveMask = stencilBuffer;
+ config.stencilExcludeBit = (int)StencilUsage.ExcludeFromTUAndAA;
+ config.prevAlphaHistory = renderGraph.ImportTexture(prevAlphaHistory);
+ config.nextAlphaHistory = renderGraph.ImportTexture(nextAlphaHistory);
+ config.historyBlendFactor = (validHistory && !hdCamera.resetPostProcessingHistory) ? AlphaUpscaler.defaultHistoryBlendFactor : 0.0f;
+ }
+
+ return AlphaUpscaler.Execute(renderGraph, ref config);
+ }
+
TextureHandle DoUpscalingAndAntiAliasing(RenderGraph renderGraph, HDCamera hdCamera, CurrentUpsamplerData upsamplerDataData,
TextureHandle source, in TextureHandle depthBuffer, in TextureHandle motionVectors, in TextureHandle stencilBuffer, in TextureHandle depthBufferMipChain)
{
bool taaUsesCAS = hdCamera.antialiasing == HDAdditionalCameraData.AntialiasingMode.TemporalAntialiasing && hdCamera.taaSharpenMode == HDAdditionalCameraData.TAASharpenMode.ContrastAdaptiveSharpening;
+ TextureHandle preUpscaleColor = source;
+
source = upsamplerDataData switch
{
#if ENABLE_UPSCALER_FRAMEWORK
@@ -648,6 +687,23 @@ TextureHandle DoUpscalingAndAntiAliasing(RenderGraph renderGraph, HDCamera hdCam
_ => source
};
+ // Advanced upscalers (including IUpscalers without alpha upscaling support) only upscale the RGB channels
+ // and leave the output alpha undefined, so rebuild it here from the pre-upscale alpha.
+ if (upsamplerDataData.isAdvancedUpsampler && source != preUpscaleColor && PostProcessEnableAlpha(hdCamera))
+ {
+ bool supportsAlphaUpscaling = false;
+ bool isTemporalUpscaler = true;
+#if ENABLE_UPSCALER_FRAMEWORK
+ if (upsamplerDataData.advancedUpsampler == AdvancedUpscalers.IUpscaler)
+ {
+ supportsAlphaUpscaling = upscaling.activeUpscaler.supportsAlphaUpscaling;
+ isTemporalUpscaler = upscaling.activeUpscaler.isTemporal;
+ }
+#endif
+ if (!supportsAlphaUpscaling)
+ source = DoAlphaUpscaling(renderGraph, hdCamera, preUpscaleColor, source, depthBuffer, motionVectors, stencilBuffer, isTemporalUpscaler);
+ }
+
SetCurrentResolutionGroup(renderGraph, hdCamera, ResolutionGroup.AfterDynamicResUpscale);
if (hdCamera.RequiresCameraJitter())
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs
index 035954b92f3..bdf303138c5 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs
@@ -379,7 +379,7 @@ void RecordRenderGraph(RenderRequest renderRequest,
// Copy and rescale depth buffer for XR devices
if (hdCamera.xr.enabled && hdCamera.xr.copyDepth && depthBackBuffer.IsValid())
- CopyDepth(m_RenderGraph, hdCamera, prepassOutput.resolvedDepthBuffer, depthBackBuffer, true);
+ CopyDepth(m_RenderGraph, prepassOutput.resolvedDepthBuffer, depthBackBuffer, true);
if (m_CurrentDebugDisplaySettings.data.historyBuffersView != -1)
{
@@ -746,7 +746,7 @@ class CopyXRDepthPassData
public int passIndex;
}
- void CopyDepth(RenderGraph renderGraph, HDCamera hdCamera, in TextureHandle depthBuffer, in TextureHandle output, bool copyForXR)
+ void CopyDepth(RenderGraph renderGraph, in TextureHandle depthBuffer, in TextureHandle output, bool copyForXR)
{
string name = copyForXR ? "Copy XR Depth" : "Copy Depth";
var profileID = copyForXR ? HDProfileId.XRDepthCopy : HDProfileId.DuplicateDepthBuffer;
@@ -757,8 +757,7 @@ void CopyDepth(RenderGraph renderGraph, HDCamera hdCamera, in TextureHandle dept
builder.UseTexture(passData.depthBuffer, AccessFlags.Read);
passData.output = output;
builder.SetRenderAttachmentDepth(output, AccessFlags.Write);
- passData.blitScaleBias = copyForXR ? new Vector2(hdCamera.actualWidth / hdCamera.finalViewport.width, hdCamera.actualHeight / hdCamera.finalViewport.height)
- : RTHandles.rtHandleProperties.rtHandleScale;
+ passData.blitScaleBias = RTHandles.rtHandleProperties.rtHandleScale;
passData.flipY = copyForXR;
passData.passIndex = renderGraph.GetTextureDesc(depthBuffer).msaaSamples != MSAASamples.None ? 1 : 0;
Debug.Assert(!(copyForXR && passData.passIndex != 0), "MSAA depth copies do not support XR scaling and Y-flipping.");
@@ -1748,7 +1747,7 @@ TransparentPrepassOutput RenderTransparentPrepass(RenderGraph renderGraph, Culli
renderQueueRange: GetTransparentRenderQueueRange(hdCamera, false)));
// Copy depth buffer for refraction
- CopyDepth(renderGraph, hdCamera, prepassOutput.depthBuffer, output.depthBufferPreRefraction, false);
+ CopyDepth(renderGraph, prepassOutput.depthBuffer, output.depthBufferPreRefraction, false);
if (hasWater)
{
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs
index e19e770d276..e6c72acbb2e 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs
@@ -339,10 +339,12 @@ Vector2Int cameraRTSize
get
{
var targetTexture = m_Camera.targetTexture;
- return targetTexture == null ? new Vector2Int(Screen.width, Screen.height) : new Vector2Int(targetTexture.width, targetTexture.height);
+ return targetTexture == null ? screenRTSize : new Vector2Int(targetTexture.width, targetTexture.height);
}
}
+ Vector2Int screenRTSize => RenderingUtils.GetScreenBackbufferSize(m_Camera);
+
// Snap camera position to pixels using Camera.worldToCameraMatrix.
void PixelSnap()
{
@@ -438,7 +440,7 @@ void OnGUI()
}
var targetTexture = m_Camera.targetTexture;
- Vector2Int rtSize = targetTexture == null ? new Vector2Int(Screen.width, Screen.height) : new Vector2Int(targetTexture.width, targetTexture.height);
+ Vector2Int rtSize = targetTexture == null ? screenRTSize : new Vector2Int(targetTexture.width, targetTexture.height);
if (rtSize.x < refResolutionX || rtSize.y < refResolutionY)
{
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs
index 5cf40956a59..84df47cda02 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs
@@ -50,7 +50,7 @@ public void Render(RenderGraph graph, ContextContainer frameData, int batchIndex
builder.SetRenderAttachment(universal2DResourceData.normalsTexture[batchIndex], 0);
// Depth needed for sprite mask stencil or z test for 3d meshes
- if (commonResourceData.activeDepthTexture.IsValid())
+ if (Renderer2D.IsDepthUsageAllowed(frameData, rendererData) && commonResourceData.activeDepthTexture.IsValid())
{
var depth = universal2DResourceData.normalsDepth.IsValid() ? universal2DResourceData.normalsDepth : commonResourceData.activeDepthTexture;
builder.SetRenderAttachmentDepth(depth);
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs
index 096996b545c..b364a1f7af9 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs
@@ -202,6 +202,26 @@ internal static bool IsDepthUsageAllowed(ContextContainer frameData, Renderer2DD
return allowDepth;
}
+ static bool ShouldImportBackBufferDepth(ContextContainer frameData, Renderer2DData rendererData, bool createColorTexture)
+ {
+ if (IsDepthUsageAllowed(frameData, rendererData))
+ return true;
+
+ // OpenGL binds the default framebuffer's depth with its color even when no pass uses it, so it must still be cleared (UUM-159093)
+ var deviceType = SystemInfo.graphicsDeviceType;
+ if (deviceType != GraphicsDeviceType.OpenGLES3 && deviceType != GraphicsDeviceType.OpenGLCore)
+ return false;
+
+ // Only when the 2D passes draw straight into the back buffer, since they are what attach and clear it
+ UniversalCameraData cameraData = frameData.Get();
+ bool isBackBuffer = cameraData.targetTexture == null && !createColorTexture;
+#if ENABLE_VR && ENABLE_XR_MODULE
+ isBackBuffer &= !cameraData.xr.enabled;
+#endif
+
+ return isBackBuffer && Graphics.backBufferHasDepthStencil;
+ }
+
private bool IsPixelPerfectCameraEnabled(UniversalCameraData cameraData, out PixelPerfectCamera ppc)
{
ppc = null;
@@ -357,11 +377,8 @@ ImportResourceSummary GetImportResourceSummary(RenderGraph renderGraph, Universa
// pending Screen.SetMSAASamples request hasn't been applied yet (deferred reallocation).
int numSamples = Screen.currentBackbufferMSAASamples;
- //NOTE: Careful what you use here as many of the properties bake-in the camera rect so for example
- //cameraData.cameraTargetDescriptor.width is the width of the rectangle but not the actual render target
- //same with cameraData.camera.pixelWidth
- output.importInfo.width = Screen.width;
- output.importInfo.height = Screen.height;
+ output.importInfo.width = cameraData.backbufferWidth;
+ output.importInfo.height = cameraData.backbufferHeight;
output.importInfo.volumeDepth = 1;
output.importInfo.msaaSamples = numSamples;
output.importInfo.format = cameraData.cameraTargetDescriptor.graphicsFormat;
@@ -528,10 +545,7 @@ void CreateResources(RenderGraph renderGraph)
depthDescriptor.depthStencilFormat = CoreUtils.GetDefaultDepthStencilFormat();
RenderingUtils.ReAllocateHandleIfNeeded(ref s_RenderGraphCameraDepthHandle, depthDescriptor, FilterMode.Point, TextureWrapMode.Clamp, name: "_CameraDepthAttachment");
- commonResourceData.activeDepthID = ActiveID.Camera;
}
- else
- commonResourceData.activeDepthID = ActiveID.BackBuffer;
}
else // Overlay camera
{
@@ -545,12 +559,14 @@ void CreateResources(RenderGraph renderGraph)
m_CreateDepthTexture = baseRenderer.m_CreateDepthTexture;
commonResourceData.activeColorID = m_CreateColorTexture ? ActiveID.Camera : ActiveID.BackBuffer;
- commonResourceData.activeDepthID = m_CreateDepthTexture ? ActiveID.Camera : ActiveID.BackBuffer;
}
+ // An intermediate color target is never paired with the back buffer depth
+ commonResourceData.activeDepthID = m_CreateDepthTexture || m_CreateColorTexture ? ActiveID.Camera : ActiveID.BackBuffer;
+
// Report this camera's real back buffer MSAA need; a 2D camera renders directly to it only when
// no intermediate color texture is created (m_CreateColorTexture == false).
- ReportRealBackbufferMSAA(cameraData, m_CreateColorTexture);
+ ReportDisplayTargetMSAA(cameraData, m_CreateColorTexture);
ImportResourceSummary importSummary = GetImportResourceSummary(renderGraph, cameraData);
@@ -588,7 +604,7 @@ void CreateResources(RenderGraph renderGraph)
commonResourceData.backBufferColor = renderGraph.ImportTexture(m_RenderGraphBackbufferColorHandle, importSummary.importInfo, importSummary.backBufferColorParams);
- if (IsDepthUsageAllowed(frameData, m_Renderer2DData))
+ if (ShouldImportBackBufferDepth(frameData, m_Renderer2DData, m_CreateColorTexture))
{
if (m_RenderGraphBackbufferDepthHandle == null)
{
@@ -773,7 +789,7 @@ void CreateOffscreenUITexture(RenderGraph renderGraph, in RenderTextureDescripto
UniversalResourceData resourceData = frameData.Get();
UniversalCameraData cameraData = frameData.Get();
TextureDesc textureDesc = new TextureDesc(descriptor);
- DrawScreenSpaceUIPass.ConfigureOffscreenUITextureDesc(ref textureDesc);
+ DrawScreenSpaceUIPass.ConfigureOffscreenUITextureDesc(ref textureDesc, cameraData);
RenderingUtils.ReAllocateHandleIfNeeded(ref s_OffscreenUIColorHandle, textureDesc, name: "_OverlayUITexture");
// Clear the texture to avoid stale data from previous frames
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/AlphaUpscaleUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/AlphaUpscaleUtils.cs
new file mode 100644
index 00000000000..49c315e56c3
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/AlphaUpscaleUtils.cs
@@ -0,0 +1,60 @@
+using UnityEngine.Rendering.RenderGraphModule;
+
+namespace UnityEngine.Rendering.Universal
+{
+ ///
+ /// Wires the core AlphaUpscaler into URP: it runs right after a color-only upscaler
+ /// and rebuilds the output alpha from the pre-upscale alpha, so the
+ /// alpha channel survives upscalers that only reconstruct the color channels.
+ ///
+ internal static class AlphaUpscaleUtils
+ {
+ internal static void Execute(RenderGraph renderGraph, UniversalCameraData cameraData, UniversalResourceData resourceData,
+ TextureHandle preUpscaleColor, bool isTemporalUpscaler, Vector2Int preUpscaleSize, Vector2Int postUpscaleSize, Vector2 jitter,
+ TextureHandle reactiveMask = default, bool reactiveMaskIsStencil = false)
+ {
+ if (!cameraData.isAlphaOutputEnabled)
+ return;
+
+ // The upscaler may have skipped this frame (e.g. unmet runtime requirements).
+ var upscaledColor = resourceData.cameraColor;
+ if (!upscaledColor.IsValid() || upscaledColor == preUpscaleColor)
+ return;
+
+ AlphaUpscaler.Config config = default;
+ config.reactiveMask = reactiveMask;
+ config.stencilExcludeBit = reactiveMaskIsStencil ? 0x1 : 0;
+ config.preUpscaleAlpha = preUpscaleColor;
+ config.upscaledColor = upscaledColor;
+ config.preUpscaleSize = preUpscaleSize;
+ // URP allocates the camera color at exactly the rendered size (render scale included, and
+ // hardware DRS scales the allocation itself), so preUpscalePhysicalSize keeps its default.
+ config.postUpscaleSize = postUpscaleSize;
+ config.jitter = jitter;
+ config.enableTexArray = cameraData.xr.enabled && cameraData.xr.singlePassEnabled;
+ config.viewCount = cameraData.xr.enabled ? cameraData.xr.viewCount : 1;
+
+ // Setup temporal inputs.
+ var history = cameraData.alphaUpscaleHistory;
+ if (isTemporalUpscaler && history != null &&
+ resourceData.motionVectorColor.IsValid() && resourceData.cameraDepthTexture.IsValid())
+ {
+ int eyeIndex = (cameraData.xr.enabled && !cameraData.xr.singlePassEnabled) ? cameraData.xr.multipassId : 0;
+ RTHandle prevAlphaHistory = history.GetPreviousTexture(eyeIndex);
+ RTHandle nextAlphaHistory = history.GetCurrentTexture(eyeIndex);
+
+ if (prevAlphaHistory != null && nextAlphaHistory != null)
+ {
+ config.motionVectors = resourceData.motionVectorColor;
+ config.cameraDepth = resourceData.cameraDepthTexture;
+ config.prevAlphaHistory = renderGraph.ImportTexture(prevAlphaHistory);
+ config.nextAlphaHistory = renderGraph.ImportTexture(nextAlphaHistory);
+ config.historyBlendFactor = (history.validHistory && !cameraData.resetHistory)
+ ? AlphaUpscaler.defaultHistoryBlendFactor : 0.0f;
+ }
+ }
+
+ resourceData.cameraColor = AlphaUpscaler.Execute(renderGraph, ref config);
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/AlphaUpscaleUtils.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/AlphaUpscaleUtils.cs.meta
new file mode 100644
index 00000000000..4252d2eb04a
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/AlphaUpscaleUtils.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 5d3c6e12f49d4d4bb66a294156503e02
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs b/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs
index 6d7e88de887..9ed2bbdb758 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs
@@ -357,7 +357,8 @@ out int wordsPerTile
{
worldToViews = worldToViews,
lights = localLights,
- minMaxZs = minMaxZs.GetSubArray(0, localLightCount * viewCount)
+ minMaxZs = minMaxZs.GetSubArray(0, localLightCount * viewCount),
+ near = nearClipPlane
};
// Innerloop batch count of 32 is not special, just a handwavy amount to not have too much scheduling overhead nor too little parallelism.
var lightMinMaxZHandle = lightMinMaxZJob.ScheduleParallel(localLightCount * viewCount, 32, new JobHandle());
@@ -369,7 +370,8 @@ out int wordsPerTile
worldToViews = worldToViews,
reflectionProbes = probes,
reflectionProbeRotation = reflectionProbeRotation,
- minMaxZs = minMaxZs.GetSubArray(localLightCount * viewCount, reflectionProbeCount * viewCount)
+ minMaxZs = minMaxZs.GetSubArray(localLightCount * viewCount, reflectionProbeCount * viewCount),
+ near = nearClipPlane
};
var reflectionProbeMinMaxZHandle = reflectionProbeMinMaxZJob.ScheduleParallel(reflectionProbeCount * viewCount, 32, lightMinMaxZHandle);
@@ -413,6 +415,7 @@ out int wordsPerTile
viewToViewportScaleBiases = new Fixed2(viewToViewportScaleBias0, viewToViewportScaleBias1),
tileCount = tileResolution,
near = nearClipPlane,
+ far = farClipPlane,
isOrthographic = isOrthographic
};
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs
index 48f6eed9f91..9c8ce063f53 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs
@@ -190,6 +190,10 @@ internal Matrix4x4 GetGPUProjectionMatrix(bool renderIntoTexture, int viewIndex
public RenderTextureDescriptor cameraTargetDescriptor;
internal RenderTargetInfo backbufferColor;
internal RenderTargetInfo backbufferDepth;
+
+ internal int backbufferWidth => backbufferColor.width;
+ internal int backbufferHeight => backbufferColor.height;
+
internal Rect pixelRect;
internal bool useScreenCoordOverride;
internal Vector4 screenSizeOverride;
@@ -607,6 +611,11 @@ internal bool IsSTPEnabled()
///
internal StpHistory stpHistory;
+ ///
+ /// Post-upscale alpha history for the alpha upscale pass that runs after color-only upscalers.
+ ///
+ internal AlphaUpscaleHistory alphaUpscaleHistory;
+
// TAA settings.
internal TemporalAA.Settings taaSettings;
@@ -693,6 +702,7 @@ public override void Reset()
backgroundColor = Color.black;
taaHistory = null;
stpHistory = null;
+ alphaUpscaleHistory = null;
taaSettings = default;
subpixelJitter = default;
baseCamera = null;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/History/AlphaUpscaleHistory.cs b/Packages/com.unity.render-pipelines.universal/Runtime/History/AlphaUpscaleHistory.cs
new file mode 100644
index 00000000000..283ff527621
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/History/AlphaUpscaleHistory.cs
@@ -0,0 +1,78 @@
+using UnityEngine.Experimental.Rendering;
+
+namespace UnityEngine.Rendering.Universal
+{
+ ///
+ /// Double-buffered post-upscale alpha history consumed by the alpha upscale pass (core AlphaUpscaler).
+ ///
+ internal sealed class AlphaUpscaleHistory : CameraHistoryItem
+ {
+ // One id per eye for XR multi-pass rendering.
+ int[] m_Ids = new int[2];
+ static readonly string[] k_Names = { "AlphaUpscaleHistory0", "AlphaUpscaleHistory1" };
+
+ Hash128 m_DescKey;
+
+ // The frame the textures were (re)allocated on. XR multi-pass calls Update once per eye
+ // within the same frame; tracking the frame keeps the history invalid for both eye passes
+ // of the allocation frame, not just the one that performed the allocation.
+ int m_AllocFrameIndex = -1;
+
+ // False for the whole frame of a (re)allocation: the previous-frame content is undefined.
+ internal bool validHistory { get; private set; }
+
+ public override void OnCreate(BufferedRTHandleSystem owner, uint typeId)
+ {
+ base.OnCreate(owner, typeId);
+ m_Ids[0] = MakeId(0);
+ m_Ids[1] = MakeId(1);
+ }
+
+ internal RTHandle GetCurrentTexture(int eyeIndex = 0) => GetCurrentFrameRT(m_Ids[eyeIndex]);
+ internal RTHandle GetPreviousTexture(int eyeIndex = 0) => GetPreviousFrameRT(m_Ids[eyeIndex]);
+
+ public override void Reset()
+ {
+ for (int i = 0; i < m_Ids.Length; i++)
+ ReleaseHistoryFrameRT(m_Ids[i]);
+ validHistory = false;
+ }
+
+ internal void Update(UniversalCameraData cameraData, bool xrMultipassEnabled)
+ {
+ if (cameraData.pixelWidth <= 0 || cameraData.pixelHeight <= 0)
+ {
+ validHistory = false;
+ return;
+ }
+
+ // The history lives at the post-upscale resolution. Base the descriptor on the camera
+ // target so the XR texture dimension carries over.
+ var desc = cameraData.cameraTargetDescriptor;
+ desc.width = cameraData.pixelWidth;
+ desc.height = cameraData.pixelHeight;
+ desc.graphicsFormat = GraphicsFormat.R16_SFloat;
+ desc.depthStencilFormat = GraphicsFormat.None;
+ desc.mipCount = 0;
+ desc.msaaSamples = 1;
+ desc.enableRandomWrite = true;
+ // The history lives at the fixed post-upscale resolution.
+ desc.useDynamicScale = false;
+
+ var descKey = Hash128.Compute(ref desc);
+ if (descKey != m_DescKey && GetCurrentTexture() != null)
+ Reset();
+
+ if (GetCurrentTexture() == null)
+ {
+ AllocHistoryFrameRT(m_Ids[0], 2, ref desc, k_Names[0]);
+ if (xrMultipassEnabled)
+ AllocHistoryFrameRT(m_Ids[1], 2, ref desc, k_Names[1]);
+ m_DescKey = descKey;
+ m_AllocFrameIndex = Time.frameCount;
+ }
+
+ validHistory = Time.frameCount != m_AllocFrameIndex;
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/History/AlphaUpscaleHistory.cs.meta b/Packages/com.unity.render-pipelines.universal/Runtime/History/AlphaUpscaleHistory.cs.meta
new file mode 100644
index 00000000000..a13e53a83f0
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/History/AlphaUpscaleHistory.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: dddb68852f1a4baf8d7a52726983af85
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs
index c60285dde51..fe7b6fb86c8 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ColorGradingLutPass.cs
@@ -13,8 +13,8 @@ public partial class ColorGradingLutPass : ScriptableRenderPass
{
const string k_InternalColorLutName = "_InternalColorGradingLut";
- readonly Material m_LutBuilderLdr;
- readonly Material m_LutBuilderHdr;
+ readonly PostProcessMaterial m_LutBuilderLdr;
+ readonly PostProcessMaterial m_LutBuilderHdr;
internal readonly GraphicsFormat m_HdrLutFormat;
internal readonly GraphicsFormat m_LdrLutFormat;
@@ -32,8 +32,8 @@ public ColorGradingLutPass(RenderPassEvent evt, PostProcessData data)
profilingSampler = new ProfilingSampler("Blit Color LUT");
renderPassEvent = evt;
- m_LutBuilderLdr = PostProcessUtils.LoadShader(data.shaders.lutBuilderLdrPS, passName);
- m_LutBuilderHdr = PostProcessUtils.LoadShader(data.shaders.lutBuilderHdrPS, passName);
+ m_LutBuilderLdr = new PostProcessMaterial(data.shaders.lutBuilderLdrPS, passName);
+ m_LutBuilderHdr = new PostProcessMaterial(data.shaders.lutBuilderHdrPS, passName);
// Warm up lut format as IsFormatSupported adds GC pressure...
// UUM-41070: We require `Linear | Render` but with the deprecated FormatUsage this was checking `Blend`
@@ -244,6 +244,9 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, out Te
UniversalCameraData cameraData = frameData.Get();
UniversalPostProcessingData postProcessingData = frameData.Get();
+ bool hdrGrading = postProcessingData.gradingMode == ColorGradingMode.HighDynamicRange;
+ (hdrGrading ? m_LutBuilderHdr : m_LutBuilderLdr).Validate();
+
this.ConfigureDescriptor(in postProcessingData, out var lutDesc, out var filterMode);
internalColorLut = UniversalRenderer.CreateRenderGraphTexture(renderGraph, lutDesc, k_InternalColorLutName, true, filterMode);
@@ -253,11 +256,11 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, out Te
passData.internalColorLut = internalColorLut;
builder.SetRenderAttachment(internalColorLut, 0, AccessFlags.WriteAll);
- passData.lutBuilderLdr = m_LutBuilderLdr;
- passData.lutBuilderHdr = m_LutBuilderHdr;
+ passData.lutBuilderLdr = m_LutBuilderLdr.material;
+ passData.lutBuilderHdr = m_LutBuilderHdr.material;
passData.allowColorGradingACESHDR = m_AllowColorGradingACESHDR;
passData.lutSize = postProcessingData.lutSize;
- passData.hdrGrading = postProcessingData.gradingMode == ColorGradingMode.HighDynamicRange;
+ passData.hdrGrading = hdrGrading;
// TODO RENDERGRAPH: culling? force culling off for testing
builder.AllowPassCulling(false);
@@ -287,8 +290,8 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
///
public void Cleanup()
{
- CoreUtils.Destroy(m_LutBuilderLdr);
- CoreUtils.Destroy(m_LutBuilderHdr);
+ m_LutBuilderLdr.Dispose();
+ m_LutBuilderHdr.Dispose();
}
// Precomputed shader ids to same some CPU cycles (mostly affects mobile)
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawScreenSpaceUIPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawScreenSpaceUIPass.cs
index e66b577a317..1a1186f9bb4 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawScreenSpaceUIPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawScreenSpaceUIPass.cs
@@ -61,12 +61,12 @@ internal void Setup(UniversalCameraData cameraData)
///
/// Get a descriptor for the required color texture for offscreen UI pass.
///
- internal static void ConfigureOffscreenUITextureDesc(ref TextureDesc textureDesc)
+ internal static void ConfigureOffscreenUITextureDesc(ref TextureDesc textureDesc, UniversalCameraData cameraData)
{
textureDesc.format = GraphicsFormat.R8G8B8A8_SRGB;
textureDesc.depthBufferBits = 0;
- textureDesc.width = Screen.width;
- textureDesc.height = Screen.height;
+ textureDesc.width = cameraData.backbufferWidth;
+ textureDesc.height = cameraData.backbufferHeight;
}
///
@@ -249,7 +249,7 @@ internal void RenderOffscreen(RenderGraph renderGraph, ContextContainer frameDat
{
UniversalCameraData cameraData = frameData.Get();
RenderTextureDescriptor depthDescriptor = cameraData.cameraTargetDescriptor;
- ConfigureDepthDescriptor(ref depthDescriptor, depthStencilFormat, Screen.width, Screen.height);
+ ConfigureDepthDescriptor(ref depthDescriptor, depthStencilFormat, cameraData.backbufferWidth, cameraData.backbufferHeight);
TextureHandle depthBuffer = UniversalRenderer.CreateRenderGraphTexture(renderGraph, depthDescriptor, "_OverlayUITexture_Depth", false);
// Render uGUI and UIToolkit overlays
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs
index ca7a42068c0..ecb001d4f8a 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs
@@ -103,8 +103,8 @@ private static void ExecutePass(RasterCommandBuffer cmd, PassData data, RTHandle
if (cameraData.xr.enabled)
isRenderToBackBufferTarget = new RenderTargetIdentifier(destination.nameID, 0, CubemapFace.Unknown, -1) == new RenderTargetIdentifier(cameraData.xr.renderTarget, 0, CubemapFace.Unknown, -1);
#endif
- var pixelRect = data.useFullScreenViewport ? new Rect(0f, 0f, Screen.width, Screen.height) : cameraData.pixelRect;
- RenderingUtils.SetupOffscreenUIViewportParams(data.blitMaterialData.material, ref pixelRect, isRenderToBackBufferTarget);
+ var pixelRect = data.useFullScreenViewport ? new Rect(0f, 0f, cameraData.backbufferWidth, cameraData.backbufferHeight) : cameraData.pixelRect;
+ RenderingUtils.SetupOffscreenUIViewportParams(cameraData, data.blitMaterialData.material, ref pixelRect, isRenderToBackBufferTarget);
if (isRenderToBackBufferTarget)
cmd.SetViewport(pixelRect);
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/BloomPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/BloomPostProcessPass.cs
index 50049f584e7..7827ec1ae6e 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/BloomPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/BloomPostProcessPass.cs
@@ -14,15 +14,14 @@ internal sealed class BloomPostProcessPass : PostProcessPass
/// Generates bloom mipmap chain using dual filtering (downsample then upsample with tent filter) for efficient wide-radius bloom.
static readonly ProfilingSampler k_ProfilingSamplerDual = ProfilingSampler.Create("Blit Bloom Mipmaps (Dual)", MarkerFlags.Default);
- Material m_Material;
- Material[] m_MaterialPyramid;
+ PostProcessMaterial m_Material;
+ PostProcessMaterial[] m_MaterialPyramid;
// Cached bloom params from previous frame to avoid unnecessary material updates
MaterialParams m_PrevParams;
BloomMipPyramid m_MipPyramid;
- bool m_IsValid;
bool m_IsDependency;
public BloomMipPyramid mipPyramid => m_MipPyramid;
@@ -35,18 +34,13 @@ public BloomPostProcessPass(Shader shader)
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = URPProfilingSamplers.Bloom;
- m_Material = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log);
+ m_Material = new PostProcessMaterial(shader, passName);
// Array for bloom pyramid materials.
// Materials are references in the command buffer, so we need a separate material for each mip level.
- m_MaterialPyramid = new Material[k_MaxPyramidSize];
+ m_MaterialPyramid = new PostProcessMaterial[k_MaxPyramidSize];
for (uint i = 0; i < k_MaxPyramidSize; ++i)
- m_MaterialPyramid[i] = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log);
-
- // Check if the pass init was successful.
- m_IsValid = m_Material != null;
- for(int i = 0; i < k_MaxPyramidSize; i++)
- m_IsValid &= m_MaterialPyramid[i] != null;
+ m_MaterialPyramid[i] = new PostProcessMaterial(shader, passName);
m_MipPyramid = new BloomMipPyramid(k_MaxPyramidSize);
@@ -55,9 +49,9 @@ public BloomPostProcessPass(Shader shader)
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
+ m_Material.Dispose();
for(int i = 0; i < k_MaxPyramidSize; i++)
- CoreUtils.Destroy(m_MaterialPyramid[i]);
+ m_MaterialPyramid[i].Dispose();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -69,7 +63,7 @@ public void Setup(bool runAsDependency)
private class BloomPassData
{
internal Material material;
- internal Material[] mipMaterials;
+ internal PostProcessMaterial[] mipMaterials;
internal TextureHandle sourceTexture;
@@ -78,13 +72,14 @@ private class BloomPassData
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
- return;
-
var bloom = volumeStack.GetComponent();
if (!bloom.IsActive() && !m_IsDependency)
return;
+ // The pyramid materials use the same shader, so they are valid if m_Material is.
+ if (!m_Material.Validate())
+ return;
+
UniversalResourceData resourceData = frameData.Get();
UniversalCameraData cameraData = frameData.Get();
@@ -120,18 +115,18 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
// Setting keywords can be somewhat expensive on low-end platforms.
// Previous params are cached to avoid setting the same keywords every frame.
bool paramsDirty = !m_PrevParams.Equals(ref newParams);
- bool isParamsPropertySet = m_Material.HasProperty(ShaderConstants._Params);
+ bool isParamsPropertySet = m_Material.material.HasProperty(ShaderConstants._Params);
if (paramsDirty || !isParamsPropertySet)
{
- m_Material.SetVector(ShaderConstants._Params, newParams.parameters);
- m_Material.SetVector(ShaderConstants._Params2, newParams.parameters2);
- CoreUtils.SetKeyword(m_Material, ShaderKeywordStrings.BloomHQ, newParams.highQualityFiltering);
- CoreUtils.SetKeyword(m_Material, ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT, newParams.enableAlphaOutput);
+ m_Material.material.SetVector(ShaderConstants._Params, newParams.parameters);
+ m_Material.material.SetVector(ShaderConstants._Params2, newParams.parameters2);
+ CoreUtils.SetKeyword(m_Material.material, ShaderKeywordStrings.BloomHQ, newParams.highQualityFiltering);
+ CoreUtils.SetKeyword(m_Material.material, ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT, newParams.enableAlphaOutput);
// These materials are duplicate just to allow different bloom blits to use different textures.
for (uint i = 0; i < k_MaxPyramidSize; ++i)
{
- var materialPyramid = m_MaterialPyramid[i];
+ var materialPyramid = m_MaterialPyramid[i].material;
materialPyramid.SetVector(ShaderConstants._Params, newParams.parameters);
CoreUtils.SetKeyword(materialPyramid, ShaderKeywordStrings.BloomHQ, newParams.highQualityFiltering);
CoreUtils.SetKeyword(materialPyramid, ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT, newParams.enableAlphaOutput);
@@ -206,7 +201,7 @@ TextureHandle BloomGaussian(RenderGraph renderGraph, in TextureHandle source)
using (var builder = renderGraph.AddUnsafePass(passName, out var passData, profilingSampler))
{
passData.sourceTexture = source;
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.mipMaterials = m_MaterialPyramid;
passData.mipPyramid = m_MipPyramid;
@@ -271,7 +266,7 @@ TextureHandle BloomGaussian(RenderGraph renderGraph, in TextureHandle source)
// gets overriden by the time the render func is executed.
// Material is a reference, so all the blits would share the same material state in the cmdbuf.
// NOTE: another option would be to use cmd.SetGlobalTexture().
- var upMaterial = data.mipMaterials[i];
+ var upMaterial = data.mipMaterials[i].material;
upMaterial.SetTexture(ShaderConstants._SourceTexLowMip, lowMip);
Blitter.BlitCameraTexture(cmd, highMip, dst, loadAction, storeAction, upMaterial, ShaderPass.k_Upsample);
@@ -290,7 +285,7 @@ TextureHandle BloomKawase(RenderGraph renderGraph, in TextureHandle source)
using (var builder = renderGraph.AddUnsafePass(k_PassNameKawase, out var passData, k_ProfilingSamplerKawase))
{
passData.sourceTexture = source;
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.mipMaterials = m_MaterialPyramid;
passData.mipPyramid = m_MipPyramid;
@@ -325,7 +320,7 @@ TextureHandle BloomKawase(RenderGraph renderGraph, in TextureHandle source)
{
TextureHandle src = ((i & 1) == 0) ? mipDownTextures[0] : mipUpTextures[0];
TextureHandle dst = ((i & 1) == 0) ? mipUpTextures[0] : mipDownTextures[0];
- Material mat = data.mipMaterials[i];
+ Material mat = data.mipMaterials[i].material;
Blitter.BlitCameraTexture(cmd, src, dst, loadAction, storeAction, mat, ShaderPass.k_Kawase);
}
@@ -344,7 +339,7 @@ TextureHandle BloomDual(RenderGraph renderGraph, in TextureHandle source)
using (var builder = renderGraph.AddUnsafePass(k_PassNameDual, out var passData, k_ProfilingSamplerDual))
{
passData.sourceTexture = source;
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.mipMaterials = m_MaterialPyramid;
passData.mipPyramid = m_MipPyramid;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldBokehProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldBokehProcessPass.cs
index f6e5c913e60..ca96eaf8ddd 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldBokehProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldBokehProcessPass.cs
@@ -9,8 +9,7 @@ internal sealed class DepthOfFieldBokehPostProcessPass : PostProcessPass
public const string k_TargetName = "CameraColorDepthOfFieldBokeh";
const int k_DownSample = 2;
- Material m_Material;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
Vector4[] m_BokehKernel;
int m_BokehHash;
@@ -23,14 +22,12 @@ public DepthOfFieldBokehPostProcessPass(Shader shader)
{
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = URPProfilingSamplers.BokehDepthOfField;
- m_Material = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
}
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
private class DoFBokehPassData
@@ -58,9 +55,6 @@ private class DoFBokehPassData
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
- return;
-
var depthOfField = volumeStack.GetComponent();
if (!depthOfField.IsActive() || depthOfField.mode.value != DepthOfFieldMode.Bokeh)
return;
@@ -69,6 +63,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
if (cameraData.isSceneViewCamera)
return;
+ if (!m_Material.Validate())
+ return;
+
var postProcessingData = frameData.Get();
var resourceData = frameData.Get();
@@ -127,7 +124,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
passData.depthTexture = resourceData.cameraDepthTexture;
builder.UseTexture(resourceData.cameraDepthTexture, AccessFlags.Read);
- passData.material = m_Material;
+ passData.material = m_Material.material;
// Pass Textures
passData.fullCoCTexture = fullCoCTexture;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldGaussianPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldGaussianPostProcessPass.cs
index def16de768f..5f960bda1d6 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldGaussianPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/DepthOfFieldGaussianPostProcessPass.cs
@@ -10,9 +10,8 @@ internal sealed class DepthOfFieldGaussianPostProcessPass : PostProcessPass
public const string k_TargetName = "CameraColorDepthOfFieldGaussian";
const int k_DownSample = 2;
- Material m_Material;
- Material m_MaterialCoc;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
+ PostProcessMaterial m_MaterialCoc;
Experimental.Rendering.GraphicsFormat m_CoCFormat;
@@ -21,9 +20,8 @@ public DepthOfFieldGaussianPostProcessPass(Shader shader)
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = URPProfilingSamplers.GaussianDepthOfField;
- m_Material = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log);
- m_MaterialCoc = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log);
- m_IsValid = m_Material != null && m_MaterialCoc != null;
+ m_Material = new PostProcessMaterial(shader, passName);
+ m_MaterialCoc = new PostProcessMaterial(shader, passName);
// Depth of Field
//
@@ -40,9 +38,8 @@ public DepthOfFieldGaussianPostProcessPass(Shader shader)
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- CoreUtils.Destroy(m_MaterialCoc);
- m_IsValid = false;
+ m_Material.Dispose();
+ m_MaterialCoc.Dispose();
}
private class DoFGaussianPassData
@@ -68,9 +65,6 @@ private class DoFGaussianPassData
};
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
- return;
-
var depthOfField = volumeStack.GetComponent();
if (!depthOfField.IsActive() || depthOfField.mode.value != DepthOfFieldMode.Gaussian)
return;
@@ -79,6 +73,10 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
if (cameraData.isSceneViewCamera)
return;
+ // m_MaterialCoc uses the same shader, so it is valid if m_Material is.
+ if (!m_Material.Validate())
+ return;
+
UniversalResourceData resourceData = frameData.Get();
var sourceTexture = resourceData.cameraColor;
@@ -117,8 +115,8 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
passData.highQualitySamplingValue = depthOfField.highQualitySampling.value;
passData.enableAlphaOutput = cameraData.isAlphaOutputEnabled;
- passData.material = m_Material;
- passData.materialCoC = m_MaterialCoc;
+ passData.material = m_Material.material;
+ passData.materialCoC = m_MaterialCoc.material;
// Inputs
passData.sourceTexture = sourceTexture;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/FinalPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/FinalPostProcessPass.cs
index 57948a22fb8..390be949870 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/FinalPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/FinalPostProcessPass.cs
@@ -10,9 +10,8 @@ internal sealed class FinalPostProcessPass : PostProcessPass
/// Blits the final post-processed image to the camera target, applying FXAA, upscaling, or format conversion as the last rendering step.
static readonly ProfilingSampler k_ProfilingSampler = ProfilingSampler.Create("Blit Final Post Processing", MarkerFlags.Default);
- Material m_Material;
+ PostProcessMaterial m_Material;
Texture2D[] m_FilmGrainTextures;
- bool m_IsValid;
public enum FilteringOperation
{
@@ -34,8 +33,7 @@ public FinalPostProcessPass(Shader shader, Texture2D[] filmGrainTextures)
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = k_ProfilingSampler;
- m_Material = PostProcessUtils.LoadShader(shader, passName);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
m_FilmGrainTextures = filmGrainTextures;
// Defaults
@@ -48,8 +46,7 @@ public FinalPostProcessPass(Shader shader, Texture2D[] filmGrainTextures)
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -82,7 +79,7 @@ private class PostProcessingFinalBlitPassData
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
+ if (!m_Material.Validate())
return;
var tonemapping = volumeStack.GetComponent();
@@ -108,7 +105,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
if (m_RenderOverlayUI)
builder.UseTexture(resourceData.overlayUITexture, AccessFlags.Read);
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.cameraData = cameraData;
passData.tonemapping = tonemapping;
@@ -201,7 +198,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
if (hdrColorEncoding)
{
PostProcessUtils.SetupHDROutput(material, cameraData.hdrDisplayInformation, cameraData.hdrDisplayColorGamut, data.tonemapping, data.hdrOperations, cameraData.rendersOverlayUI);
- RenderingUtils.SetupOffscreenUIViewportParams(material, ref cameraData.pixelRect, cameraData.resolveFinalTarget);
+ RenderingUtils.SetupOffscreenUIViewportParams(cameraData, material, ref cameraData.pixelRect, cameraData.resolveFinalTarget);
}
material.SetVector(ShaderConstants._SourceSize, PostProcessUtils.CalcShaderSourceSize(sourceTextureHdl));
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/Fsr1UpscalePostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/Fsr1UpscalePostProcessPass.cs
index 9299750d8f2..bd8ccaa1ddd 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/Fsr1UpscalePostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/Fsr1UpscalePostProcessPass.cs
@@ -8,8 +8,7 @@ internal sealed class Fsr1UpscalePostProcessPass : PostProcessPass
{
public const string k_TargetName = "CameraColorUpscaled";
- Material m_Material;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
TextureDesc m_UpscaledDesc;
@@ -18,8 +17,7 @@ public Fsr1UpscalePostProcessPass(Shader shader)
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = new ProfilingSampler("Blit FSR Upscaling");
- m_Material = PostProcessUtils.LoadShader(shader, passName);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
// Default
PostProcessUtils.MakeCompatible(ref m_UpscaledDesc);
@@ -30,8 +28,7 @@ public Fsr1UpscalePostProcessPass(Shader shader)
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
private class PostProcessingFinalFSRScalePassData
@@ -51,7 +48,7 @@ public void Setup(TextureDesc upscaledDesc)
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
+ if (!m_Material.Validate())
return;
var cameraData = frameData.Get();
@@ -70,7 +67,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
builder.SetRenderAttachment(destinationTexture, 0, AccessFlags.Write);
passData.sourceTexture = sourceTexture;
builder.UseTexture(sourceTexture, AccessFlags.Read);
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.fsrInputSize = new Vector2(srcDesc.width, srcDesc.height);
passData.fsrOutputSize = new Vector2(dstDesc.width, dstDesc.height);
passData.enableAlphaOutput = cameraData.isAlphaOutputEnabled;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareDataDrivenPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareDataDrivenPostProcessPass.cs
index 033ab8f65a0..68a79c21110 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareDataDrivenPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareDataDrivenPostProcessPass.cs
@@ -6,8 +6,7 @@ namespace UnityEngine.Rendering.Universal
{
internal sealed class LensFlareDataDrivenPostProcessPass : PostProcessPass
{
- Material m_Material;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
const string k_passNameOcclusion = "Blit Lens Flare Occlusion";
@@ -16,14 +15,12 @@ public LensFlareDataDrivenPostProcessPass(Shader shader)
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = URPProfilingSamplers.LensFlareDataDriven;
- m_Material = PostProcessUtils.LoadShader(shader, passName);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
}
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
private class LensFlarePassData
@@ -41,13 +38,13 @@ private class LensFlarePassData
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
- return;
-
var postProcessingData = frameData.Get();
if (LensFlareCommonSRP.Instance.IsEmpty() || !postProcessingData.supportDataDrivenLensFlare)
return;
+ if (!m_Material.Validate())
+ return;
+
var cameraData = frameData.Get();
var resourceData = frameData.Get();
@@ -55,7 +52,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
var destinationTexture = resourceData.cameraColor;
// Reset keywords
- m_Material.shaderKeywords = null;
+ m_Material.material.shaderKeywords = null;
var desc = destinationTexture.GetDescriptor(renderGraph);
@@ -76,7 +73,7 @@ void LensFlareDataDrivenComputeOcclusion(RenderGraph renderGraph, UniversalResou
builder.UseTexture(occlusionHandle, AccessFlags.Write);
passData.cameraData = cameraData;
passData.viewport = cameraData.pixelRect;
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.width = (float)dstDesc.width;
passData.height = (float)dstDesc.height;
if (paniniProjection.IsActive())
@@ -171,7 +168,7 @@ void RenderLensFlareDataDriven(RenderGraph renderGraph, UniversalResourceData re
passData.destinationTexture = destination;
builder.UseTexture(destination, AccessFlags.Write);
passData.cameraData = cameraData;
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.width = (float)srcDesc.width;
passData.height = (float)srcDesc.height;
passData.viewport.x = 0.0f;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareScreenSpacePostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareScreenSpacePostProcessPass.cs
index 73482fa2809..9dda36ffcb8 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareScreenSpacePostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/LensFlareScreenSpacePostProcessPass.cs
@@ -6,8 +6,7 @@ namespace UnityEngine.Rendering.Universal
{
internal sealed class LensFlareScreenSpacePostProcessPass : PostProcessPass
{
- Material m_Material;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
// Post-processing main color-buffer texture desc. Can be different from downsampled bloom/flare textures.
int m_ColorBufferWidth;
@@ -19,8 +18,7 @@ public LensFlareScreenSpacePostProcessPass(Shader shader)
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = URPProfilingSamplers.LensFlareScreenSpace;
- m_Material = PostProcessUtils.LoadShader(shader, passName);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
// Default values
m_ColorBufferWidth = 1; // Unknown at pipe/pass construction time. Safe default. Avoid division by zero.
@@ -30,8 +28,7 @@ public LensFlareScreenSpacePostProcessPass(Shader shader)
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -59,10 +56,10 @@ private class LensFlareScreenSpacePassData
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
+ if (!IsActive(volumeStack, frameData))
return;
- if (!IsActive(volumeStack, frameData))
+ if (!m_Material.Validate())
return;
var lensFlareScreenSpace = volumeStack.GetComponent();
@@ -112,7 +109,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
passData.actualColorWidth = m_ColorBufferWidth;
passData.actualColorHeight = m_ColorBufferHeight;
passData.camera = cameraData.camera;
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.lensFlareScreenSpace = lensFlareScreenSpace; // NOTE: reference, assumed constant until executed.
passData.downsample = downsample;
passData.flareResultTmp = resultTmpTexture;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/MotionBlurPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/MotionBlurPostProcessPass.cs
index 6aaf38a179c..1a1189b89df 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/MotionBlurPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/MotionBlurPostProcessPass.cs
@@ -8,22 +8,19 @@ internal sealed class MotionBlurPostProcessPass : PostProcessPass
{
public const string k_TargetName = "CameraColorMotionBlur";
- Material m_Material;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
public MotionBlurPostProcessPass(Shader shader)
{
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = URPProfilingSamplers.MotionBlur;
- m_Material = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
}
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
private class MotionBlurPassData
@@ -39,9 +36,6 @@ private class MotionBlurPassData
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if(!m_IsValid)
- return;
-
// Disable MotionBlur in EditMode, so that editing remains clear and readable.
// NOTE: HDRP does the same via CoreUtils::AreAnimatedMaterialsEnabled().
// Disable MotionBlurMode.CameraAndObjects on renderers that do not support motion vectors
@@ -56,6 +50,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
if (cameraData.isSceneViewCamera)
return;
+ if (!m_Material.Validate())
+ return;
+
UniversalResourceData resourceData = frameData.Get();
TextureHandle motionVectorColor = resourceData.motionVectorColor;
@@ -97,7 +94,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
Debug.Assert(cameraDepthTexture.IsValid(), "Camera depth texture is invalid. Per-camera motion blur requires a depth texture.");
builder.UseTexture(cameraDepthTexture, AccessFlags.Read);
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.passIndex = passIndex;
passData.camera = cameraData.camera;
passData.enableAlphaOutput = cameraData.isAlphaOutputEnabled;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/PaniniProjectionPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/PaniniProjectionPostProcessPass.cs
index a8a4f77a60a..28928f051f4 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/PaniniProjectionPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/PaniniProjectionPostProcessPass.cs
@@ -8,22 +8,19 @@ internal sealed class PaniniProjectionPostProcessPass : PostProcessPass
{
public const string k_TargetName = "CameraColorPaniniProjection";
- Material m_Material;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
public PaniniProjectionPostProcessPass(Shader shader)
{
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = URPProfilingSamplers.PaniniProjection;
- m_Material = PostProcessUtils.LoadShader(shader, passName, logLevel: LogType.Log);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
}
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
private class PaniniProjectionPassData
@@ -35,9 +32,6 @@ private class PaniniProjectionPassData
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if(!m_IsValid)
- return;
-
var paniniProjection = volumeStack.GetComponent();
if(!paniniProjection.IsActive())
@@ -47,6 +41,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
if (cameraData.isSceneViewCamera)
return;
+ if (!m_Material.Validate())
+ return;
+
UniversalResourceData resourceData = frameData.Get();
var sourceTexture = resourceData.cameraColor;
var destinationTexture = PostProcessUtils.CreateCompatibleTexture(renderGraph, sourceTexture, k_TargetName, true, FilterMode.Bilinear);
@@ -72,7 +69,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
builder.SetRenderAttachment(destinationTexture, 0, AccessFlags.Write);
passData.sourceTexture = sourceTexture;
builder.UseTexture(sourceTexture, AccessFlags.Read);
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.paniniParams = new Vector4(viewExtents.x, viewExtents.y, paniniD, paniniS);
passData.isPaniniGeneric = 1f - Mathf.Abs(paniniD) > float.Epsilon;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/ScalingSetupPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/ScalingSetupPostProcessPass.cs
index 38fbd254932..719251345a5 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/ScalingSetupPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/ScalingSetupPostProcessPass.cs
@@ -8,8 +8,7 @@ internal sealed class ScalingSetupPostProcessPass : PostProcessPass
{
public const string k_TargetName = "SetupUpscaling";
- Material m_Material;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
HDROutputUtils.Operation m_HdrOperations;
@@ -18,8 +17,7 @@ public ScalingSetupPostProcessPass(Shader shader)
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = new ProfilingSampler("Setup Final Post Processing");
- m_Material = PostProcessUtils.LoadShader(shader, passName);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
// Defaults
m_HdrOperations = HDROutputUtils.Operation.None; // HDR disabled.
@@ -27,8 +25,7 @@ public ScalingSetupPostProcessPass(Shader shader)
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -49,7 +46,7 @@ private class PostProcessingFinalSetupPassData
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
+ if (!m_Material.Validate())
return;
var tonemapping = volumeStack.GetComponent();
@@ -78,7 +75,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
passData.sourceTexture = sourceTexture;
builder.UseTexture(sourceTexture, AccessFlags.Read);
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.cameraData = cameraData;
passData.tonemapping = tonemapping;
passData.hdrOperations = m_HdrOperations;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/SmaaPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/SmaaPostProcessPass.cs
index 4a27b13f14a..b00353dc7b8 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/SmaaPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/SmaaPostProcessPass.cs
@@ -9,8 +9,7 @@ internal sealed class SmaaPostProcessPass : PostProcessPass
{
public const string k_TargetName = "CameraColorSMAA";
- Material m_Material;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
// Static resource textures for SMAA technique
Texture2D m_AreaTexture;
@@ -26,8 +25,7 @@ public SmaaPostProcessPass(Shader shader, Texture2D smaaAreaTexture, Texture2D s
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = URPProfilingSamplers.SMAANeighborhoodBlend;
- m_Material = PostProcessUtils.LoadShader(shader, passName);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
m_AreaTexture = smaaAreaTexture;
m_SearchTexture = smaaSearchTexture;
@@ -42,8 +40,7 @@ public SmaaPostProcessPass(Shader shader, Texture2D smaaAreaTexture, Texture2D s
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
private class SMAASetupPassData
@@ -67,13 +64,13 @@ private class SMAAPassData
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
- return;
-
var cameraData = frameData.Get();
if (cameraData.antialiasing != AntialiasingMode.SubpixelMorphologicalAntiAliasing)
return;
+ if (!m_Material.Validate())
+ return;
+
var resourceData = frameData.Get();
var sourceTexture = resourceData.cameraColor;
@@ -109,7 +106,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
passData.stencilMask = (float)kStencilBit;
passData.antialiasingQuality = cameraData.antialiasingQuality;
- passData.material = m_Material;
+ passData.material = m_Material.material;
builder.SetRenderAttachment(edgeTexture, 0, AccessFlags.Write);
builder.SetRenderAttachmentDepth(edgeTextureStencil, AccessFlags.Write);
@@ -138,7 +135,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
builder.SetRenderAttachmentDepth(edgeTextureStencil, AccessFlags.Read);
passData.sourceTexture = edgeTexture;
builder.UseTexture(edgeTexture, AccessFlags.Read);
- passData.material = m_Material;
+ passData.material = m_Material.material;
builder.SetRenderFunc(static (SMAAPassData data, RasterGraphContext context) =>
{
@@ -159,7 +156,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
builder.UseTexture(sourceTexture, AccessFlags.Read);
passData.blendTexture = blendTexture;
builder.UseTexture(blendTexture, AccessFlags.Read);
- passData.material = m_Material;
+ passData.material = m_Material.material;
builder.SetRenderFunc(static (SMAAPassData data, RasterGraphContext context) =>
{
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StopNanPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StopNanPostProcessPass.cs
index bd653d285f0..5238899826e 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StopNanPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StopNanPostProcessPass.cs
@@ -8,22 +8,19 @@ internal sealed class StopNanPostProcessPass : PostProcessPass
{
public const string k_TargetName = "CameraColorStopNaNs";
- Material m_Material;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
public StopNanPostProcessPass(Shader shader)
{
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = URPProfilingSamplers.StopNaNs;
- m_Material = PostProcessUtils.LoadShader(shader, passName);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
}
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
private class StopNaNsPassData
@@ -33,13 +30,13 @@ private class StopNaNsPassData
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
- return;
-
var cameraData = frameData.Get();
if (!cameraData.isStopNaNEnabled)
return;
+ if (!m_Material.Validate())
+ return;
+
var resourceData = frameData.Get();
var sourceTexture = resourceData.cameraColor;
var destinationTexture = PostProcessUtils.CreateCompatibleTexture(renderGraph, sourceTexture, k_TargetName, true, FilterMode.Bilinear);
@@ -50,7 +47,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
builder.SetRenderAttachment(destinationTexture, 0, AccessFlags.ReadWrite);
passData.sourceTexture = sourceTexture;
builder.UseTexture(sourceTexture, AccessFlags.Read);
- passData.stopNaN = m_Material;
+ passData.stopNaN = m_Material.material;
builder.SetRenderFunc(static (StopNaNsPassData data, RasterGraphContext context) =>
{
var cmd = context.cmd;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StpPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StpPostProcessPass.cs
index 55e7988291b..15735979eb1 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StpPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/StpPostProcessPass.cs
@@ -82,6 +82,17 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
UpscalerPostProcessPass.UpdateCameraResolution(renderGraph, cameraData, new Vector2Int(destDesc.width, destDesc.height));
resourceData.cameraColor = destinationTexture;
+
+#if !ENABLE_UPSCALER_FRAMEWORK
+ // STP only upscales the color channels; rebuild the output alpha from the pre-upscale image.
+ // cameraData.jitter is in NDC space; converting it back to pixels at the rendering resolution
+ // recovers the applied sub-pixel jitter. Negated because the alpha upscale kernel follows
+ // HDRP's jitter sign convention, which is the opposite of URP's (see the IUpscaler sign note
+ // in HDCamera.GetJitteredProjectionMatrix).
+ Vector2 alphaJitter = -0.5f * new Vector2(cameraData.jitter.x * srcDesc.width, cameraData.jitter.y * srcDesc.height);
+ AlphaUpscaleUtils.Execute(renderGraph, cameraData, resourceData, sourceTexture, isTemporalUpscaler: true,
+ new Vector2Int(srcDesc.width, srcDesc.height), new Vector2Int(destDesc.width, destDesc.height), alphaJitter);
+#endif
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/TemporalAntiAliasingPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/TemporalAntiAliasingPostProcessPass.cs
index b7ca47b4a6e..82b85d22351 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/TemporalAntiAliasingPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/TemporalAntiAliasingPostProcessPass.cs
@@ -8,8 +8,7 @@ internal sealed class TemporalAntiAliasingPostProcessPass : PostProcessPass
{
public const string k_TargetName = "CameraColorTemporalAA";
- Material m_Material;
- bool m_IsValid;
+ PostProcessMaterial m_Material;
uint m_WarnCounter;
public TemporalAntiAliasingPostProcessPass(Shader shader)
@@ -17,23 +16,18 @@ public TemporalAntiAliasingPostProcessPass(Shader shader)
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = null;
- m_Material = PostProcessUtils.LoadShader(shader, passName);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
m_WarnCounter = 0;
}
public override void Dispose()
{
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if (!m_IsValid)
- return;
-
UniversalCameraData cameraData = frameData.Get();
#if ENABLE_UPSCALER_FRAMEWORK
var postProcessingData = frameData.Get();
@@ -56,6 +50,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
return;
}
+ if (!m_Material.Validate())
+ return;
+
UniversalResourceData resourceData = frameData.Get();
var sourceTexture = resourceData.cameraColor;
@@ -66,7 +63,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
Debug.Assert(motionVectors.IsValid(), "MotionVectors are invalid. TAA requires a motion vector texture.");
- TemporalAA.Render(renderGraph, m_Material, cameraData, sourceTexture, in cameraDepth, in motionVectors, destinationTexture);
+ TemporalAA.Render(renderGraph, m_Material.material, cameraData, sourceTexture, in cameraDepth, in motionVectors, destinationTexture);
resourceData.cameraColor = destinationTexture;
}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UberPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UberPostProcessPass.cs
index 806965caf04..58a7debfe21 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UberPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UberPostProcessPass.cs
@@ -7,7 +7,7 @@ namespace UnityEngine.Rendering.Universal
{
internal sealed class UberPostProcessPass : PostProcessPass
{
- Material m_Material;
+ PostProcessMaterial m_Material;
Texture2D[] m_FilmGrainTextures;
public enum FilteringOperation
@@ -20,7 +20,6 @@ public enum FilteringOperation
RTHandle m_UserLut;
FilteringOperation m_FilteringOperation;
HDROutputUtils.Operation m_HdrOperations;
- bool m_IsValid;
bool m_IsFinalPass;
bool m_RequireSRGBConversionBlit;
bool m_RenderOverlayUI;
@@ -31,8 +30,7 @@ public UberPostProcessPass(Shader shader, Texture2D[] filmGrainTextures)
this.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing - 1;
this.profilingSampler = URPProfilingSamplers.UberPostProcess;
- m_Material = PostProcessUtils.LoadShader(shader, passName);
- m_IsValid = m_Material != null;
+ m_Material = new PostProcessMaterial(shader, passName);
m_FilmGrainTextures = filmGrainTextures;
// Defaults
@@ -48,8 +46,7 @@ public UberPostProcessPass(Shader shader, Texture2D[] filmGrainTextures)
public override void Dispose()
{
m_UserLut?.Release();
- CoreUtils.Destroy(m_Material);
- m_IsValid = false;
+ m_Material.Dispose();
}
public void Setup(Texture ditherTexture,
@@ -101,7 +98,7 @@ private class UberPostPassData
///
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
- if(!m_IsValid)
+ if (!m_Material.Validate())
return;
var colorLookup = volumeStack.GetComponent();
@@ -186,7 +183,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
if(bloomTexture.IsValid())
builder.UseTexture(bloomTexture, AccessFlags.Read);
- passData.material = m_Material;
+ passData.material = m_Material.material;
passData.cameraData = cameraData;
passData.useFastSRGBLinearConversion = postProcessingData.useFastSRGBLinearConversion;
passData.requireSRGBConversionBlit = m_RequireSRGBConversionBlit;
@@ -275,7 +272,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
if(PostProcessUtils.RequireHDROutput(cameraData))
{
PostProcessUtils.SetupHDROutput(material, cameraData.hdrDisplayInformation, cameraData.hdrDisplayColorGamut, data.tonemapping, data.hdrOperations, cameraData.rendersOverlayUI);
- RenderingUtils.SetupOffscreenUIViewportParams(material, ref cameraData.pixelRect, data.isActiveTargetBackBuffer);
+ RenderingUtils.SetupOffscreenUIViewportParams(cameraData, material, ref cameraData.pixelRect, data.isActiveTargetBackBuffer);
}
#if ENABLE_VR && ENABLE_XR_MODULE
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UpscalerPostProcessPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UpscalerPostProcessPass.cs
index 280a08e49ac..756e35efeb1 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UpscalerPostProcessPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcess/UpscalerPostProcessPass.cs
@@ -47,8 +47,8 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
// reconstructs to full resolution mid-frame, but ScalableBufferManager is a single global scale with no per-stage
// render->display transition, so the post-upscale chain (UberPost, final blit) keeps writing into the
// ScalableBufferManager-scaled sub-rect and only that sub-rect of the screen updates.
- // Gate on camera.allowDynamicResolution (the stable opt-in), not the live ScalableBufferManager factor,
- // which would flip per-frame as the app crosses factor 1.0.
+ // Gate on camera.allowDynamicResolution (the stable opt-in), not the live ScalableBufferManager factor,
+ // which would flip per-frame as the app crosses factor 1.0.
if (cameraData.camera.allowDynamicResolution && postProcessingData.activeUpscaler.isTemporal)
{
if (Debug.isDebugBuild && !m_WarnedHardwareDrsTemporalUnsupported)
@@ -117,7 +117,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
}
return;
}
-
+
if (Debug.isDebugBuild) // Saw valid motion data: reset so a later missing-data camera warns again.
m_WarnedMissingMotionData = false;
@@ -217,6 +217,13 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
// Use the output texture of upscaling
resourceData.cameraColor = io.cameraColor;
+
+ // The negated jitter follows HDRP's sign convention (see HDCamera.GetJitteredProjectionMatrix).
+ if (!upscaler.supportsAlphaUpscaling)
+ {
+ AlphaUpscaleUtils.Execute(renderGraph, cameraData, resourceData, sourceTexture, upscaler.isTemporal,
+ io.preUpscaleResolution, io.postUpscaleResolution, -io.subpixelJitter);
+ }
#endif
}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs
index 1f9aa2e2fb1..27e0d49858f 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs
@@ -1,3 +1,4 @@
+using System;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
using System.Runtime.CompilerServices; // AggressiveInlining
@@ -9,29 +10,6 @@ namespace UnityEngine.Rendering.Universal
///
public static class PostProcessUtils
{
- ///
- /// Creates a post-processing pass material from a shader. Shader is error checked for device support.
- ///
- /// Shader used for the material
- /// Pass name for error messages.
- /// LogType for the message if the shader is not supported.
- /// A new Material instance using the provided shader. Null if the shader is not supported or it's missing.
- internal static Material LoadShader(Shader shader, string passName = "", LogType logLevel = LogType.Warning)
- {
- if (shader == null)
- {
- Debug.LogError($"Missing shader (in '{passName}'). PostProcessing render passes will not execute. Check for missing reference in the Renderer and/or PostProcessData resources.");
- return null;
- }
- else if (!shader.isSupported)
- {
- Debug.unityLogger.Log(logLevel, $"Shader '{shader.name}' is not supported or has been stripped from the build (in '{passName}'). PostProcessing render passes will not execute.");
- return null;
- }
-
- return CoreUtils.CreateEngineMaterial(shader);
- }
-
///
/// Creates a texture compatible with post-processing effects.
///
@@ -422,4 +400,55 @@ static class ShaderConstants
public static readonly int _SourceSize = Shader.PropertyToID("_SourceSize");
}
}
+
+ ///
+ /// Helper material class for a post-processing materials.
+ /// Handles checks and logging in case the shader is missing, unsupported or stripped from the build.
+ ///
+ internal sealed class PostProcessMaterial : IDisposable
+ {
+ readonly Shader m_Shader;
+ readonly string m_PassName;
+ Material m_Material;
+ bool m_LoggedFailure;
+
+ public Shader shader => m_Shader;
+ public Material material => m_Material;
+ public bool isValid => m_Material != null;
+
+ public PostProcessMaterial(Shader shader, string passName)
+ {
+ m_Shader = shader;
+ m_PassName = passName;
+
+ // Note: isSupported is also false when all variants of the shader were stripped from the build.
+ if (shader != null && shader.isSupported)
+ m_Material = CoreUtils.CreateEngineMaterial(shader);
+ }
+
+ ///
+ /// Returns whether the material can be used, and logs the reason once if it can't.
+ ///
+ public bool Validate()
+ {
+ if (isValid)
+ return true;
+
+ if (!m_LoggedFailure)
+ {
+ m_LoggedFailure = true;
+ if (m_Shader == null)
+ Debug.LogError($"Missing shader (in '{m_PassName}'). This post-processing pass will not execute. Check for missing reference in the Renderer and/or PostProcessData resources.");
+ else if (!m_Shader.isSupported)
+ Debug.LogWarning($"Shader '{m_Shader.name}' is not supported or has been stripped from the build (in '{m_PassName}'). This post-processing pass will not execute.");
+ }
+ return false;
+ }
+
+ public void Dispose()
+ {
+ CoreUtils.Destroy(m_Material);
+ m_Material = null;
+ }
+ }
}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs
index b28d5913991..e49c557fd1a 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs
@@ -221,12 +221,33 @@ internal static void SetScaleBiasRt(RasterCommandBuffer cmd, in UniversalCameraD
cmd.SetGlobalVector(Shader.PropertyToID("_ScaleBiasRt"), scaleBiasRt);
}
- internal static void SetupOffscreenUIViewportParams(Material material, ref Rect pixelRect, bool isRenderToBackBufferTarget)
+ // Returns the size of the backbuffer the camera renders to, in pixels.
+ internal static Vector2Int GetScreenBackbufferSize(Camera camera)
+ {
+ // Screen.width/height only ever describe the main display, so cameras targeting a secondary
+ // display need to query that display instead.
+ //
+ // UUM-149562: on QNX and Embedded Linux the graphics backend still reports the main display's
+ // resolution for the backbuffer of a secondary display. Returning the secondary display's real
+ // resolution here would no longer match what the backend reports, the render pass would fail
+ // validation and the secondary display would stop rendering altogether. Falling back to the main
+ // display size keeps those platforms rendering as usual. Remove the platform exclusions
+ // above once the backend reports per-display backbuffer dimensions.
+#if ENABLE_MULTIPLE_DISPLAYS && !UNITY_QNX && !UNITY_EMBEDDED_LINUX
+ int targetDisplay = camera.targetDisplay;
+ var displays = Display.displays;
+ if (targetDisplay > 0 && targetDisplay < displays.Length)
+ return new Vector2Int(displays[targetDisplay].renderingWidth, displays[targetDisplay].renderingHeight);
+#endif
+ return new Vector2Int(Screen.width, Screen.height);
+ }
+
+ internal static void SetupOffscreenUIViewportParams(UniversalCameraData cameraData, Material material, ref Rect pixelRect, bool isRenderToBackBufferTarget)
{
Vector4 offscreenUIViewportParams = new Vector4(0f, 0f, 1f, 1f);
if (isRenderToBackBufferTarget)
{
- var rcpScreenSize = new Vector2(1f / Screen.width, 1f / Screen.height);
+ var rcpScreenSize = new Vector2(1f / cameraData.backbufferWidth, 1f / cameraData.backbufferHeight);
offscreenUIViewportParams = new Vector4(pixelRect.x * rcpScreenSize.x, pixelRect.y * rcpScreenSize.y, pixelRect.width * rcpScreenSize.x, pixelRect.height * rcpScreenSize.y);
}
material.SetVector(ShaderPropertyId.offscreenUIViewportParams, offscreenUIViewportParams);
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs b/Packages/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs
index 7293c88161e..fbdcd3605a1 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/ScriptableRenderer.cs
@@ -1228,29 +1228,35 @@ void InternalFinishRenderingCommon(CommandBuffer cmd, bool resolveFinalTarget)
}
}
- // Tells the pipeline this camera needs the real back buffer (the OS surface, not
- // resourceData.backBuffer) multisampled. The pipeline keeps it single-sampled on frames where no
- // camera needs MSAA, to save bandwidth.
+ // Tells the pipeline this camera needs its display target multisampled: the real back buffer (the OS
+ // surface, not resourceData.backBuffer), or the XR eye textures for XR cameras. The pipeline keeps it
+ // single-sampled on frames where no camera needs MSAA, to save bandwidth.
//
- // Contract: any renderer that renders multisampled content directly into the real back buffer must
+ // Contract: any renderer that renders multisampled content directly into the display target must
// call this while rendering, or the pipeline may request a single-sampled surface and that content
// is silently rendered without MSAA.
- private protected void ReportRealBackbufferMSAA(UniversalCameraData cameraData, bool requiresIntermediateAttachments)
+ private protected void ReportDisplayTargetMSAA(UniversalCameraData cameraData, bool requiresIntermediateAttachments)
{
- if (NeedsRealBackbufferMSAA(cameraData, this, requiresIntermediateAttachments))
- (RenderPipelineManager.currentPipeline as UniversalRenderPipeline)?.RequireRealBackbufferMSAA();
+ if (NeedsDisplayTargetMSAA(cameraData, this, requiresIntermediateAttachments))
+ {
+ var pipeline = RenderPipelineManager.currentPipeline as UniversalRenderPipeline;
+#if ENABLE_VR && ENABLE_XR_MODULE
+ if (cameraData.xr.enabled)
+ {
+ pipeline?.RequireXRDisplayMSAA();
+ return;
+ }
+#endif
+ pipeline?.RequireRealBackbufferMSAA();
+ }
}
- // True when this camera renders multisampled content into the real back buffer, so the surface must
+ // True when this camera renders multisampled content into its display target, so the surface must
// be multisampled. The tile-only case is the subtle one: there the back buffer shares a native render
// pass with the MSAA intermediate attachments, so it must match their sample count even though it
// isn't rendered to directly.
- static bool NeedsRealBackbufferMSAA(UniversalCameraData cameraData, ScriptableRenderer renderer, bool requiresIntermediateAttachments)
+ static bool NeedsDisplayTargetMSAA(UniversalCameraData cameraData, ScriptableRenderer renderer, bool requiresIntermediateAttachments)
{
-#if ENABLE_VR && ENABLE_XR_MODULE
- if (cameraData.xr.enabled)
- return false;
-#endif
if (cameraData.targetTexture != null)
return false;
if (!(renderer.supportedRenderingFeatures.msaa && cameraData.camera.allowMSAA))
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs
index 4bae86b9dc1..b6e1e644e37 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs
@@ -14,6 +14,8 @@ struct LightMinMaxZJob : IJobFor
public NativeArray lights;
public NativeArray minMaxZs;
+ public float near;
+
public void Execute(int index)
{
var lightIndex = index % lights.Length;
@@ -40,7 +42,8 @@ public void Execute(int index)
var angleB = math.PI * 0.5f - angleA;
var coneRadius = light.range * cosAngleA * math.sin(angleA) / math.sin(angleB);
var a = endPointVS - originVS;
- var e = math.sqrt(1.0f - a.z * a.z / math.dot(a, a));
+ // Saturate: rounding can push the argument slightly below 0, where sqrt returns NaN.
+ var e = math.sqrt(math.saturate(1.0f - a.z * a.z / math.dot(a, a)));
// `-a.z` and `a.z` is `dot(a, {0, 0, -1}).z` and `dot(a, {0, 0, 1}).z` optimized
// `cosAngleA` is multiplied by `coneHeight` to avoid normalizing `a`, which we know has length `coneHeight`
@@ -55,8 +58,9 @@ public void Execute(int index)
minMax.y = float.MinValue;
}
- minMax.x = math.max(minMax.x, 0);
- minMax.y = math.max(minMax.y, 0);
+ // Clamp to near, not 0: an orthographic near plane can be negative. A light entirely closer than the near
+ // plane keeps max < min, which ZBinningJob treats as empty.
+ minMax.x = math.max(minMax.x, near);
minMaxZs[index] = minMax;
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs
index 30aaaf490de..a7cc93726ea 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs
@@ -16,6 +16,8 @@ struct ReflectionProbeMinMaxZJob : IJobFor
public bool reflectionProbeRotation;
public NativeArray minMaxZs;
+ public float near;
+
public void Execute(int index)
{
var minMax = math.float2(float.MaxValue, float.MinValue);
@@ -45,6 +47,8 @@ public void Execute(int index)
minMax.y = math.max(minMax.y, cornerVS.z);
}
+ // As in LightMinMaxZJob: a probe entirely closer than the near plane keeps max < min.
+ minMax.x = math.max(minMax.x, near);
minMaxZs[index] = minMax;
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.cs
index 800ba60da59..05773bb64eb 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.cs
@@ -32,6 +32,7 @@ struct TilingJob : IJobFor
public Fixed2 viewToViewportScaleBiases;
public int2 tileCount;
public float near;
+ public float far;
public bool isOrthographic;
InclusiveRange m_TileYRange;
@@ -75,7 +76,7 @@ void TileLight(int lightIndex)
var lightToWorld = (float4x4)light.localToWorldMatrix;
var lightPositionVS = math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c3.xyz, 1)).xyz;
lightPositionVS.z *= -1;
- if (lightPositionVS.z >= near) ExpandY(lightPositionVS);
+ if (IsInDepthRange(lightPositionVS)) ExpandY(lightPositionVS);
var lightDirectionVS = math.normalize(math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c2.xyz, 0)).xyz);
lightDirectionVS.z *= -1;
@@ -84,39 +85,25 @@ void TileLight(int lightIndex)
var rangesq = square(range);
var cosHalfAngle = math.cos(halfAngle);
var coneHeight = cosHalfAngle * range;
-
- // Radius of circle formed by intersection of sphere and near plane.
- // Found using Pythagoras with a right triangle formed by three points:
- // (a) light position
- // (b) light position projected to near plane
- // (c) a point on the near plane at a distance `range` from the light position
- // (i.e. lies both on the sphere and the near plane)
- // Thus the hypotenuse is formed by (a) and (c) with length `range`, and the known side is formed
- // by (a) and (b) with length equal to the distance between the near plane and the light position.
- // The remaining unknown side is formed by (b) and (c) with length equal to the radius of the circle.
- // m_ClipCircleRadius = sqrt(sq(light.range) - sq(m_Near - m_LightPosition.z));
- var sphereClipRadius = math.sqrt(rangesq - square(near - lightPositionVS.z));
-
- // Assumes a point on the sphere, i.e. at distance `range` from the light position.
- // If spot light, we check the angle between the direction vector from the light position and the light direction vector.
- // Note that division by range is to normalize the vector, as we know that the resulting vector will have length `range`.
- bool SpherePointIsValid(float3 p) => light.lightType == LightType.Point ||
- math.dot(math.normalize(p - lightPositionVS), lightDirectionVS) >= cosHalfAngle;
-
- // Project light sphere onto YZ plane, find the horizon points, and re-construct view space position of found points.
- // CalculateSphereYBounds(lightPositionVS, range, near, sphereClipRadius, out var sphereBoundY0, out var sphereBoundY1);
- GetSphereHorizon(lightPositionVS.yz, range, near, sphereClipRadius, out var sphereBoundYZ0, out var sphereBoundYZ1);
- var sphereBoundY0 = math.float3(lightPositionVS.x, sphereBoundYZ0);
- var sphereBoundY1 = math.float3(lightPositionVS.x, sphereBoundYZ1);
- if (SpherePointIsValid(sphereBoundY0)) ExpandY(sphereBoundY0);
- if (SpherePointIsValid(sphereBoundY1)) ExpandY(sphereBoundY1);
-
- // Project light sphere onto XZ plane, find the horizon points, and re-construct view space position of found points.
- GetSphereHorizon(lightPositionVS.xz, range, near, sphereClipRadius, out var sphereBoundXZ0, out var sphereBoundXZ1);
- var sphereBoundX0 = math.float3(sphereBoundXZ0.x, lightPositionVS.y, sphereBoundXZ0.y);
- var sphereBoundX1 = math.float3(sphereBoundXZ1.x, lightPositionVS.y, sphereBoundXZ1.y);
- if (SpherePointIsValid(sphereBoundX0)) ExpandY(sphereBoundX0);
- if (SpherePointIsValid(sphereBoundX1)) ExpandY(sphereBoundX1);
+ var isSpot = light.lightType == LightType.Spot;
+
+ // Outline of the sphere projected onto the YZ and XZ planes: the horizon as seen from the camera, and the
+ // extremes of the circles cut by the near and far planes. Missing points are NaN.
+ GetCircleHorizon(lightPositionVS.yz, range, out var horizonY0, out var horizonY1);
+ GetCircleHorizon(lightPositionVS.xz, range, out var horizonX0, out var horizonX1);
+ ExpandYIfInSphereCap(math.float3(lightPositionVS.x, horizonY0), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ ExpandYIfInSphereCap(math.float3(lightPositionVS.x, horizonY1), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ ExpandYIfInSphereCap(math.float3(horizonX0.x, lightPositionVS.y, horizonX0.y), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ ExpandYIfInSphereCap(math.float3(horizonX1.x, lightPositionVS.y, horizonX1.y), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ for (var i = 0; i < 2; i++)
+ {
+ var depth = i == 0 ? near : far;
+ var sectionRadius = math.sqrt(rangesq - square(depth - lightPositionVS.z));
+ ExpandYIfInSphereCap(math.float3(lightPositionVS.x, lightPositionVS.y - sectionRadius, depth), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ ExpandYIfInSphereCap(math.float3(lightPositionVS.x, lightPositionVS.y + sectionRadius, depth), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ ExpandYIfInSphereCap(math.float3(lightPositionVS.x - sectionRadius, lightPositionVS.y, depth), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ ExpandYIfInSphereCap(math.float3(lightPositionVS.x + sectionRadius, lightPositionVS.y, depth), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ }
if (light.lightType == LightType.Spot)
{
@@ -137,8 +124,8 @@ bool SpherePointIsValid(float3 p) => light.lightType == LightType.Point ||
GetProjectedCircleHorizon(baseCenter.yz, baseRadius, baseUY.yz, baseVY.yz, out var baseY1UV, out var baseY2UV);
var baseY1 = baseCenter + baseY1UV.x * baseUY + baseY1UV.y * baseVY;
var baseY2 = baseCenter + baseY2UV.x * baseUY + baseY2UV.y * baseVY;
- if (baseY1.z >= near) ExpandY(baseY1);
- if (baseY2.z >= near) ExpandY(baseY2);
+ if (IsInDepthRange(baseY1)) ExpandY(baseY1);
+ if (IsInDepthRange(baseY2)) ExpandY(baseY2);
// Project cone base into the XZ plane, find the horizon points, and re-construct view space position of found points.
// See comment for YZ plane for details.
@@ -147,71 +134,67 @@ bool SpherePointIsValid(float3 p) => light.lightType == LightType.Point ||
GetProjectedCircleHorizon(baseCenter.xz, baseRadius, baseUX.xz, baseVX.xz, out var baseX1UV, out var baseX2UV);
var baseX1 = baseCenter + baseX1UV.x * baseUX + baseX1UV.y * baseVX;
var baseX2 = baseCenter + baseX2UV.x * baseUX + baseX2UV.y * baseVX;
- if (baseX1.z >= near) ExpandY(baseX1);
- if (baseX2.z >= near) ExpandY(baseX2);
+ if (IsInDepthRange(baseX1)) ExpandY(baseX1);
+ if (IsInDepthRange(baseX2)) ExpandY(baseX2);
- // Handle base circle clipping by intersecting it with the near-plane if needed.
+ // Handle base circle clipping by intersecting it with the near and far planes if needed.
if (GetCircleClipPoints(baseCenter, lightDirectionVS, baseRadius, near, out var baseClip0, out var baseClip1))
{
ExpandY(baseClip0);
ExpandY(baseClip1);
}
+ if (GetCircleClipPoints(baseCenter, lightDirectionVS, baseRadius, far, out var baseFarClip0, out var baseFarClip1))
+ {
+ ExpandY(baseFarClip0);
+ ExpandY(baseFarClip1);
+ }
- bool ConicPointIsValid(float3 p) =>
- math.dot(math.normalize(p - lightPositionVS), lightDirectionVS) >= 0 &&
- math.dot(p - lightPositionVS, lightDirectionVS) <= coneHeight;
+ var sinHalfAngle = math.sin(halfAngle);
+ var coneDistanceTolerance = 1e-5f * (math.length(lightPositionVS) + range);
+ bool ConicPointIsValid(float3 p) => IsOnCone(p, lightPositionVS, lightDirectionVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance);
- // Calculate Z bounds of cone and check if it's overlapping with the near plane.
+ // Calculate Z bounds of cone and check if it's overlapping with the near and far planes.
// From https://www.iquilezles.org/www/articles/diskbbox/diskbbox.htm
- var baseExtentZ = baseRadius * math.sqrt(1.0f - square(lightDirectionVS.z));
- var coneIsClipping = near >= math.min(baseCenter.z - baseExtentZ, lightPositionVS.z) && near <= math.max(baseCenter.z + baseExtentZ, lightPositionVS.z);
-
- var coneU = math.cross(lightDirectionVS, lightPositionVS);
- // The cross product will be the 0-vector if the light-direction and camera-to-light-position vectors are parallel.
- // In that case, {1, 0, 0} is orthogonal to the light direction and we use that instead.
- coneU = math.csum(coneU) != 0f ? math.normalize(coneU) : math.float3(1, 0, 0);
+ var baseExtentZ = baseRadius * math.sqrt(math.saturate(1.0f - square(lightDirectionVS.z)));
+ var coneMinZ = math.min(baseCenter.z - baseExtentZ, lightPositionVS.z);
+ var coneMaxZ = math.max(baseCenter.z + baseExtentZ, lightPositionVS.z);
+ var coneIsClipping = near >= coneMinZ && near <= coneMaxZ;
+ var coneCrossesFar = far >= coneMinZ && far <= coneMaxZ;
+
+ // Any frame orthogonal to the axis works; cross with the view axis least aligned with it to keep it well conditioned.
+ var coneU = math.normalize(math.cross(lightDirectionVS, math.abs(lightDirectionVS.x) < 0.5f ? math.float3(1, 0, 0) : math.float3(0, 1, 0)));
var coneV = math.cross(lightDirectionVS, coneU);
- if (coneIsClipping)
+ var nearSection = new ConeSection(near, lightPositionVS, lightDirectionVS, cosHalfAngle, sinHalfAngle);
+ var farSection = new ConeSection(far, lightPositionVS, lightDirectionVS, cosHalfAngle, sinHalfAngle);
+ for (var i = 0; i < 2; i++)
{
- var r = baseRadius / coneHeight;
-
- // Find the Y bounds of the near-plane cone intersection, i.e. where y' = 0
- var thetaY = FindNearConicTangentTheta(lightPositionVS.yz, lightDirectionVS.yz, r, coneU.yz, coneV.yz);
- var p0Y = EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, thetaY.x);
- var p1Y = EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, thetaY.y);
+ if (i == 0 ? !coneIsClipping : !coneCrossesFar)
+ continue;
+ var section = i == 0 ? nearSection : farSection;
+ section.GetYExtremes(out var p0Y, out var p1Y);
if (ConicPointIsValid(p0Y)) ExpandY(p0Y);
if (ConicPointIsValid(p1Y)) ExpandY(p1Y);
- // Find the X bounds of the near-plane cone intersection, i.e. where x' = 0
- var thetaX = FindNearConicTangentTheta(lightPositionVS.xz, lightDirectionVS.xz, r, coneU.xz, coneV.xz);
- var p0X = EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, thetaX.x);
- var p1X = EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, thetaX.y);
+ section.GetXExtremes(out var p0X, out var p1X);
if (ConicPointIsValid(p0X)) ExpandY(p0X);
if (ConicPointIsValid(p1X)) ExpandY(p1X);
}
// Calculate the lines making up the sides of the cone as seen from the camera. `l1` and `l2` form lines
// from the light position.
- GetConeSideTangentPoints(lightPositionVS, lightDirectionVS, cosHalfAngle, baseRadius, coneHeight, range, coneU, coneV, out var l1, out var l2);
+ GetConeSideTangentPoints(-lightPositionVS, lightDirectionVS, cosHalfAngle, baseRadius, coneHeight, range, coneU, coneV, out var l1, out var l2);
- {
- var planeNormal = math.float3(0, 1, viewPlaneBottoms[m_ViewIndex]);
- var l1t = math.dot(-lightPositionVS, planeNormal) / math.dot(l1, planeNormal);
- var l1x = lightPositionVS + l1 * l1t;
- if (l1t >= 0 && l1t <= 1 && l1x.z >= near) ExpandY(l1x);
- }
- {
- var planeNormal = math.float3(0, 1, viewPlaneTops[m_ViewIndex]);
- var l1t = math.dot(-lightPositionVS, planeNormal) / math.dot(l1, planeNormal);
- var l1x = lightPositionVS + l1 * l1t;
- if (l1t >= 0 && l1t <= 1 && l1x.z >= near) ExpandY(l1x);
- }
+ // Where the cone sides cross the bottom and top of the screen.
+ ExpandYAtViewPlane(lightPositionVS, l1, viewPlaneBottoms[m_ViewIndex]);
+ ExpandYAtViewPlane(lightPositionVS, l1, viewPlaneTops[m_ViewIndex]);
+ ExpandYAtViewPlane(lightPositionVS, l2, viewPlaneBottoms[m_ViewIndex]);
+ ExpandYAtViewPlane(lightPositionVS, l2, viewPlaneTops[m_ViewIndex]);
m_TileYRange.Clamp(0, (short)(tileCount.y - 1));
// Calculate tile plane ranges for cone.
- for (var planeIndex = m_TileYRange.start + 1; planeIndex <= m_TileYRange.end; planeIndex++)
+ for (var planeIndex = m_TileYRange.start; planeIndex <= m_TileYRange.end + 1; planeIndex++)
{
var planeRange = InclusiveRange.empty;
@@ -223,51 +206,55 @@ bool ConicPointIsValid(float3 p) =>
// Intersect lines with y-plane and clip if needed.
var l1t = math.dot(-lightPositionVS, planeNormal) / math.dot(l1, planeNormal);
var l1x = lightPositionVS + l1 * l1t;
- if (l1t >= 0 && l1t <= 1 && l1x.z >= near) planeRange.Expand((short)math.clamp(ViewToTileSpace(l1x).x, 0, tileCount.x - 1));
+ if (l1t >= 0 && l1t <= 1 && IsInDepthRange(l1x)) ExpandTileX(ref planeRange, ViewToTileSpace(l1x).x);
var l2t = math.dot(-lightPositionVS, planeNormal) / math.dot(l2, planeNormal);
var l2x = lightPositionVS + l2 * l2t;
- if (l2t >= 0 && l2t <= 1 && l2x.z >= near) planeRange.Expand((short)math.clamp(ViewToTileSpace(l2x).x, 0, tileCount.x - 1));
+ if (l2t >= 0 && l2t <= 1 && IsInDepthRange(l2x)) ExpandTileX(ref planeRange, ViewToTileSpace(l2x).x);
- if (IntersectCircleYPlane(planeY, baseCenter, lightDirectionVS, baseUY, baseVY, baseRadius, out var circleTile0, out var circleTile1))
+ if (IntersectCirclePlane(math.float4(0, 1, -planeY, 0), baseCenter, baseUY, baseVY, baseRadius, out var circleTile0, out var circleTile1))
{
- if (circleTile0.z >= near) planeRange.Expand((short)math.clamp(ViewToTileSpace(circleTile0).x, 0, tileCount.x - 1));
- if (circleTile1.z >= near) planeRange.Expand((short)math.clamp(ViewToTileSpace(circleTile1).x, 0, tileCount.x - 1));
+ if (IsInDepthRange(circleTile0)) ExpandTileX(ref planeRange, ViewToTileSpace(circleTile0).x);
+ if (IsInDepthRange(circleTile1)) ExpandTileX(ref planeRange, ViewToTileSpace(circleTile1).x);
}
if (coneIsClipping)
{
- var y = planeY * near;
- var r = baseRadius / coneHeight;
- var theta = FindNearConicYTheta(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, y);
- var p0 = math.float3(EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, theta.x).x, y, near);
- var p1 = math.float3(EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, theta.y).x, y, near);
- if (ConicPointIsValid(p0)) planeRange.Expand((short)math.clamp(ViewToTileSpace(p0).x, 0, tileCount.x - 1));
- if (ConicPointIsValid(p1)) planeRange.Expand((short)math.clamp(ViewToTileSpace(p1).x, 0, tileCount.x - 1));
+ nearSection.IntersectRow(planeY * near, out var p0, out var p1);
+ if (ConicPointIsValid(p0)) ExpandTileX(ref planeRange, ViewToTileSpace(p0).x);
+ if (ConicPointIsValid(p1)) ExpandTileX(ref planeRange, ViewToTileSpace(p1).x);
}
- // Write to tile ranges above and below the plane. Note that at `m_Offset` we store Y-range.
- var tileIndex = m_Offset + 1 + planeIndex;
- tileRanges[tileIndex] = InclusiveRange.Merge(tileRanges[tileIndex], planeRange);
- tileRanges[tileIndex - 1] = InclusiveRange.Merge(tileRanges[tileIndex - 1], planeRange);
+ if (coneCrossesFar)
+ {
+ farSection.IntersectRow(planeY * far, out var p0, out var p1);
+ if (ConicPointIsValid(p0)) ExpandTileX(ref planeRange, ViewToTileSpace(p0).x);
+ if (ConicPointIsValid(p1)) ExpandTileX(ref planeRange, ViewToTileSpace(p1).x);
+ }
+
+ MergeTileRangeRows(planeIndex, planeRange);
}
}
m_TileYRange.Clamp(0, (short)(tileCount.y - 1));
// Calculate tile plane ranges for sphere.
- for (var planeIndex = m_TileYRange.start + 1; planeIndex <= m_TileYRange.end; planeIndex++)
+ for (var planeIndex = m_TileYRange.start; planeIndex <= m_TileYRange.end + 1; planeIndex++)
{
var planeRange = InclusiveRange.empty;
var planeY = math.lerp(viewPlaneBottoms[m_ViewIndex], viewPlaneTops[m_ViewIndex], planeIndex * tileScaleInv.y);
- GetSphereYPlaneHorizon(lightPositionVS, range, near, sphereClipRadius, planeY, out var sphereTile0, out var sphereTile1);
- if (SpherePointIsValid(sphereTile0)) planeRange.Expand((short)math.clamp(ViewToTileSpace(sphereTile0).x, 0, tileCount.x - 1));
- if (SpherePointIsValid(sphereTile1)) planeRange.Expand((short)math.clamp(ViewToTileSpace(sphereTile1).x, 0, tileCount.x - 1));
+ GetSphereYPlaneHorizon(lightPositionVS, range, planeY, out var sphereTile0, out var sphereTile1);
+ ExpandTileXIfInSphereCap(ref planeRange, sphereTile0, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ ExpandTileXIfInSphereCap(ref planeRange, sphereTile1, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ for (var i = 0; i < 2; i++)
+ {
+ GetSphereSectionRowPoints(lightPositionVS, rangesq, i == 0 ? near : far, planeY, out var section0, out var section1);
+ ExpandTileXIfInSphereCap(ref planeRange, section0, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ ExpandTileXIfInSphereCap(ref planeRange, section1, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot);
+ }
- var tileIndex = m_Offset + 1 + planeIndex;
- tileRanges[tileIndex] = InclusiveRange.Merge(tileRanges[tileIndex], planeRange);
- tileRanges[tileIndex - 1] = InclusiveRange.Merge(tileRanges[tileIndex - 1], planeRange);
+ MergeTileRangeRows(planeIndex, planeRange);
}
tileRanges[m_Offset] = m_TileYRange;
@@ -276,120 +263,160 @@ bool ConicPointIsValid(float3 p) =>
void TileLightOrthographic(int lightIndex)
{
var light = lights[lightIndex];
+ if (light.lightType != LightType.Point && light.lightType != LightType.Spot)
+ {
+ return;
+ }
+
var lightToWorld = (float4x4)light.localToWorldMatrix;
var lightPosVS = math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c3.xyz, 1)).xyz;
lightPosVS.z *= -1;
- ExpandOrthographic(lightPosVS);
+ if (IsInDepthRange(lightPosVS)) ExpandOrthographic(lightPosVS);
var lightDirVS = math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c2.xyz, 0)).xyz;
lightDirVS.z *= -1;
lightDirVS = math.normalize(lightDirVS);
+ var isSpot = light.lightType == LightType.Spot;
var halfAngle = math.radians(light.spotAngle * 0.5f);
var range = light.range;
var rangeSq = square(range);
var cosHalfAngle = math.cos(halfAngle);
+ var sinHalfAngle = math.sin(halfAngle);
var coneHeight = cosHalfAngle * range;
- var coneHeightSq = square(coneHeight);
- var coneHeightInv = 1f / coneHeight;
- var coneHeightInvSq = square(coneHeightInv);
-
- bool SpherePointIsValid(float3 p) => light.lightType == LightType.Point ||
- math.dot(math.normalize(p - lightPosVS), lightDirVS) >= cosHalfAngle;
-
- var sphereBoundY0 = lightPosVS - math.float3(0, range, 0);
- var sphereBoundY1 = lightPosVS + math.float3(0, range, 0);
- var sphereBoundX0 = lightPosVS - math.float3(range, 0, 0);
- var sphereBoundX1 = lightPosVS + math.float3(range, 0, 0);
- if (SpherePointIsValid(sphereBoundY0)) ExpandOrthographic(sphereBoundY0);
- if (SpherePointIsValid(sphereBoundY1)) ExpandOrthographic(sphereBoundY1);
- if (SpherePointIsValid(sphereBoundX0)) ExpandOrthographic(sphereBoundX0);
- if (SpherePointIsValid(sphereBoundX1)) ExpandOrthographic(sphereBoundX1);
+ // The outline of the sphere is its equator facing the camera, clipped to the depth range, and the circles cut by
+ // the near and far planes.
+ var sphereOutline = math.bool3(IsInDepthRange(lightPosVS), math.abs(near - lightPosVS.z) <= range, math.abs(far - lightPosVS.z) <= range);
+ for (var i = 0; i < 3; i++)
+ {
+ if (!sphereOutline[i])
+ continue;
+ var depth = i == 0 ? lightPosVS.z : i == 1 ? near : far;
+ var radius = math.sqrt(rangeSq - square(depth - lightPosVS.z));
+ ExpandOrthographicIfInSphereCap(math.float3(lightPosVS.x - radius, lightPosVS.y, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot);
+ ExpandOrthographicIfInSphereCap(math.float3(lightPosVS.x + radius, lightPosVS.y, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot);
+ ExpandOrthographicIfInSphereCap(math.float3(lightPosVS.x, lightPosVS.y - radius, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot);
+ ExpandOrthographicIfInSphereCap(math.float3(lightPosVS.x, lightPosVS.y + radius, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot);
+ }
var circleCenter = lightPosVS + lightDirVS * coneHeight;
- var circleRadius = math.sqrt(rangeSq - coneHeightSq);
- var circleRadiusSq = square(circleRadius);
- var circleUp = math.normalize(math.float3(0, 1, 0) - lightDirVS * lightDirVS.y);
- var circleRight = math.normalize(math.float3(1, 0, 0) - lightDirVS * lightDirVS.x);
- var circleBoundY0 = circleCenter - circleUp * circleRadius;
- var circleBoundY1 = circleCenter + circleUp * circleRadius;
-
- if (light.lightType == LightType.Spot)
+ var circleRadius = range * sinHalfAngle;
+ var coneU = math.normalize(math.cross(lightDirVS, math.abs(lightDirVS.x) < 0.5f ? math.float3(1, 0, 0) : math.float3(0, 1, 0)));
+ var coneV = math.cross(lightDirVS, coneU);
+ var nearSection = new ConeSection(near, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle);
+ var farSection = new ConeSection(far, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle);
+ var circleExtentZ = circleRadius * math.sqrt(math.saturate(1.0f - square(lightDirVS.z)));
+ var coneMinZ = math.min(circleCenter.z - circleExtentZ, lightPosVS.z);
+ var coneMaxZ = math.max(circleCenter.z + circleExtentZ, lightPosVS.z);
+ var coneCrosses = math.bool2(near >= coneMinZ && near <= coneMaxZ, far >= coneMinZ && far <= coneMaxZ);
+ float3 l1 = 0, l2 = 0;
+ var coneDistanceTolerance = 1e-5f * (math.length(lightPosVS) + range);
+
+ if (isSpot)
{
- var circleBoundX0 = circleCenter - circleRight * circleRadius;
- var circleBoundX1 = circleCenter + circleRight * circleRadius;
- ExpandOrthographic(circleBoundY0);
- ExpandOrthographic(circleBoundY1);
- ExpandOrthographic(circleBoundX0);
- ExpandOrthographic(circleBoundX1);
- }
+ // Extremes of the cone base circle, and its points on the near and far planes.
+ var circleUp = math.normalize(math.float3(0, 1, 0) - lightDirVS * lightDirVS.y) * circleRadius;
+ var circleRight = math.normalize(math.float3(1, 0, 0) - lightDirVS * lightDirVS.x) * circleRadius;
+ ExpandOrthographicIfInDepthRange(circleCenter - circleUp);
+ ExpandOrthographicIfInDepthRange(circleCenter + circleUp);
+ ExpandOrthographicIfInDepthRange(circleCenter - circleRight);
+ ExpandOrthographicIfInDepthRange(circleCenter + circleRight);
+ for (var i = 0; i < 2; i++)
+ {
+ if (GetCircleClipPoints(circleCenter, lightDirVS, circleRadius, i == 0 ? near : far, out var clip0, out var clip1))
+ {
+ ExpandOrthographic(clip0);
+ ExpandOrthographic(clip1);
+ }
+ }
- m_TileYRange.Clamp(0, (short)(tileCount.y - 1));
+ // Extremes of the cone sections with the near and far planes.
+ for (var i = 0; i < 2; i++)
+ {
+ if (!coneCrosses[i])
+ continue;
+ var section = i == 0 ? nearSection : farSection;
+ section.GetYExtremes(out var p0Y, out var p1Y);
+ section.GetXExtremes(out var p0X, out var p1X);
+ if (IsOnCone(p0Y, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p0Y);
+ if (IsOnCone(p1Y, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p1Y);
+ if (IsOnCone(p0X, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p0X);
+ if (IsOnCone(p1X, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p1X);
+ }
- // Find two lines in screen-space for the cone if the light is a spot.
- float coneDir0X = 0, coneDir0YInv = 0, coneDir1X = 0, coneDir1YInv = 0;
- if (light.lightType == LightType.Spot)
- {
- // Distance from light position to and radius of sphere fitted to the end of the cone.
- var sphereDistance = coneHeight + circleRadiusSq * coneHeightInv;
- var sphereRadius = math.sqrt(square(circleRadiusSq) * coneHeightInvSq + circleRadiusSq);
- var directionXYSqInv = math.rcp(math.lengthsq(lightDirVS.xy));
- var polarIntersection = -circleRadiusSq * coneHeightInv * directionXYSqInv * lightDirVS.xy;
- var polarDir = math.sqrt((square(sphereRadius) - math.lengthsq(polarIntersection)) * directionXYSqInv) * math.float2(lightDirVS.y, -lightDirVS.x);
- var conePBase = lightPosVS.xy + sphereDistance * lightDirVS.xy + polarIntersection;
- var coneP0 = conePBase - polarDir;
- var coneP1 = conePBase + polarDir;
-
- coneDir0X = coneP0.x - lightPosVS.x;
- coneDir0YInv = math.rcp(coneP0.y - lightPosVS.y);
- coneDir1X = coneP1.x - lightPosVS.x;
- coneDir1YInv = math.rcp(coneP1.y - lightPosVS.y);
+ // Silhouette lines of the cone as seen along the view direction.
+ GetConeSideTangentPoints(math.float3(0, 0, -1), lightDirVS, cosHalfAngle, circleRadius, coneHeight, range, coneU, coneV, out l1, out l2);
}
- // Tile plane ranges
- for (var planeIndex = m_TileYRange.start + 1; planeIndex <= m_TileYRange.end; planeIndex++)
+ m_TileYRange.Clamp(0, (short)(tileCount.y - 1));
+
+ // Tile plane ranges; the rows are the planes y = planeY.
+ for (var planeIndex = m_TileYRange.start; planeIndex <= m_TileYRange.end + 1; planeIndex++)
{
var planeRange = InclusiveRange.empty;
-
- // Sphere
var planeY = math.lerp(viewPlaneBottoms[m_ViewIndex], viewPlaneTops[m_ViewIndex], planeIndex * tileScaleInv.y);
- var sphereX = math.sqrt(rangeSq - square(planeY - lightPosVS.y));
- var sphereX0 = math.float3(lightPosVS.x - sphereX, planeY, lightPosVS.z);
- var sphereX1 = math.float3(lightPosVS.x + sphereX, planeY, lightPosVS.z);
- if (SpherePointIsValid(sphereX0)) { ExpandRangeOrthographic(ref planeRange, sphereX0.x); }
- if (SpherePointIsValid(sphereX1)) { ExpandRangeOrthographic(ref planeRange, sphereX1.x); }
- if (light.lightType == LightType.Spot)
+ for (var i = 0; i < 3; i++)
{
- // Circle
- if (planeY >= circleBoundY0.y && planeY <= circleBoundY1.y)
+ if (!sphereOutline[i])
+ continue;
+ var depth = i == 0 ? lightPosVS.z : i == 1 ? near : far;
+ var halfWidth = math.sqrt(rangeSq - square(depth - lightPosVS.z) - square(planeY - lightPosVS.y));
+ ExpandRangeOrthographicIfInSphereCap(ref planeRange, math.float3(lightPosVS.x - halfWidth, planeY, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot);
+ ExpandRangeOrthographicIfInSphereCap(ref planeRange, math.float3(lightPosVS.x + halfWidth, planeY, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot);
+ }
+
+ if (isSpot)
+ {
+ if (IntersectCirclePlane(math.float4(0, 1, 0, -planeY), circleCenter, coneU, coneV, circleRadius, out var circle0, out var circle1))
{
- var intersectionDistance = (planeY - circleCenter.y) / circleUp.y;
- var closestPointX = circleCenter.x + intersectionDistance * circleUp.x;
- var intersectionDirX = -lightDirVS.z / math.length(math.float3(-lightDirVS.z, 0, lightDirVS.x));
- var sideDistance = math.sqrt(square(circleRadius) - square(intersectionDistance));
- var circleX0 = closestPointX - sideDistance * intersectionDirX;
- var circleX1 = closestPointX + sideDistance * intersectionDirX;
- ExpandRangeOrthographic(ref planeRange, circleX0);
- ExpandRangeOrthographic(ref planeRange, circleX1);
+ if (IsInDepthRange(circle0)) ExpandRangeOrthographic(ref planeRange, circle0.x);
+ if (IsInDepthRange(circle1)) ExpandRangeOrthographic(ref planeRange, circle1.x);
}
- // Cone
- var deltaY = planeY - lightPosVS.y;
- var coneT0 = deltaY * coneDir0YInv;
- var coneT1 = deltaY * coneDir1YInv;
- if (coneT0 >= 0 && coneT0 <= 1) { ExpandRangeOrthographic(ref planeRange, lightPosVS.x + coneT0 * coneDir0X); }
- if (coneT1 >= 0 && coneT1 <= 1) { ExpandRangeOrthographic(ref planeRange, lightPosVS.x + coneT1 * coneDir1X); }
+ var line0 = lightPosVS + l1 * ((planeY - lightPosVS.y) / l1.y);
+ var line1 = lightPosVS + l2 * ((planeY - lightPosVS.y) / l2.y);
+ if (IsOnSegment(line0, lightPosVS, l1)) ExpandRangeOrthographic(ref planeRange, line0.x);
+ if (IsOnSegment(line1, lightPosVS, l2)) ExpandRangeOrthographic(ref planeRange, line1.x);
+
+ for (var i = 0; i < 2; i++)
+ {
+ if (!coneCrosses[i])
+ continue;
+ (i == 0 ? nearSection : farSection).IntersectRow(planeY, out var p0, out var p1);
+ if (IsOnCone(p0, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandRangeOrthographic(ref planeRange, p0.x);
+ if (IsOnCone(p1, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandRangeOrthographic(ref planeRange, p1.x);
+ }
}
- var tileIndex = m_Offset + 1 + planeIndex;
- tileRanges[tileIndex] = InclusiveRange.Merge(tileRanges[tileIndex], planeRange);
- tileRanges[tileIndex - 1] = InclusiveRange.Merge(tileRanges[tileIndex - 1], planeRange);
+ MergeTileRangeRows(planeIndex, planeRange);
}
tileRanges[m_Offset] = m_TileYRange;
}
+ // Whether p = origin + t * line lies on the segment (t in [0, 1]) and in the depth range.
+ bool IsOnSegment(float3 p, float3 origin, float3 line)
+ {
+ var t = math.dot(p - origin, line) / math.lengthsq(line);
+ return t >= 0 && t <= 1 && IsInDepthRange(p);
+ }
+
+ void ExpandOrthographicIfInDepthRange(float3 positionVS)
+ {
+ if (IsInDepthRange(positionVS)) ExpandOrthographic(positionVS);
+ }
+
+ void ExpandOrthographicIfInSphereCap(float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot)
+ {
+ if (IsInSphereCap(positionVS, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot)) ExpandOrthographic(positionVS);
+ }
+
+ void ExpandRangeOrthographicIfInSphereCap(ref InclusiveRange range, float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot)
+ {
+ if (IsInSphereCap(positionVS, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot)) ExpandRangeOrthographic(ref range, positionVS.x);
+ }
+
static readonly float3[] k_CubePoints =
{
new(-1, -1, -1),
@@ -435,8 +462,9 @@ void TileReflectionProbe(int index)
// The vertices of the cube in view space.
var points = new NativeArray(k_CubePoints.Length, Allocator.Temp);
- // This is initially filled with just the cube vertices that lie in front of the near plane.
- var clippedPoints = new NativeArray(k_CubePoints.Length + k_CubeLineIndices.Length * 3, Allocator.Temp);
+ // This is initially filled with just the cube vertices that lie between the near and far planes. Each edge can add
+ // two more points where it crosses them.
+ var clippedPoints = new NativeArray(k_CubePoints.Length + k_CubeLineIndices.Length * 3 * 2, Allocator.Temp);
var clippedPointsCount = 0;
var leftmostIndex = 0;
for (var i = 0; i < k_CubePoints.Length; i++)
@@ -445,7 +473,7 @@ void TileReflectionProbe(int index)
var point = math.mul(worldToViews[m_ViewIndex], math.float4(rotatedPointsWS, 1)).xyz;
point.z *= -1;
points[i] = point;
- if (point.z >= near)
+ if (IsInDepthRange(point))
{
var clippedPoint = isOrthographic ? point.xy : point.xy/point.z;
var clippedIndex = clippedPointsCount++;
@@ -454,8 +482,8 @@ void TileReflectionProbe(int index)
}
}
- // Clip the cube's line segments with the near plane, and add the new vertices to clippedPoints. Only lines
- // that are clipped will generate new vertices.
+ // Clip the cube's line segments with the near and far planes, and add the new vertices to clippedPoints. Only
+ // lines that cross a plane generate new vertices.
for (var i = 0; i < k_CubeLineIndices.Length; i++)
{
var indices = k_CubeLineIndices[i];
@@ -463,12 +491,11 @@ void TileReflectionProbe(int index)
for (var j = 0; j < 3; j++)
{
var p1 = points[indices[j+1]];
- // The entire line is in front of the near plane.
- if (p0.z < near && p1.z < near) continue;
- // Check whether the line needs clipping.
- if (p0.z < near || p1.z < near)
+ for (var k = 0; k < 2; k++)
{
- var d = (near - p0.z) / (p1.z - p0.z);
+ var depth = k == 0 ? near : far;
+ if ((p0.z < depth) == (p1.z < depth)) continue;
+ var d = (depth - p0.z) / (p1.z - p0.z);
var p = math.lerp(p0, p1, d);
var clippedPoint = isOrthographic ? p.xy : p.xy/p.z;
var clippedIndex = clippedPointsCount++;
@@ -517,7 +544,7 @@ void TileReflectionProbe(int index)
m_TileYRange.Clamp(0, (short)(tileCount.y - 1));
// Calculate tile plane ranges for sphere.
- for (var planeIndex = m_TileYRange.start + 1; planeIndex <= m_TileYRange.end; planeIndex++)
+ for (var planeIndex = m_TileYRange.start; planeIndex <= m_TileYRange.end + 1; planeIndex++)
{
var planeRange = InclusiveRange.empty;
@@ -535,12 +562,10 @@ void TileReflectionProbe(int index)
var p = math.float3(x, planeY, 1);
var pTS = isOrthographic ? ViewToTileSpaceOrthographic(p) : ViewToTileSpace(p);
- planeRange.Expand((short)math.clamp(pTS.x, 0, tileCount.x - 1));
+ ExpandTileX(ref planeRange, pTS.x);
}
- var tileIndex = m_Offset + 1 + planeIndex;
- tileRanges[tileIndex] = InclusiveRange.Merge(tileRanges[tileIndex], planeRange);
- tileRanges[tileIndex - 1] = InclusiveRange.Merge(tileRanges[tileIndex - 1], planeRange);
+ MergeTileRangeRows(planeIndex, planeRange);
}
tileRanges[m_Offset] = m_TileYRange;
@@ -567,182 +592,140 @@ float2 ViewToTileSpaceOrthographic(float3 positionVS)
return (positionVS.xy * viewToViewportScaleBiases[m_ViewIndex].xy + viewToViewportScaleBiases[m_ViewIndex].zw) * tileScale;
}
- ///
- /// Expands the tile Y range and the X range in the row containing the position.
- ///
- void ExpandY(float3 positionVS)
+ void ExpandY(float3 positionVS) => ExpandTile(ViewToTileSpace(positionVS));
+
+ bool IsInDepthRange(float3 positionVS) => positionVS.z >= near && positionVS.z <= far;
+
+ // Whether a point of a cone section lies on the cone, up to its base. Also rejects points off the cone, which
+ // degenerate sections can produce. Tolerates ~1e-4 rad, or a distance from the surface on the order of the float
+ // precision of the light's coordinates.
+ internal static bool IsOnCone(float3 p, float3 vertex, float3 axis, float cosHalfAngle, float sinHalfAngle, float coneHeight, float distanceTolerance)
{
- // var positionTS = math.clamp(ViewToTileSpace(positionVS), 0, tileCount - 1);
- var positionTS = ViewToTileSpace(positionVS);
- var tileY = (int)positionTS.y;
- var tileX = (int)positionTS.x;
- m_TileYRange.Expand((short)math.clamp(tileY, 0, tileCount.y - 1));
- if (tileY >= 0 && tileY < tileCount.y && tileX >= 0 && tileX < tileCount.x)
- {
- var rowXRange = tileRanges[m_Offset + 1 + tileY];
- rowXRange.Expand((short)tileX);
- tileRanges[m_Offset + 1 + tileY] = rowXRange;
- }
+ var q = p - vertex;
+ var length = math.length(q);
+ var axial = math.dot(q, axis);
+ return axial >= cosHalfAngle * length - sinHalfAngle * (1e-4f * length + distanceTolerance) && axial <= coneHeight;
}
- ///
- /// Expands the tile Y range and the X range in the row containing the position.
- ///
- void ExpandOrthographic(float3 positionVS)
+ // For points on a light's sphere: skips points outside the depth range and, for spot lights, outside the cone.
+ bool IsInSphereCap(float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot) =>
+ IsInDepthRange(positionVS) && (!isSpot || math.dot(math.normalize(positionVS - lightPositionVS), lightDirectionVS) >= cosHalfAngle);
+
+ void ExpandYIfInSphereCap(float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot)
{
- // var positionTS = math.clamp(ViewToTileSpace(positionVS), 0, tileCount - 1);
- var positionTS = ViewToTileSpaceOrthographic(positionVS);
- var tileY = (int)positionTS.y;
- var tileX = (int)positionTS.x;
- m_TileYRange.Expand((short)math.clamp(tileY, 0, tileCount.y - 1));
- if (tileY >= 0 && tileY < tileCount.y && tileX >= 0 && tileX < tileCount.x)
- {
- var rowXRange = tileRanges[m_Offset + 1 + tileY];
- rowXRange.Expand((short)tileX);
- tileRanges[m_Offset + 1 + tileY] = rowXRange;
- }
+ if (IsInSphereCap(positionVS, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot)) ExpandY(positionVS);
}
- void ExpandRangeOrthographic(ref InclusiveRange range, float xVS)
+ void ExpandTileXIfInSphereCap(ref InclusiveRange range, float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot)
{
- range.Expand((short)math.clamp(ViewToTileSpaceOrthographic(xVS).x, 0, tileCount.x - 1));
+ if (IsInSphereCap(positionVS, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot)) ExpandTileX(ref range, ViewToTileSpace(positionVS).x);
}
- static float square(float x) => x * x;
-
- ///
- /// Finds the two horizon points seen from (0, 0) of a sphere projected onto either XZ or YZ. Takes clipping into account.
- ///
- static void GetSphereHorizon(float2 center, float radius, float near, float clipRadius, out float2 p0, out float2 p1)
+ // Expands the tile Y range where the segment from origin to origin + line crosses the view plane y = planeY * z.
+ void ExpandYAtViewPlane(float3 origin, float3 line, float planeY)
{
- var direction = math.normalize(center);
-
- // Distance from camera to center of sphere
- var d = math.length(center);
-
- // Distance from camera to sphere horizon edge
- var l = math.sqrt(d * d - radius * radius);
-
- // Height of circle horizon
- var h = l * radius / d;
+ var planeNormal = math.float3(0, 1, -planeY);
+ var t = math.dot(-origin, planeNormal) / math.dot(line, planeNormal);
+ var positionVS = origin + line * t;
+ if (t >= 0 && t <= 1 && IsInDepthRange(positionVS)) ExpandY(positionVS);
+ }
- // Center of circle horizon
- var c = direction * (l * h / radius);
+ void ExpandOrthographic(float3 positionVS) => ExpandTile(ViewToTileSpaceOrthographic(positionVS));
- p0 = math.float2(float.MinValue, 1f);
- p1 = math.float2(float.MaxValue, 1f);
+ void ExpandRangeOrthographic(ref InclusiveRange range, float xVS) => ExpandTileX(ref range, ViewToTileSpaceOrthographic(xVS).x);
- // Handle clipping
- if (center.y - radius < near)
+ ///
+ /// Expands the tile Y range and the X range in the row containing the tile-space position.
+ ///
+ void ExpandTile(float2 positionTS)
+ {
+ // NaN marks a missed intersection; skip it, as float-to-int casts of NaN differ across Burst, IL2CPP and Mono.
+ if (math.any(math.isnan(positionTS))) return;
+ // Floor, not truncate, so (-1, 0) maps off-screen; clamp before casting to keep the cast in range.
+ var tile = (int2)math.clamp(math.floor(positionTS), -1f, (float2)tileCount);
+ m_TileYRange.Expand((short)math.clamp(tile.y, 0, tileCount.y - 1));
+ // Keep one tile of off-screen slack; TileRangeExpansionJob only sets on-screen columns,
+ // so fully off-screen rows cover nothing while rows reaching an edge keep the edge tile.
+ if (tile.y >= 0 && tile.y < tileCount.y)
{
- p0 = math.float2(center.x + clipRadius, near);
- p1 = math.float2(center.x - clipRadius, near);
+ var rowXRange = tileRanges[m_Offset + 1 + tile.y];
+ rowXRange.Expand((short)tile.x);
+ tileRanges[m_Offset + 1 + tile.y] = rowXRange;
}
+ }
- // Circle horizon points
- var c0 = c + math.float2(-direction.y, direction.x) * h;
- if (square(d) >= square(radius) && c0.y >= near)
+ // Tile-space X counterpart of ExpandTile, for a row-boundary range.
+ void ExpandTileX(ref InclusiveRange range, float tileX)
+ {
+ if (math.isnan(tileX)) return;
+ range.Expand((short)math.clamp(math.floor(tileX), -1f, tileCount.x));
+ }
+
+ // Merge planeRange into the rows above and below boundary planeIndex; m_Offset holds the Y range.
+ void MergeTileRangeRows(int planeIndex, InclusiveRange planeRange)
+ {
+ if (planeIndex < tileCount.y)
{
- if (c0.x > p0.x) { p0 = c0; }
- if (c0.x < p1.x) { p1 = c0; }
+ var above = m_Offset + 1 + planeIndex;
+ tileRanges[above] = InclusiveRange.Merge(tileRanges[above], planeRange);
}
-
- var c1 = c + math.float2(direction.y, -direction.x) * h;
- if (square(d) >= square(radius) && c1.y >= near)
+ if (planeIndex > 0)
{
- if (c1.x > p0.x) { p0 = c1; }
- if (c1.x < p1.x) { p1 = c1; }
+ var below = m_Offset + planeIndex;
+ tileRanges[below] = InclusiveRange.Merge(tileRanges[below], planeRange);
}
}
- static void GetSphereYPlaneHorizon(float3 center, float sphereRadius, float near, float clipRadius, float y, out float3 left, out float3 right)
+ static float square(float x) => x * x;
+
+ ///
+ /// Returns the points where the tangents from the origin touch a 2D circle, or NaN if the origin is inside it.
+ ///
+ static void GetCircleHorizon(float2 center, float radius, out float2 p0, out float2 p1)
{
- // Note: The y-plane is the plane that is determined by `y` in that it contains the vector (1, 0, 0)
- // and goes through the points (0, y, 1) and (0, 0, 0). This would become a straight line in screen-space, and so it
- // represents the boundary between two rows of tiles.
-
- // Near-plane clipping - will get overwritten if no clipping is needed.
- // `y` is given for the view plane (Z=1), scale it so that it is on the near plane instead.
- var yNear = y * near;
- // Find the two points of intersection between the clip circle of the sphere and the y-plane.
- // Found using Pythagoras with a right triangle formed by three points:
- // (a) center of the clip circle
- // (b) a point straight above the clip circle center on the y-plane
- // (c) a point that is both on the circle and the y-plane (this is the point we want to find in the end)
- // The hypotenuse is formed by (a) and (c) with length equal to the clip radius. The known side is
- // formed by (a) and (b) and is simply the distance from the center to the y-plane along the y-axis.
- // The remaining side gives us the x-displacement needed to find the intersection points.
- var clipHalfWidth = math.sqrt(square(clipRadius) - square(yNear - center.y));
- left = math.float3(center.x - clipHalfWidth, yNear, near);
- right = math.float3(center.x + clipHalfWidth, yNear, near);
-
- // Basis vectors in the y-plane for being able to parameterize the plane.
+ // With d the distance to the center and l the tangent length, the points are (l^2 * center +- l * r * perp(center)) / d^2.
+ var dSq = math.lengthsq(center);
+ var l = math.sqrt(dSq - square(radius));
+ var side = l * radius * math.float2(-center.y, center.x);
+ p0 = (square(l) * center + side) / dSq;
+ p1 = (square(l) * center - side) / dSq;
+ }
+
+ ///
+ /// Returns the horizon points, as seen from the origin, of the circle cut from a sphere by the plane through the
+ /// origin and the view-plane row at height y. NaN if the plane misses the sphere or the origin is inside the circle.
+ ///
+ static void GetSphereYPlaneHorizon(float3 center, float sphereRadius, float y, out float3 left, out float3 right)
+ {
+ // Basis vectors in the y-plane, which contains (1, 0, 0) and (0, y, 1), and its normal (0, 1, -y).
var planeU = math.normalize(math.float3(0, y, 1));
var planeV = math.float3(1, 0, 0);
-
- // Calculate the normal of the y-plane. Found from: (0, y, 1) Ć (1, 0, 0) = (0, 1, -y)
- // This is used to represent the plane along with the origin, which is just 0 and thus doesn't show up
- // in the calculations.
var normal = math.normalize(math.float3(0, 1, -y));
- // We want to first find the circle from the intersection of the y-plane and the sphere.
-
- // The shortest distance from the sphere center and the y-plane. The sign determines which side of the plane
- // the center is on.
- var signedDistance = math.dot(normal, center);
-
- // Unsigned shortest distance from the sphere center to the plane.
- var distanceToPlane = math.abs(signedDistance);
-
- // The center of the intersection circle in the y-plane, which is the point on the plane closest to the
- // sphere center. I.e. this is at `distanceToPlane` from the center.
+ // The section circle is centered at the point of the plane closest to the sphere center.
+ var distanceToPlane = math.dot(normal, center);
var centerOnPlane = math.float2(math.dot(center, planeU), math.dot(center, planeV));
-
- // Distance from origin to the circle center.
- var distanceInPlane = math.length(centerOnPlane);
-
- // Direction from origin to the circle center.
- var directionPS = centerOnPlane / distanceInPlane;
-
- // Calculate the radius of the circle using Pythagoras. We know that any point on the circle is a point on
- // the sphere. Thus we can construct a triangle with the sphere center, circle center, and a point on the
- // circle. We then want to find its distance to the circle center, as that will be equal to the radius. As
- // the point is on the sphere, it must be `sphereRadius` from the sphere center, forming the hypotenuse. The
- // other side is between the sphere and circle centers, which we've already calculated to be
- // `distanceToPlane`.
var circleRadius = math.sqrt(square(sphereRadius) - square(distanceToPlane));
- // Now that we have the circle, we can find the horizon points. Since we've parametrized the plane, we can
- // just do this in 2D.
-
- // Any of these conditions will yield NaN due to negative square roots. They are signs that clipping is needed,
- // so we fallback on the already calculated values in that case.
- if (square(distanceToPlane) <= square(sphereRadius) && square(circleRadius) <= square(distanceInPlane))
- {
- // Distance from origin to circle horizon edge.
- var l = math.sqrt(square(distanceInPlane) - square(circleRadius));
-
- // Height of circle horizon.
- var h = l * circleRadius / distanceInPlane;
-
- // Center of circle horizon.
- var c = directionPS * (l * h / circleRadius);
-
- // Calculate the horizon points in the plane.
- var leftOnPlane = c + math.float2(directionPS.y, -directionPS.x) * h;
- var rightOnPlane = c + math.float2(-directionPS.y, directionPS.x) * h;
-
- // Transform horizon points to view space and use if not clipped.
- var leftCandidate = leftOnPlane.x * planeU + leftOnPlane.y * planeV;
- if (leftCandidate.z >= near) left = leftCandidate;
+ GetCircleHorizon(centerOnPlane, circleRadius, out var leftOnPlane, out var rightOnPlane);
+ left = leftOnPlane.x * planeU + leftOnPlane.y * planeV;
+ right = rightOnPlane.x * planeU + rightOnPlane.y * planeV;
+ }
- var rightCandidate = rightOnPlane.x * planeU + rightOnPlane.y * planeV;
- if (rightCandidate.z >= near) right = rightCandidate;
- }
+ ///
+ /// Returns the points where the plane through the origin and the view-plane row at height planeY crosses the
+ /// circle cut from a sphere by the plane z = depth, or NaN if there are none.
+ ///
+ static void GetSphereSectionRowPoints(float3 center, float radiusSq, float depth, float planeY, out float3 p0, out float3 p1)
+ {
+ var y = planeY * depth;
+ var halfWidth = math.sqrt(radiusSq - square(depth - center.z) - square(y - center.y));
+ p0 = math.float3(center.x - halfWidth, y, depth);
+ p1 = math.float3(center.x + halfWidth, y, depth);
}
///
- /// Finds the two points of intersection of a 3D circle and the near plane.
+ /// Finds the two points of intersection of a 3D circle and the plane z = near.
///
static bool GetCircleClipPoints(float3 circleCenter, float3 circleNormal, float circleRadius, float near, out float3 p0, out float3 p1)
{
@@ -779,32 +762,6 @@ static bool GetCircleClipPoints(float3 circleCenter, float3 circleNormal, float
return math.abs(distance) <= circleRadius;
}
- static (float, float) IntersectEllipseLine(float a, float b, float3 line)
- {
- // The line is represented as a homogenous 2D line {u, v, w} such that ux + vy + w = 0.
- // The ellipse is represented by the implicit equation x^2/a^2 + y^2/b^2 = 1.
- // We solve the line equation for y: y = (ux + w) / v
- // We then substitute this into the ellipse equation and expand and re-arrange a bit:
- // x^2/a^2 + ((ux + w) / v)^2/b^2 = 1 =>
- // x^2/a^2 + ((ux + w)^2 / v^2)/b^2 = 1 =>
- // x^2/a^2 + (ux + w)^2/(v^2 b^2) = 1 =>
- // x^2/a^2 + (u^2 x^2 + w^2 + 2 u x w)/(v^2 b^2) = 1 =>
- // x^2/a^2 + x^2 u^2 / (v^2 b^2) + w^2/(v^2 b^2) + x 2 u w / (v^2 b^2) = 1 =>
- // x^2 (1/a^2 + u^2 / (v^2 b^2)) + x 2 u w / (v^2 b^2) + w^2 / (v^2 b^2) - 1 = 0
- // We now have a quadratic equation with:
- // a = 1/a^2 + u^2 / (v^2 b^2)
- // b = 2 u w / (v^2 b^2)
- // c = w^2 / (v^2 b^2) - 1
- var div = math.rcp(square(line.y) * square(b));
- var qa = 1f / square(a) + square(line.x) * div;
- var qb = 2f * line.x * line.z * div;
- var qc = square(line.z) * div - 1f;
- var sqrtD = math.sqrt(qb * qb - 4f * qa * qc);
- var x1 = (-qb + sqrtD) / (2f * qa);
- var x2 = (-qb - sqrtD) / (2f * qa);
- return (x1, x2);
- }
-
///
/// Calculates the horizon of a circle orthogonally projected to a plane as seen from the origin on the plane.
///
@@ -814,7 +771,7 @@ static bool GetCircleClipPoints(float3 circleCenter, float3 circleNormal, float
/// The minor axis of the ellipse formed by the projection of the circle.
/// The first horizon point expressed as factors of and .
/// The second horizon point expressed as factors of and .
- static void GetProjectedCircleHorizon(float2 center, float radius, float2 U, float2 V, out float2 uv1, out float2 uv2)
+ internal static void GetProjectedCircleHorizon(float2 center, float radius, float2 U, float2 V, out float2 uv1, out float2 uv2)
{
// U is assumed to be constructed such that it is never 0, but V can be if the circle projects to a line segment.
// In that case, the solution can be trivially found using U only.
@@ -827,76 +784,47 @@ static void GetProjectedCircleHorizon(float2 center, float radius, float2 U, flo
else
{
var ul = math.length(U);
- var ulinv = math.rcp(ul);
- var vlinv = math.rcp(vl);
// Normalize U and V in the plane.
- var u = U * ulinv;
- var v = V * vlinv;
+ var u = U / ul;
+ var v = V / vl;
// Major and minor axis of the ellipse.
var a = ul * radius;
var b = vl * radius;
- // Project the camera position into a 2D coordinate system with the circle at (0, 0) and
- // the ellipse major and minor axes as the coordinate system axes. This allows us to use the standard
- // form of the ellipse equation, greatly simplifying the calculations.
- var cameraUV = math.float2(math.dot(-center, u), math.dot(-center, v));
-
- // Find the polar line of the camera position in the normalized UV coordinate system.
- var polar = math.float3(cameraUV.x / square(a), cameraUV.y / square(b), -1);
- var (t1, t2) = IntersectEllipseLine(a, b, polar);
-
- // Find Y by putting polar into line equation and solving. Denormalize by dividing by U and V lengths.
- uv1 = math.float2(t1 * ulinv, (-polar.x / polar.y * t1 - polar.z / polar.y) * vlinv);
- uv2 = math.float2(t2 * ulinv, (-polar.x / polar.y * t2 - polar.z / polar.y) * vlinv);
+ // Scale the ellipse to the unit circle, where the tangent points from the camera q are
+ // (q +- sqrt(|q|^2 - 1) * perp(q)) / |q|^2. A camera inside the ellipse has no horizon and yields NaN.
+ var q = math.float2(math.dot(-center, u), math.dot(-center, v)) / math.float2(a, b);
+ var qq = math.lengthsq(q);
+ var side = math.sqrt(qq - 1f) * math.float2(-q.y, q.x);
+ uv1 = (q + side) / qq * radius;
+ uv2 = (q - side) / qq * radius;
}
}
- static bool IntersectCircleYPlane(
- float y, float3 circleCenter, float3 circleNormal, float3 circleU, float3 circleV, float circleRadius,
+ ///
+ /// Intersects a 3D circle with the plane dot(plane.xyz, p) + plane.w = 0.
+ ///
+ static bool IntersectCirclePlane(
+ float4 plane, float3 circleCenter, float3 circleU, float3 circleV, float circleRadius,
out float3 p1, out float3 p2)
{
p1 = p2 = 0;
- // Intersecting a circle with a plane yields 2 points, or the whole circle if the plane and the plane of the
- // circle are the same, or nothing if the planes are parallel but offset. We're only interested in the first
- // case. Our other tests will catch the other cases.
-
- // The two points will be on the line of intersection of the two planes. Thus we first have to find that line.
-
- // Shoot 2 rays along the y-plane and intersect the circle plane. We then transform them into the circle
- // plane, so that we can work in 2D.
- var CdotN = math.dot(circleCenter, circleNormal);
- var h1v = math.float3(1, y, 1) * CdotN / math.dot(math.float3(1, y, 1), circleNormal) - circleCenter;
- var h1 = math.float2(math.dot(h1v, circleU), math.dot(h1v, circleV));
- var h2v = math.float3(-1, y, 1) * CdotN / math.dot(math.float3(-1, y, 1), circleNormal) - circleCenter;
- var h2 = math.float2(math.dot(h2v, circleU), math.dot(h2v, circleV));
-
- var lineDirection = math.normalize(h2 - h1);
- // We now have the direction of the line, and would like to find the point on it that is closest to the
- // circle center. A line in 2D is similar to a plane in 3D. So we can calculate a normal, which is just a
- // perpendicular/orthogonal direction, and then take the dot product to find the distance. This is similar
- // to when calculating the d-term for a plane in 3D, which is also just calculating the closest distance
- // from the origin to the plane.
- var lineNormal = math.float2(lineDirection.y, -lineDirection.x);
- var distToLine = math.dot(h1, lineNormal);
- // We can then get that point on the line by following our normal with the distance we just calculated.
- var lineCenter = lineNormal * distToLine;
-
- // Avoid negative square roots, as this means we've hit one of the cases that we do not care about.
- if (distToLine > circleRadius) return false;
-
- // What's left now is to intersect the line with the circle. We can do so with Pythagoras. Our triangle
- // is made up of `lineCenter`, the circle center and one of the intersection points.
- // We know the distance from `lineCenter` to the circle center (`distToLine`), and the distance from
- // the circle center to one of the intersection points must be the circle radius, as it lies on the
- // circle, forming the hypotenuse.
- var l = math.sqrt(circleRadius * circleRadius - distToLine * distToLine);
-
- // What we found above is the distance from `lineCenter` to each of the intersection points. So we just
- // scrub along the line in both directions using the found distance, and then transform back into view
- // space.
+ // In circle coordinates (s, t), the plane is the line a * s + b * t + k = 0. Parallel planes (a = b = 0)
+ // give the whole circle or nothing, which the other bounds cover.
+ var lineNormal = math.float2(math.dot(plane.xyz, circleU), math.dot(plane.xyz, circleV));
+ var lineNormalLengthSq = math.lengthsq(lineNormal);
+ if (lineNormalLengthSq == 0f) return false;
+
+ var k = math.dot(plane.xyz, circleCenter) + plane.w;
+ var distToLineSq = k * k / lineNormalLengthSq;
+ if (distToLineSq > circleRadius * circleRadius) return false;
+
+ var lineCenter = -k / lineNormalLengthSq * lineNormal;
+ var lineDirection = math.float2(-lineNormal.y, lineNormal.x) * math.rsqrt(lineNormalLengthSq);
+ var l = math.sqrt(circleRadius * circleRadius - distToLineSq);
var x1 = lineCenter + l * lineDirection;
var x2 = lineCenter - l * lineDirection;
p1 = circleCenter + x1.x * circleU + x1.y * circleV;
@@ -905,67 +833,110 @@ static bool IntersectCircleYPlane(
return true;
}
- static void GetConeSideTangentPoints(float3 vertex, float3 axis, float cosHalfAngle, float circleRadius, float coneHeight, float range, float3 circleU, float3 circleV, out float3 l1, out float3 l2)
+ ///
+ /// Finds the cone's silhouette lines from its vertex, as seen along toCamera: the vector from the vertex to the
+ /// camera, or the direction towards the camera for an orthographic projection.
+ ///
+ static void GetConeSideTangentPoints(float3 toCamera, float3 axis, float cosHalfAngle, float circleRadius, float coneHeight, float range, float3 circleU, float3 circleV, out float3 l1, out float3 l2)
{
l1 = l2 = 0;
- if (math.dot(math.normalize(-vertex), axis) >= cosHalfAngle)
+ if (math.dot(math.normalize(toCamera), axis) >= cosHalfAngle)
{
return;
}
- var d = -math.dot(vertex, axis);
- // If d is zero, this leads to a numerical instability in the code later on. This is why we make the value
- // an epsilon if it is zero.
- if (d == 0f) d = 1e-6f;
- var sign = d < 0 ? -1f : 1f;
- // sign *= vertex.z < 0 ? -1f : 1f;
- // `origin` is the center of the circular slice we're about to calculate at distance `d` from the `vertex`.
- var origin = vertex + axis * d;
- // Get the radius of the circular slice of the cone at the `origin`.
- var radius = math.abs(d) * circleRadius / coneHeight;
- // `circleU` and `circleV` are the two vectors perpendicular to the cone's axis. `cameraUV` is thus the
- // position of the camera projected onto the plane of the circular slice. This basically creates a new
- // 2D coordinate space, with (0, 0) located at the center of the circular slice, which why this variable
- // is called `origin`.
- var cameraUV = math.float2(math.dot(circleU, -origin), math.dot(circleV, -origin));
- // Use homogeneous coordinates to find the tangents.
- var polar = math.float3(cameraUV, -square(radius));
- var p1 = math.float2(-1, -polar.x / polar.y * (-1) - polar.z / polar.y);
- var p2 = math.float2(1, -polar.x / polar.y * 1 - polar.z / polar.y);
- var lineDirection = math.normalize(p2 - p1);
- var lineNormal = math.float2(lineDirection.y, -lineDirection.x);
- var distToLine = math.dot(p1, lineNormal);
- var lineCenter = lineNormal * distToLine;
- var l = math.sqrt(radius * radius - distToLine * distToLine);
- var x1UV = lineCenter + l * lineDirection;
- var x2UV = lineCenter - l * lineDirection;
- var dir1 = math.normalize((origin + x1UV.x * circleU + x1UV.y * circleV) - vertex) * sign;
- var dir2 = math.normalize((origin + x2UV.x * circleU + x2UV.y * circleV) - vertex) * sign;
- l1 = dir1 * range;
- l2 = dir2 * range;
- }
+ // Silhouette generators satisfy dot(e, w.xy) = tan * w.z for unit e in the u/v plane, w = toCamera in the cone frame.
+ // Solved directly so it stays stable when the camera lies near the plane through the vertex.
+ var w = math.float3(math.dot(toCamera, circleU), math.dot(toCamera, circleV), math.dot(toCamera, axis));
+ var distToAxisSq = math.lengthsq(w.xy);
+ if (distToAxisSq == 0f)
+ {
+ return;
+ }
- static float3 EvaluateNearConic(float near, float3 o, float3 d, float r, float3 u, float3 v, float theta)
- {
- var h = (near - o.z) / (d.z + r * u.z * math.cos(theta) + r * v.z * math.sin(theta));
- return math.float3(o.xy + h * (d.xy + r * u.xy * math.cos(theta) + r * v.xy * math.sin(theta)), near);
+ var invDistToAxis = math.rsqrt(distToAxisSq);
+ var n = w.xy * invDistToAxis;
+ var c = math.clamp(circleRadius / coneHeight * w.z * invDistToAxis, -1f, 1f);
+ var s = math.sqrt(1f - c * c);
+ var e1 = c * n + s * math.float2(-n.y, n.x);
+ var e2 = c * n - s * math.float2(-n.y, n.x);
+ var sinHalfAngle = circleRadius / range;
+ l1 = (cosHalfAngle * axis + sinHalfAngle * (e1.x * circleU + e1.y * circleV)) * range;
+ l2 = (cosHalfAngle * axis + sinHalfAngle * (e2.x * circleU + e2.y * circleV)) * range;
}
- // o, d, u and v are expected to contain {x or y, z}. I.e. pass in x values to find tangents where x' = 0
- // Returns the two theta values as a float2.
- static float2 FindNearConicTangentTheta(float2 o, float2 d, float r, float2 u, float2 v)
+ ///
+ /// Section of a cone with the plane z = depth. With q = p - vertex = (x, y, z) and z = depth - vertex.z fixed, the cone
+ /// is dot(q, axis)^2 = cos^2 * dot(q, q), which is solved directly in the plane to stay stable when the vertex is close to it.
+ ///
+ internal struct ConeSection
{
- var sqrt = math.sqrt(square(d.x) * square(u.y) + square(d.x) * square(v.y) - 2f * d.x * d.y * u.x * u.y - 2f * d.x * d.y * v.x * v.y + square(d.y) * square(u.x) + square(d.y) * square(v.x) - square(r) * square(u.x) * square(v.y) + 2f * square(r) * u.x * u.y * v.x * v.y - square(r) * square(u.y) * square(v.x));
- var denom = d.x * v.y - d.y * v.x - r * u.x * v.y + r * u.y * v.x;
- return 2 * math.atan((-d.x * u.y + d.y * u.x + math.float2(1, -1) * sqrt) / denom);
+ float3 m_Vertex;
+ float3 m_Axis;
+ float m_Depth;
+ float m_Z;
+ float m_CosSq;
+ float m_SinSq;
+
+ public ConeSection(float depth, float3 vertex, float3 axis, float cosHalfAngle, float sinHalfAngle)
+ {
+ m_Vertex = vertex;
+ m_Axis = axis;
+ m_Depth = depth;
+ m_Z = depth - vertex.z;
+ m_CosSq = cosHalfAngle * cosHalfAngle;
+ m_SinSq = sinHalfAngle * sinHalfAngle;
+ }
+
+ ///
+ /// Returns the points with extreme y, NaN or infinite where there are none.
+ ///
+ public void GetYExtremes(out float3 p0, out float3 p1)
+ {
+ var d = m_Axis;
+ var y = SolveQuadratic(d.z * d.z - m_SinSq, -d.y * d.z * m_Z, m_Z * m_Z * (d.y * d.y - m_SinSq));
+ var x = -d.x * (d.y * y + d.z * m_Z) / (d.x * d.x - m_CosSq);
+ p0 = ToView(x.x, y.x);
+ p1 = ToView(x.y, y.y);
+ }
+
+ ///
+ /// Returns the points with extreme x, NaN or infinite where there are none.
+ ///
+ public void GetXExtremes(out float3 p0, out float3 p1)
+ {
+ var d = m_Axis;
+ var x = SolveQuadratic(d.z * d.z - m_SinSq, -d.x * d.z * m_Z, m_Z * m_Z * (d.x * d.x - m_SinSq));
+ var y = -d.y * (d.x * x + d.z * m_Z) / (d.y * d.y - m_CosSq);
+ p0 = ToView(x.x, y.x);
+ p1 = ToView(x.y, y.y);
+ }
+
+ ///
+ /// Returns the points at view-space height y, NaN or infinite where there are none.
+ ///
+ public void IntersectRow(float yVS, out float3 p0, out float3 p1)
+ {
+ var d = m_Axis;
+ var y = yVS - m_Vertex.y;
+ var k = d.y * y + d.z * m_Z;
+ var x = SolveQuadratic(d.x * d.x - m_CosSq, d.x * k, k * k - m_CosSq * (y * y + m_Z * m_Z));
+ p0 = ToView(x.x, y);
+ p1 = ToView(x.y, y);
+ }
+
+ float3 ToView(float x, float y) => math.float3(m_Vertex.xy + math.float2(x, y), m_Depth);
}
- static float2 FindNearConicYTheta(float near, float3 o, float3 d, float r, float3 u, float3 v, float y)
+ ///
+ /// Returns the roots of a * t^2 + 2 * b * t + c = 0: NaN if there are none, and one is infinite if a is 0.
+ ///
+ static float2 SolveQuadratic(float a, float b, float c)
{
- var sqrt = math.sqrt(-square(d.y) * square(o.z) + 2 * square(d.y) * o.z * near - square(d.y) * square(near) + 2 * d.y * d.z * o.y * o.z - 2 * d.y * d.z * o.y * near - 2 * d.y * d.z * o.z * y + 2 * d.y * d.z * y * near - square(d.z) * square(o.y) + 2 * square(d.z) * o.y * y - square(d.z) * square(y) + square(o.y) * square(r) * square(u.z) + square(o.y) * square(r) * square(v.z) - 2 * o.y * o.z * square(r) * u.y * u.z - 2 * o.y * o.z * square(r) * v.y * v.z - 2 * o.y * y * square(r) * square(u.z) - 2 * o.y * y * square(r) * square(v.z) + 2 * o.y * square(r) * u.y * u.z * near + 2 * o.y * square(r) * v.y * v.z * near + square(o.z) * square(r) * square(u.y) + square(o.z) * square(r) * square(v.y) + 2 * o.z * y * square(r) * u.y * u.z + 2 * o.z * y * square(r) * v.y * v.z - 2 * o.z * square(r) * square(u.y) * near - 2 * o.z * square(r) * square(v.y) * near + square(y) * square(r) * square(u.z) + square(y) * square(r) * square(v.z) - 2 * y * square(r) * u.y * u.z * near - 2 * y * square(r) * v.y * v.z * near + square(r) * square(u.y) * square(near) + square(r) * square(v.y) * square(near));
- var denom = d.y * o.z - d.y * near - d.z * o.y + d.z * y + o.y * r * u.z - o.z * r * u.y - y * r * u.z + r * u.y * near;
- return 2 * math.atan((r * (o.y * v.z - o.z * v.y - y * v.z + v.y * near) + math.float2(1, -1) * sqrt) / denom);
+ // Avoids the cancellation in -b + sqrt(b^2 - ac) by computing that root as c / q.
+ var q = -(b + (b < 0f ? -math.sqrt(b * b - a * c) : math.sqrt(b * b - a * c)));
+ return math.float2(q / a, c / q);
}
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ZBinningJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ZBinningJob.cs
index 1c4e6b7f95b..247292de32f 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ZBinningJob.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ZBinningJob.cs
@@ -81,6 +81,8 @@ void FillZBins(int binStart, int binEnd, int itemStart, int itemEnd, int headerI
for (var index = itemStart; index < itemEnd; index++)
{
var minMax = minMaxZs[itemOffset + index];
+ // Empty depth range, e.g. an item entirely closer than the near plane; skipping it also keeps log2 away from non-positive depths.
+ if (minMax.x > minMax.y) continue;
var minBin = math.max((int)((isOrthographic ? minMax.x : math.log2(minMax.x)) * zBinScale + zBinOffset), binStart);
var maxBin = math.min((int)((isOrthographic ? minMax.y : math.log2(minMax.y)) * zBinScale + zBinOffset), binEnd);
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs
index 9e18087294a..753b93d03ab 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs
@@ -49,6 +49,7 @@ internal class AutoUpscaler : AbstractUpscaler
public override string name => k_UpscalerName_Auto;
public override bool isTemporal => false;
public override bool supportsSharpening => false;
+ public override bool supportsAlphaUpscaling => true;
// RecordRenderGraph is an empty implementation from AbstractUpscaler
}
internal class BilinearUpscaler : AbstractUpscaler
@@ -56,18 +57,21 @@ internal class BilinearUpscaler : AbstractUpscaler
public override string name => k_UpscalerName_Linear;
public override bool isTemporal => false;
public override bool supportsSharpening => false;
+ public override bool supportsAlphaUpscaling => true;
}
internal class PointUpscaler : AbstractUpscaler
{
public override string name => k_UpscalerName_Point;
public override bool isTemporal => false;
public override bool supportsSharpening => false;
+ public override bool supportsAlphaUpscaling => true;
}
internal class FSR1Upscaler : AbstractUpscaler
{
public override string name => k_UpscalerName_FSR1;
public override bool isTemporal => false;
public override bool supportsSharpening => true;
+ public override bool supportsAlphaUpscaling => true;
// the FSR1 class is only for registration / unifying API for choosing an upscaler.
// The pass execution logic is still carried out by the internal Fsr1UpscalePostProcessPass.cs
}
@@ -257,13 +261,39 @@ internal static bool UseDynamicBranchFogKeyword()
private UniversalRenderPipelineGlobalSettings m_GlobalSettings;
- // Set by any camera that needs the real back buffer multisampled; one camera keeps it on for the
- // whole frame. Reset and consumed only in Render() so it can never be read stale.
- private bool m_FrameNeedsRealBackbufferMSAA;
+ struct DisplayMSAARequest
+ {
+ // Set by any camera that needs the surface multisampled; one camera keeps it on for the
+ // whole frame. Reset and consumed only in Render() so it can never be read stale.
+ bool m_NeededThisFrame;
+
+ // Hysteresis on dropping MSAA to 1: counts consecutive frames not needing MSAA so a per-frame
+ // flip-flop of the decision doesn't keep reallocating the surface.
+ int m_FramesSinceNeeded;
- // Hysteresis on dropping back buffer MSAA to 1: counts consecutive frames not needing back buffer
- // MSAA so a per-frame flip-flop of the decision doesn't keep reallocating the back buffer.
- private int m_FramesSinceRealBackbufferMSAANeeded;
+ public void BeginFrame() => m_NeededThisFrame = false;
+ public void Require() => m_NeededThisFrame = true;
+ public void ResetDowngradeDelay() => m_FramesSinceNeeded = 0;
+
+ // Returns the sample count to request. Upgrades apply immediately; downgrades wait out the
+ // hysteresis, since extra MSAA frames cost only bandwidth, never correctness.
+ public int Resolve(int assetSamples, int currentSamples)
+ {
+ if (m_NeededThisFrame)
+ {
+ m_FramesSinceNeeded = 0;
+ return assetSamples; // upgrade immediately
+ }
+ if (++m_FramesSinceNeeded >= realBackbufferMSAADowngradeDelayFrames)
+ return 1; // downgrade only after the delay
+ return currentSamples; // hold current during the delay
+ }
+ }
+
+ // The real backbuffer and XR eye textures each need their own: a camera with allowXRRendering disabled
+ // will render into the real back buffer in the same frame as the XR cameras render into the eye textures.
+ private DisplayMSAARequest m_RealBackbufferMSAARequest;
+ private DisplayMSAARequest m_XRDisplayMSAARequest;
// Must be > 1: when the renderer configuration changes for only a few frames (different render passes
// enqueued, e.g. by the volume system), this keeps us from setting back buffer MSAA to 1 and back
@@ -391,7 +421,7 @@ public UniversalRenderPipeline(UniversalRenderPipelineAsset asset)
// Apply the asset's MSAA to the back buffer at bind time so it doesn't lag asset changes by a
// frame; ApplyRealBackbufferMSAARequest still turns it off per-frame when no camera needs it.
RequestRealBackbufferMSAA(asset.msaaSampleCount);
- m_FramesSinceRealBackbufferMSAANeeded = 0;
+ m_RealBackbufferMSAARequest.ResetDowngradeDelay();
var defaultVolumeProfileSettings = GraphicsSettings.GetRenderPipelineSettings();
VolumeManager.instance.Initialize(defaultVolumeProfileSettings.volumeProfile, asset.volumeProfile);
@@ -399,6 +429,7 @@ public UniversalRenderPipeline(UniversalRenderPipelineAsset asset)
// Configure initial XR settings
MSAASamples msaaSamples = (MSAASamples)Mathf.Clamp(Mathf.NextPowerOfTwo(QualitySettings.antiAliasing), (int)MSAASamples.None, (int)MSAASamples.MSAA8x);
XRSystem.SetDisplayMSAASamples(msaaSamples);
+ m_XRDisplayMSAARequest.ResetDowngradeDelay();
XRSystem.SetRenderScale(asset.renderScale);
Lightmapping.SetDelegate(s_LightsDelegate);
@@ -595,9 +626,11 @@ protected override void Render(ScriptableRenderContext renderContext, List cameras)
@@ -623,7 +656,6 @@ void RenderCameras(ScriptableRenderContext renderContext, List cameras)
GraphicsSettings.lightsUseLinearIntensity = (QualitySettings.activeColorSpace == ColorSpace.Linear);
GraphicsSettings.lightsUseColorTemperature = true;
SetupPerFrameShaderConstants();
- XRSystem.SetDisplayMSAASamples((MSAASamples)asset.msaaSampleCount);
#if UNITY_ENABLE_CHECKS
if (DebugManager.instance.isAnyDebugUIActive)
@@ -693,32 +725,19 @@ void RenderCameras(ScriptableRenderContext renderContext, List cameras)
#endif
}
- // Renderers call this (via ScriptableRenderer.ReportRealBackbufferMSAA) to report that a camera needs
+ // Renderers call this (via ScriptableRenderer.ReportDisplayTargetMSAA) to report that a camera needs
// the real back buffer multisampled.
internal void RequireRealBackbufferMSAA()
{
- m_FrameNeedsRealBackbufferMSAA = true;
+ m_RealBackbufferMSAARequest.Require();
}
// Only sets the request for the next frame. The current frame already imported the live back buffer
// value (Screen.currentBackbufferMSAASamples) into RenderGraph, so rendering stays correct no matter
// when the surface is actually reallocated (deferred to the next frame on platforms like Metal).
- // Upgrades apply immediately; downgrades wait out the hysteresis, since extra MSAA frames cost only
- // bandwidth, never correctness.
private void ApplyRealBackbufferMSAARequest()
{
- int desired;
- if (m_FrameNeedsRealBackbufferMSAA)
- {
- m_FramesSinceRealBackbufferMSAANeeded = 0;
- desired = asset.msaaSampleCount; // upgrade immediately
- }
- else if (++m_FramesSinceRealBackbufferMSAANeeded >= realBackbufferMSAADowngradeDelayFrames)
- desired = 1; // downgrade only after the delay
- else
- desired = Screen.msaaSamples; // hold current during the delay
-
- RequestRealBackbufferMSAA(desired);
+ RequestRealBackbufferMSAA(m_RealBackbufferMSAARequest.Resolve(asset.msaaSampleCount, Screen.msaaSamples));
}
// Sets the real back buffer MSAA count, clamped to 1 where MSAA is resolved explicitly (the
@@ -732,6 +751,23 @@ private void RequestRealBackbufferMSAA(int samples)
Screen.SetMSAASamples(samples);
}
+ // XR counterpart of RequireRealBackbufferMSAA, for the XR eye textures.
+ internal void RequireXRDisplayMSAA()
+ {
+ m_XRDisplayMSAARequest.Require();
+ }
+
+ // XR counterpart of ApplyRealBackbufferMSAARequest. The eye textures are reallocated at the next XR
+ // frame start, and URP imports their live descriptor each frame, so rendering stays correct.
+ private void ApplyXRDisplayMSAARequest()
+ {
+ if (!XRSystem.displayActive)
+ return;
+
+ int samples = m_XRDisplayMSAARequest.Resolve(asset.msaaSampleCount, (int)XRSystem.GetDisplayMSAASamples());
+ XRSystem.SetDisplayMSAASamples((MSAASamples)samples);
+ }
+
///
/// Check whether RenderRequest is supported
///
@@ -797,6 +833,10 @@ protected override void ProcessRenderRequests(ScriptableRenderConte
RTDesc.width = Mathf.Max(1, RTDesc.width);
RTDesc.height = Mathf.Max(1, RTDesc.height);
+ RTDesc.depthStencilFormat = destination.depthStencilFormat;
+ if (RTDesc.depthStencilFormat == GraphicsFormat.None)
+ RTDesc.depthStencilFormat = CoreUtils.GetDefaultDepthStencilFormat();
+
//if mip is 0 and target is Texture2D we can immediately render to the requested destination
if(destination.dimension != TextureDimension.Tex2D || mipLevel != 0)
{
@@ -2001,6 +2041,11 @@ static void InitializeAdditionalCameraData(Camera camera, UniversalAdditionalCam
cameraData.requiresOpaqueTexture = false;
}
+ // Apply post-processing settings to the alpha output.
+ // cameraData.isAlphaOutputEnabled is set based on target alpha channel availability on create. Target can be a RenderTexture or the back-buffer.
+ bool allowAlphaOutput = !cameraData.postProcessEnabled || (cameraData.postProcessEnabled && settings.allowPostProcessAlphaOutput);
+ cameraData.isAlphaOutputEnabled = cameraData.isAlphaOutputEnabled && allowAlphaOutput;
+
// NOTE: TAA depends on XR modifications of cameraTargetDescriptor.
if (additionalCameraData != null)
UpdateTemporalAAData(cameraData, additionalCameraData);
@@ -2073,11 +2118,6 @@ static void InitializeAdditionalCameraData(Camera camera, UniversalAdditionalCam
cameraData.stackAnyPostProcessingEnabled = cameraData.postProcessEnabled;
cameraData.stackLastCameraOutputToHDR = cameraData.isHDROutputActive;
-
- // Apply post-processing settings to the alpha output.
- // cameraData.isAlphaOutputEnabled is set based on target alpha channel availability on create. Target can be a RenderTexture or the back-buffer.
- bool allowAlphaOutput = !cameraData.postProcessEnabled || (cameraData.postProcessEnabled && settings.allowPostProcessAlphaOutput);
- cameraData.isAlphaOutputEnabled = cameraData.isAlphaOutputEnabled && allowAlphaOutput;
}
static UniversalRenderingData CreateRenderingData(ContextContainer frameData, UniversalRenderPipelineAsset settings, CommandBuffer cmd, RenderingMode? renderingMode, ScriptableRenderer renderer)
@@ -2364,6 +2404,19 @@ private static void UpdateTemporalAAData(UniversalCameraData cameraData, Univers
cameraData.stpHistory = additionalCameraData.historyManager.GetHistoryForWrite();
}
+ bool needsAlphaUpscaleHistory = cameraData.isAlphaOutputEnabled;
+#if ENABLE_UPSCALER_FRAMEWORK
+ IUpscaler activeUpscaler = upscaling.activeUpscaler;
+ needsAlphaUpscaleHistory &= activeUpscaler != null && activeUpscaler.isTemporal && !activeUpscaler.supportsAlphaUpscaling;
+#else
+ needsAlphaUpscaleHistory &= cameraData.IsSTPEnabled();
+#endif
+ if (needsAlphaUpscaleHistory)
+ {
+ additionalCameraData.historyManager.RequestAccess();
+ cameraData.alphaUpscaleHistory = additionalCameraData.historyManager.GetHistoryForWrite();
+ }
+
// Update TAA settings
ref var taaSettings = ref additionalCameraData.taaSettings;
cameraData.taaSettings = taaSettings;
@@ -2408,6 +2461,17 @@ private static void UpdateTemporalAATargets(UniversalCameraData cameraData)
if (cameraData.IsSTPRequested())
cameraData.stpHistory?.Reset();
}
+
+ // The alpha history is common to all color-only temporal upscalers,
+ // so it is updated outside the per-upscaler branches above.
+ if (cameraData.alphaUpscaleHistory != null)
+ {
+ bool alphaXrMultipassEnabled = false;
+#if ENABLE_VR && ENABLE_XR_MODULE
+ alphaXrMultipassEnabled = cameraData.xr.enabled && !cameraData.xr.singlePassEnabled;
+#endif
+ cameraData.alphaUpscaleHistory.Update(cameraData, alphaXrMultipassEnabled);
+ }
}
static void UpdateCameraStereoMatrices(Camera camera, XRPass xr)
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs
index 3b0c39ddf3a..226d14a4cde 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipelineCore.cs
@@ -1513,12 +1513,14 @@ internal static void CreateBackbufferInfo(Camera camera, UniversalCameraData cam
if (camera.targetTexture == null)
{
+ Vector2Int backbufferSize = RenderingUtils.GetScreenBackbufferSize(camera);
+
// Describe the real backbuffer's live MSAA. UpdateCameraData later overrides this
// with the XR eye texture properties when an XR pass is actually active.
cameraData.backbufferColor = new RenderTargetInfo
{
- width = Screen.width,
- height = Screen.height,
+ width = backbufferSize.x,
+ height = backbufferSize.y,
volumeDepth = 1,
msaaSamples = Screen.currentBackbufferMSAASamples,
format = colorFormatProxy,
@@ -1545,6 +1547,7 @@ internal static void CreateBackbufferInfo(Camera camera, UniversalCameraData cam
}
}
}
+
internal static int GetIntermediateTexturesMSAA(UniversalCameraData cameraData, ScriptableRenderer renderer)
{
bool rendererSupportsMSAA = renderer != null && renderer.supportedRenderingFeatures.msaa;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderer.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderer.cs
index fa0e45761e6..2c771aa7c65 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderer.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderer.cs
@@ -876,7 +876,7 @@ static bool RequiresIntermediateColorTexture(UniversalCameraData cameraData, in
bool requiresBlitForOffscreenCamera = applyPostProcessing || renderPassInputs.requiresColorTexture || requiresExplicitMsaaResolve || !cameraData.isDefaultViewport || requestedColorHistory;
if (isOffscreenRender)
- return requiresBlitForOffscreenCamera;
+ return requiresBlitForOffscreenCamera || isScaledRender;
return requiresBlitForOffscreenCamera || isScaledRender || isScalableBufferManagerUsed || cameraData.isHdrEnabled ||
!isCompatibleBackbufferTextureDimension || isCapturing || cameraData.requireSrgbConversion;
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs
index b024b3e2496..bd7f9fd69cc 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs
@@ -671,7 +671,7 @@ internal override void OnRecordRenderGraph(RenderGraph renderGraph, ScriptableRe
s_RequiresIntermediateAttachments = RequiresIntermediateAttachments(cameraData, in renderPassInputs, requireCopyFromDepth, applyPostProcessing, m_DrawOverlayUIPass.RequiresComposition());
// Report this camera's real back buffer MSAA need to the pipeline.
- ReportRealBackbufferMSAA(cameraData, s_RequiresIntermediateAttachments);
+ ReportDisplayTargetMSAA(cameraData, s_RequiresIntermediateAttachments);
CreateRenderGraphCameraRenderTargets(renderGraph, isCameraTargetOffscreenDepth, s_RequiresIntermediateAttachments, depthTextureIsDepthFormat);
@@ -1903,7 +1903,7 @@ void CreateOffscreenUITexture(RenderGraph renderGraph, TextureDesc descriptor)
{
UniversalResourceData resourceData = frameData.Get();
UniversalCameraData cameraData = frameData.Get();
- DrawScreenSpaceUIPass.ConfigureOffscreenUITextureDesc(ref descriptor);
+ DrawScreenSpaceUIPass.ConfigureOffscreenUITextureDesc(ref descriptor, cameraData);
RenderingUtils.ReAllocateHandleIfNeeded(ref s_OffscreenUIColorHandle, descriptor, name: "_OverlayUITexture");
// Clear the texture to avoid stale data from previous frames
diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Billboard.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Billboard.shader
index 7a6677a309a..28f04d69a26 100644
--- a/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Billboard.shader
+++ b/Packages/com.unity.render-pipelines.universal/Shaders/Nature/SpeedTree7Billboard.shader
@@ -108,6 +108,7 @@ Shader "Universal Render Pipeline/Nature/SpeedTree7 Billboard"
#pragma multi_compile __ LOD_FADE_CROSSFADE
#pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT
#pragma multi_compile_fragment _ _RENDER_PASS_ENABLED
+ #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/RenderingLayers.hlsl"
#pragma shader_feature_local EFFECT_BUMP
#pragma shader_feature_local EFFECT_HUE_VARIATION
diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLit.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLit.shader
index 9ecf67a72e4..5c81240b3d8 100644
--- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLit.shader
+++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainDetailLit.shader
@@ -81,10 +81,12 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/Vertexlit"
#include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ProbeVolumeVariants.hlsl"
#pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT
#pragma multi_compile_fragment _ _RENDER_PASS_ENABLED
+ #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/RenderingLayers.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/GBufferOutput.hlsl"
+ #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/GBufferOutputFormat.hlsl"
TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex);
float4 _MainTex_ST;
diff --git a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassBillboard.shader b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassBillboard.shader
index f65389b2166..a4adc2b6516 100644
--- a/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassBillboard.shader
+++ b/Packages/com.unity.render-pipelines.universal/Shaders/Terrain/WavingGrassBillboard.shader
@@ -91,6 +91,7 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/BillboardWavingDoublePass
#pragma multi_compile_fragment _ _GBUFFER_NORMALS_OCT
#pragma multi_compile_fragment _ _SCREEN_SPACE_IRRADIANCE
#include_with_pragmas "Packages/com.unity.render-pipelines.core/ShaderLibrary/FoveatedRenderingKeywords.hlsl"
+ #include_with_pragmas "Packages/com.unity.render-pipelines.universal/ShaderLibrary/RenderingLayers.hlsl"
// -------------------------------------
// Unity defined keywords
@@ -100,6 +101,7 @@ Shader "Hidden/TerrainEngine/Details/UniversalPipeline/BillboardWavingDoublePass
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
+ #pragma instancing_options renderinglayer
#pragma vertex WavingGrassBillboardVert
#pragma fragment LitPassFragmentGrass
diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs
new file mode 100644
index 00000000000..de217bba2a2
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs
@@ -0,0 +1,65 @@
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using UnityEngine;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.Universal;
+
+namespace UnityEditor.Rendering.Universal.Tests
+{
+ // With Rendering Layers enabled, deferred lighting only lights a pixel whose GBuffer rendering layers mask
+ // contains the light's layers. A GBuffer pass without the _WRITE_RENDERING_LAYERS variant leaves that mask
+ // unwritten, so what it draws takes whatever was there before, usually nothing, and goes unlit.
+ class GBufferRenderingLayersTests
+ {
+ const string k_ShaderFolder = "Packages/com.unity.render-pipelines.universal/Shaders";
+
+ [Test]
+ public void GBufferPassesDeclareWriteRenderingLayers()
+ {
+ var lightMode = new ShaderTagId("LightMode");
+ var renderPipeline = new ShaderTagId("RenderPipeline");
+ var checkedShaders = new HashSet();
+ var missing = new List();
+
+ foreach (var guid in AssetDatabase.FindAssets("t:Shader", new[] { k_ShaderFolder }))
+ {
+ var path = AssetDatabase.GUIDToAssetPath(guid);
+ var shader = AssetDatabase.LoadAssetAtPath(path);
+ Assert.IsNotNull(shader, $"Failed to load shader at path '{path}'");
+
+ var data = ShaderUtil.GetShaderData(shader);
+ // Serialized subshaders only: the runtime list also holds the Fallback shader's subshaders.
+ for (int s = 0; s < data.SerializedSubshaderCount; ++s)
+ {
+ var subshader = data.GetSerializedSubshader(s);
+ // Shader Graph assets can carry subshaders for other pipelines, such as HDRP, which URP never selects.
+ // Untagged subshaders stay in: URP can select them.
+ var pipelineTag = subshader.FindTagValue(renderPipeline).name;
+ if (!string.IsNullOrEmpty(pipelineTag) && pipelineTag != "UniversalPipeline")
+ continue;
+
+ for (int p = 0; p < subshader.PassCount; ++p)
+ {
+ var pass = subshader.GetPass(p);
+ if (pass.FindTagValue(lightMode).name != "UniversalGBuffer")
+ continue;
+
+ checkedShaders.Add(path);
+ var keywords = ShaderUtil.GetPassKeywords(shader, new PassIdentifier((uint)s, (uint)p), ShaderType.Fragment);
+ if (!keywords.Any(k => k.name == ShaderKeywordStrings.WriteRenderingLayers))
+ missing.Add($"{path} (subshader {s}, pass '{pass.Name}')");
+ }
+ }
+ }
+
+ Assert.That(checkedShaders, Does.Contain($"{k_ShaderFolder}/Lit.shader"),
+ "Found no GBuffer pass in Lit.shader; did the shader folder or the LightMode tag change?");
+ Assert.That(missing, Is.Empty,
+ $"These GBuffer passes do not declare {ShaderKeywordStrings.WriteRenderingLayers}, so with Rendering Layers on in "
+ + "Deferred they leave the rendering layers target unwritten and deferred lighting skips them. Add "
+ + "#include_with_pragmas \"Packages/com.unity.render-pipelines.universal/ShaderLibrary/RenderingLayers.hlsl\" "
+ + "to the pass:\n" + string.Join("\n", missing));
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs.meta
new file mode 100644
index 00000000000..0b8651424d9
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/GBufferRenderingLayersTests.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 5d2ed4d1fc144e858d6c2ea194f8fe4e
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RealBackbufferMSAATests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RealBackbufferMSAATests.cs
index ae014dc6670..1834215372d 100644
--- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RealBackbufferMSAATests.cs
+++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RealBackbufferMSAATests.cs
@@ -74,9 +74,9 @@ public void OneTimeSetUp()
if (UniversalRenderer.PlatformRequiresExplicitMsaaResolve())
IgnoreWithLog("Platform resolves MSAA explicitly (no multisampled back buffer); the real back buffer MSAA request is always 1, so there is nothing to test here.");
- // Under XR, URP renders into the XR-owned back buffer and never multisamples it directly, so the
- // optimization is inactive. A global gate (rather than URP's per-camera xr.enabled check) is enough
- // to skip the device XR and mock-XR jobs, where the fixture is meaningless.
+ // Under XR, the cameras here render into the XR eye textures, not the real back buffer, so this
+ // fixture's checks don't apply (XRDisplayMSAATests covers the eye textures). A global gate (rather
+ // than URP's per-camera xr.enabled check) is enough to skip the device XR and mock-XR jobs.
if (XRSystem.displayActive || XRGraphicsAutomatedTests.enabled)
IgnoreWithLog("XR is active; URP renders into the XR-owned back buffer and never multisamples it directly, so there is nothing to test here.");
diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs
index be45a68bba9..cb48c0c2095 100644
--- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs
+++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs
@@ -14,6 +14,9 @@ class RuntimeTests
Camera camera;
RenderPipelineAsset currentAssetGraphics;
RenderPipelineAsset currentAssetQuality;
+ RenderTexture m_Destination;
+ UniversalRenderPipelineAsset m_TestAsset;
+ UniversalRendererData m_TestRendererData;
[SetUp]
public void Setup()
@@ -30,6 +33,22 @@ public void Cleanup()
GraphicsSettings.defaultRenderPipeline = currentAssetGraphics;
QualitySettings.renderPipeline = currentAssetQuality;
Object.DestroyImmediate(go);
+ if (m_Destination != null)
+ {
+ m_Destination.Release();
+ Object.DestroyImmediate(m_Destination);
+ m_Destination = null;
+ }
+ if (m_TestAsset != null)
+ {
+ Object.DestroyImmediate(m_TestAsset);
+ m_TestAsset = null;
+ }
+ if (m_TestRendererData != null)
+ {
+ Object.DestroyImmediate(m_TestRendererData);
+ m_TestRendererData = null;
+ }
}
static readonly (int tier, string textTier)[] k_ShadowResolutions =
@@ -118,6 +137,99 @@ public IEnumerator PipelineHasCorrectColorSpace()
"GraphicsSettings.lightsUseLinearIntensity must match active color space.");
}
+ [UnityTest]
+ public IEnumerator RenderRequest_WithCubemapDestination_RendersIntoRequestedFace(
+ [Values] bool useSingleCameraRequest,
+ [Values] bool destinationHasDepth)
+ {
+ AssetCheck();
+
+ if ((SystemInfo.copyTextureSupport & CopyTextureSupport.DifferentTypes) == 0)
+ Assert.Ignore("Render requests into a cubemap require CopyTextureSupport.DifferentTypes.");
+
+ // The active quality level can use a debug renderer that overwrites the camera color
+ m_TestRendererData = ScriptableObject.CreateInstance();
+ m_TestRendererData.renderingMode = RenderingMode.Forward;
+ m_TestAsset = ScriptableObject.CreateInstance();
+ m_TestAsset.m_RendererDataList[0] = m_TestRendererData;
+ QualitySettings.renderPipeline = m_TestAsset;
+ yield return null;
+ Assert.AreSame(m_TestAsset, GraphicsSettings.currentRenderPipeline, "The test URP asset is not active.");
+
+ camera.clearFlags = CameraClearFlags.SolidColor;
+ camera.backgroundColor = Color.red;
+ camera.cullingMask = 0;
+
+ var depthStencilFormat = destinationHasDepth
+ ? CoreUtils.GetDefaultDepthStencilFormat()
+ : UnityEngine.Experimental.Rendering.GraphicsFormat.None;
+ m_Destination = new RenderTexture(64, 64, UnityEngine.Experimental.Rendering.GraphicsFormat.R8G8B8A8_UNorm,
+ depthStencilFormat)
+ {
+ dimension = TextureDimension.Cube
+ };
+ m_Destination.Create();
+
+ if (useSingleCameraRequest)
+ {
+ RenderPipeline.SubmitRenderRequest(camera, new UniversalRenderPipeline.SingleCameraRequest
+ {
+ destination = m_Destination,
+ face = CubemapFace.PositiveX
+ });
+ }
+ else
+ {
+ RenderPipeline.SubmitRenderRequest(camera, new RenderPipeline.StandardRequest
+ {
+ destination = m_Destination,
+ face = CubemapFace.PositiveX
+ });
+ }
+ yield return null;
+
+ var faceCopy = new RenderTexture(m_Destination.width, m_Destination.height, 0, m_Destination.graphicsFormat);
+ Texture2D readback = null;
+ var previousActive = RenderTexture.active;
+ try
+ {
+ Graphics.CopyTexture(m_Destination, (int)CubemapFace.PositiveX, 0, faceCopy, 0, 0);
+
+ int centerX = faceCopy.width / 2;
+ int centerY = faceCopy.height / 2;
+ Color pixel;
+
+ // ReadPixels does not work on WebGPU when the browser lacks JSPI
+ if (SystemInfo.supportsAsyncGPUReadback)
+ {
+ var request = AsyncGPUReadback.Request(faceCopy, 0, TextureFormat.RGBA32);
+ while (!request.done)
+ yield return null;
+
+ Assert.IsFalse(request.hasError, "AsyncGPUReadback of the requested cubemap face failed.");
+ pixel = request.GetData()[centerY * faceCopy.width + centerX];
+ }
+ else
+ {
+ readback = new Texture2D(faceCopy.width, faceCopy.height, TextureFormat.RGBA32, false);
+ RenderTexture.active = faceCopy;
+ readback.ReadPixels(new Rect(0, 0, faceCopy.width, faceCopy.height), 0, 0);
+ readback.Apply();
+ pixel = readback.GetPixel(centerX, centerY);
+ }
+
+ Assert.Greater(pixel.r, 0.9f, $"The requested cubemap face does not contain the camera rendering. Pixel: {pixel}");
+ }
+ finally
+ {
+ RenderTexture.active = previousActive;
+ faceCopy.Release();
+ Object.DestroyImmediate(faceCopy);
+ if (readback != null)
+ Object.DestroyImmediate(readback);
+ }
+ }
+
// When switching to URP it sets "UniversalPipeline" as global shader tag.
// When switching to Built-in it sets "" as global shader tag.
#if UNITY_EDITOR // TODO This API call does not reset in player
diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs
new file mode 100644
index 00000000000..712f303a7ef
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs
@@ -0,0 +1,206 @@
+using System.Collections;
+using System.Collections.Generic;
+using NUnit.Framework;
+using UnityEngine.Experimental.Rendering;
+using UnityEngine.Rendering.RenderGraphModule;
+using UnityEngine.TestTools;
+
+namespace UnityEngine.Rendering.Universal.Tests
+{
+ // XR counterpart of RealBackbufferMSAATests: URP keeps the XR eye textures single-sampled while no XR camera
+ // renders MSAA directly into them (e.g. the camera goes through post-processing).
+ [TestFixture]
+ class XRDisplayMSAATests
+ {
+ const int k_AssetMsaaSampleCount = 4;
+ // Downgrade hysteresis + one-frame apply lag (eye textures are reallocated at the next XR frame start) + margin.
+ const int k_SettleFrames = UniversalRenderPipeline.realBackbufferMSAADowngradeDelayFrames + 1 + 3;
+ // Upgrades skip the hysteresis: 1 frame to request + 1 frame for the reallocation + 1 frame of margin.
+ const int k_UpgradeFrames = 3;
+
+ RenderPipelineAsset m_PreviousQualityRenderPipelineAsset;
+ UniversalRenderPipelineAsset m_Asset;
+ UniversalRendererData m_RendererData;
+ Camera m_Camera;
+ bool m_Intermediate;
+
+ readonly List m_DisabledCameras = new();
+ readonly ForceIntermediatePass m_ForceIntermediatePass = new();
+ ProbePass m_ProbePass;
+
+ [OneTimeSetUp]
+ public void OneTimeSetUp()
+ {
+ // Captured before any early-out: NUnit runs OneTimeTearDown even when OneTimeSetUp ignores.
+ m_PreviousQualityRenderPipelineAsset = QualitySettings.renderPipeline;
+
+ if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset)
+ Assert.Ignore("These tests only run when URP is the active render pipeline.");
+ if (UniversalRenderer.PlatformRequiresExplicitMsaaResolve())
+ Assert.Ignore("Platform resolves MSAA explicitly (no multisampled eye texture); the display target MSAA request is always 1, so there is nothing to test here.");
+ if (!XRSystem.displayActive)
+ Assert.Ignore("No active XR display.");
+
+ foreach (var cam in Object.FindObjectsByType(FindObjectsInactive.Exclude))
+ {
+ if (!cam.enabled)
+ continue;
+ cam.enabled = false;
+ m_DisabledCameras.Add(cam);
+ }
+
+ m_RendererData = ScriptableObject.CreateInstance();
+ m_RendererData.renderingMode = RenderingMode.Forward;
+ m_Asset = ScriptableObject.CreateInstance();
+ m_Asset.m_RendererDataList[0] = m_RendererData;
+ // Pin every setting that feeds RequiresIntermediateColorTexture, so only the force-intermediate pass
+ // decides whether the camera renders directly.
+ m_Asset.supportsHDR = false;
+ m_Asset.supportsCameraOpaqueTexture = false;
+ m_Asset.supportsCameraDepthTexture = false;
+ m_Asset.renderScale = 1.0f;
+ QualitySettings.renderPipeline = m_Asset;
+
+ RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
+ }
+
+ [OneTimeTearDown]
+ public void OneTimeTearDown()
+ {
+ RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
+ // Restoring the pipeline recreates it, which resets the XR display MSAA to the quality setting.
+ QualitySettings.renderPipeline = m_PreviousQualityRenderPipelineAsset;
+
+ foreach (var cam in m_DisabledCameras)
+ {
+ if (cam != null)
+ cam.enabled = true;
+ }
+ m_DisabledCameras.Clear();
+
+ if (m_RendererData != null)
+ Object.DestroyImmediate(m_RendererData);
+ if (m_Asset != null)
+ Object.DestroyImmediate(m_Asset);
+ }
+
+ [SetUp]
+ public void SetUp()
+ {
+ m_Asset.msaaSampleCount = k_AssetMsaaSampleCount;
+ m_Intermediate = false;
+ m_ProbePass = new ProbePass();
+
+ var go = new GameObject("MSAA Test XR Camera");
+ m_Camera = go.AddComponent();
+ m_Camera.allowMSAA = true;
+ m_Camera.allowHDR = false;
+ m_Camera.allowDynamicResolution = false;
+ var data = go.AddComponent();
+ data.SetRenderer(0);
+ data.renderPostProcessing = false;
+ }
+
+ [TearDown]
+ public void TearDown()
+ {
+ if (m_Camera != null)
+ Object.DestroyImmediate(m_Camera.gameObject);
+ }
+
+ void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
+ {
+ if (camera != m_Camera)
+ return;
+
+ var renderer = camera.GetComponent().scriptableRenderer;
+ if (m_Intermediate)
+ renderer.EnqueuePass(m_ForceIntermediatePass);
+ renderer.EnqueuePass(m_ProbePass);
+ }
+
+ [UnityTest]
+ public IEnumerator IntermediateToggles_DisplayFollows()
+ {
+ // Like toggling post-processing: the final pass becomes a full-screen blit, so the eye textures don't
+ // need MSAA, and get it back when the camera renders directly again.
+ yield return TickFrames(k_SettleFrames);
+ AssertDisplayMSAA(k_AssetMsaaSampleCount, checkEyeTexture: false);
+ // Where the provider doesn't multisample its eye textures, only the request can be checked.
+ bool eyeTextureMsaaSupported = m_ProbePass.backbufferMsaaSamples == k_AssetMsaaSampleCount;
+
+ m_Intermediate = true;
+ yield return TickFrames(k_SettleFrames);
+ AssertDisplayMSAA(1, eyeTextureMsaaSupported);
+
+ m_Intermediate = false;
+ yield return TickFrames(k_UpgradeFrames);
+ AssertDisplayMSAA(k_AssetMsaaSampleCount, eyeTextureMsaaSupported);
+ }
+
+ [UnityTest]
+ public IEnumerator AssetMSAAChangedAtRuntime_DisplayFollows()
+ {
+ // A runtime asset change must reach the eye textures without recreating the pipeline.
+ const int k_ChangedSampleCount = 2;
+ yield return TickFrames(k_SettleFrames);
+ AssertDisplayMSAA(k_AssetMsaaSampleCount, checkEyeTexture: false);
+ bool eyeTextureMsaaSupported = m_ProbePass.backbufferMsaaSamples == k_AssetMsaaSampleCount;
+
+ m_Asset.msaaSampleCount = k_ChangedSampleCount;
+ yield return TickFrames(k_UpgradeFrames);
+ AssertDisplayMSAA(k_ChangedSampleCount, eyeTextureMsaaSupported);
+ }
+
+ void AssertDisplayMSAA(int expectedSamples, bool checkEyeTexture)
+ {
+ Assert.IsTrue(m_ProbePass.xrEnabled, "The test camera did not render as an XR camera.");
+ Assert.AreEqual(!m_Intermediate, m_ProbePass.activeTargetIsBackbuffer,
+ $"The test camera should render {(m_Intermediate ? "through an intermediate" : "directly to the eye textures")}.");
+ Assert.AreEqual(expectedSamples, (int)XRSystem.GetDisplayMSAASamples(), "Unexpected XR display MSAA request.");
+ if (checkEyeTexture)
+ Assert.AreEqual(expectedSamples, m_ProbePass.backbufferMsaaSamples, "The eye texture URP rendered to has an unexpected MSAA sample count.");
+ }
+
+ static IEnumerator TickFrames(int count)
+ {
+ for (int i = 0; i < count; i++)
+ yield return null;
+ }
+
+ class ForceIntermediatePass : ScriptableRenderPass
+ {
+ public ForceIntermediatePass()
+ {
+ requiresIntermediateTexture = true;
+ }
+
+ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
+ {
+ }
+ }
+
+ // Records the last render of the test camera: whether it rendered as XR, whether directly to the eye
+ // textures, and the MSAA sample count of the eye texture URP imported as the back buffer.
+ class ProbePass : ScriptableRenderPass
+ {
+ public bool xrEnabled;
+ public bool activeTargetIsBackbuffer;
+ public int backbufferMsaaSamples;
+
+ public ProbePass()
+ {
+ renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
+ }
+
+ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
+ {
+ var cameraData = frameData.Get();
+ var resourceData = frameData.Get();
+ xrEnabled = cameraData.xr.enabled;
+ activeTargetIsBackbuffer = resourceData.isActiveTargetBackBuffer;
+ backbufferMsaaSamples = renderGraph.GetRenderTargetInfo(resourceData.backBufferColor).msaaSamples;
+ }
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs.meta
new file mode 100644
index 00000000000..3ab46d7c300
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/XRDisplayMSAATests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 347f234cc981746e3bbd178e4d4dbc66
\ No newline at end of file
diff --git a/Packages/com.unity.visualeffectgraph/Editor/GraphView/Elements/Controllers/VFXParameterController.cs b/Packages/com.unity.visualeffectgraph/Editor/GraphView/Elements/Controllers/VFXParameterController.cs
index 2cc1f67ee66..e721e16de5a 100644
--- a/Packages/com.unity.visualeffectgraph/Editor/GraphView/Elements/Controllers/VFXParameterController.cs
+++ b/Packages/com.unity.visualeffectgraph/Editor/GraphView/Elements/Controllers/VFXParameterController.cs
@@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Numerics;
using System.Reflection;
using System.Collections.ObjectModel;
+using System.Globalization;
using UnityEngine;
using UnityEngine.Profiling;
@@ -555,6 +557,26 @@ public void SetMemberValue(string memberPath, object value)
}
}
+ ///
+ /// Builds the name given to a new parameter of a type, such as "New Vector 3".
+ ///
+ /// The type of the parameter.
+ /// The default exposed name for .
+ public static string GetDefaultExposedName(Type type)
+ {
+ return $"New {ObjectNames.NicifyVariableName(type.UserFriendlyName())}";
+ }
+
+ ///
+ /// Makes a parameter name unique among the parameters of the graph.
+ ///
+ /// The controller of the graph whose parameter names are taken.
+ /// The wanted name.
+ /// The maximum length of the result, or 0 for no limit.
+ ///
+ /// The unique name. See for the
+ /// counter format.
+ ///
public static string MakeNameUnique(VFXViewController viewController, string candidateName, int maxLength = 0)
{
var allNames = new HashSet(viewController.parameterControllers.Select(t => t.exposedName), StringComparer.OrdinalIgnoreCase);
@@ -562,73 +584,144 @@ public static string MakeNameUnique(VFXViewController viewController, string can
return MakeNameUnique(candidateName, allNames, true, maxLength, null);
}
+ ///
+ /// Makes a name unique among by adding or incrementing a counter at its end.
+ ///
+ ///
+ /// When is true, the counter is written " (N)": "Speed" becomes "Speed (1)" and
+ /// "Speed (1)" becomes "Speed (2)".
+ /// Other trailing digits are part of the name, so "New Vector 3" becomes "New Vector 3 (1)".
+ /// When is false, the name must stay an identifier and the counter is written
+ /// "_N".
+ ///
+ ///
+ /// The wanted name. When is true, leading and trailing whitespace is removed.
+ /// Identifiers keep their leading and trailing underscores.
+ ///
+ /// The names already taken. Callers pass a set that ignores case.
+ ///
+ /// True for names that can contain spaces, such as parameter and category names. False for identifiers.
+ ///
+ ///
+ /// The maximum length of the result, or 0 for no limit. A longer name is cut and always gets a counter, and the
+ /// name is cut so that it fits with its counter. When a counter is too long for any of the name to fit with it,
+ /// the number at the end is kept as part of the name and counting starts again at 1.
+ ///
+ ///
+ /// When set, receives each name with a counter that was tried, including the returned one.
+ ///
+ ///
+ /// The unique name, or null when only contains whitespace, or only underscores for an
+ /// identifier.
+ ///
public static string MakeNameUnique(string name, HashSet allNames, bool allowSpace = true, int maxLength = 0, List rejectedCandidateNames = null)
{
if (string.IsNullOrEmpty(name))
{
name = "parameter";
}
- string candidateName = name.Trim(allowSpace ? ' ' : '_');
- if (candidateName.Length < 1)
+ string candidateName = allowSpace ? name.Trim() : name;
+ if ((allowSpace ? candidateName : candidateName.Trim('_')).Length == 0)
{
return null;
}
- bool forceSuffix = false;
- if (maxLength > 0 && candidateName.Length > maxLength)
- {
+
+ bool isCut = maxLength > 0 && candidateName.Length > maxLength;
+ if (isCut)
candidateName = candidateName.Substring(0, maxLength);
- forceSuffix = true;
- }
- string candidateMainPart = null;
- int cpt = 0;
- while (forceSuffix || allNames.Contains(candidateName))
+ else if (!allNames.Contains(candidateName))
+ return candidateName;
+
+ string wholeName = candidateName;
+ (string mainPart, BigInteger counter) = SplitCounter(wholeName, allowSpace);
+ do
{
- forceSuffix = false;
- if (candidateMainPart == null)
+ ++counter;
+ candidateName = AppendCounter(mainPart, counter, allowSpace, maxLength);
+ if (candidateName == null)
{
- int spaceIndex = candidateName.LastIndexOf(allowSpace ? ' ' : '_');
- if (spaceIndex == -1)
- {
- candidateMainPart = candidateName;
- }
- else
- {
- if (int.TryParse(candidateName.Substring(spaceIndex + 1), out cpt)) // spaceIndex can't be last char because of Trim()
- {
- candidateMainPart = candidateName.Substring(0, spaceIndex);
- }
- else
- {
- candidateMainPart = candidateName;
- }
- }
+ mainPart = wholeName;
+ counter = BigInteger.One;
+ candidateName = AppendCounter(mainPart, counter, allowSpace, maxLength);
}
- ++cpt;
+ rejectedCandidateNames?.Add(candidateName);
+ }
+ while (allNames.Contains(candidateName));
- // Do not exceed the character count limit when appending a suffix
- var suffix = allowSpace ? $" {cpt}" : $"_{cpt}";
- if (maxLength > 0)
+ return candidateName;
+ }
+
+ ///
+ /// Writes the counter read by at the end of a name.
+ ///
+ /// The name without a counter.
+ /// The counter to write.
+ /// True to write a " (N)" counter, false to write a "_N" counter.
+ ///
+ /// The maximum length of the result, or 0 for no limit. is cut so that it fits with
+ /// the counter. When is true, whitespace left at the end of the cut is removed.
+ ///
+ ///
+ /// The name with its counter, or null when the counter leaves no room for any of .
+ ///
+ static string AppendCounter(string mainPart, BigInteger counter, bool allowSpace, int maxLength)
+ {
+ string digits = counter.ToString(CultureInfo.InvariantCulture);
+ string suffix = allowSpace ? $" ({digits})" : $"_{digits}";
+ if (maxLength > 0)
+ {
+ int mainLength = maxLength - suffix.Length;
+ if (mainLength < Math.Min(1, mainPart.Length))
{
- var maxMainPartLength = Math.Max(0, (int)maxLength - suffix.Length);
- candidateName = $"{candidateMainPart.Substring(0, Math.Min(candidateMainPart.Length, maxMainPartLength))}{suffix}";
+ return null;
}
- else
+
+ if (mainPart.Length > mainLength)
{
- candidateName = $"{candidateMainPart}{suffix}";
+ mainPart = mainPart.Substring(0, mainLength);
+ if (allowSpace)
+ {
+ mainPart = mainPart.TrimEnd();
+ }
}
- rejectedCandidateNames?.Add(candidateName);
}
- return candidateName;
+ return mainPart + suffix;
}
- public void CheckNameUnique(HashSet allNames)
+ ///
+ /// Splits the counter written by
+ /// from the end of a name.
+ ///
+ ///
+ /// The name, without leading or trailing whitespace when is true.
+ ///
+ /// True to read a " (N)" counter, false to read a "_N" counter.
+ ///
+ /// The name without its counter, and the counter, or 0 when has none.
+ ///
+ static (string mainPart, BigInteger counter) SplitCounter(string name, bool allowSpace)
{
- string candidateName = MakeNameUnique(base.model.exposedName, allNames, false, kMaxExposedNameLength);
- if (candidateName != base.model.exposedName)
+ if (allowSpace)
+ {
+ int openIndex = name.LastIndexOf(" (", StringComparison.Ordinal);
+ if (openIndex != -1 && name[name.Length - 1] == ')')
+ {
+ int digitsIndex = openIndex + 2;
+ string digits = name.Substring(digitsIndex, name.Length - 1 - digitsIndex);
+
+ if (BigInteger.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out BigInteger counter))
+ return (name.Substring(0, openIndex), counter);
+ }
+ }
+ else
{
- model.SetSettingValue("m_ExposedName", candidateName);
+ int separatorIndex = name.LastIndexOf('_');
+ if (separatorIndex != -1 && BigInteger.TryParse(name.Substring(separatorIndex + 1), NumberStyles.None, CultureInfo.InvariantCulture, out BigInteger counter))
+ return (name.Substring(0, separatorIndex), counter);
}
+
+ return (name, BigInteger.Zero);
}
public string exposedName
diff --git a/Packages/com.unity.visualeffectgraph/Editor/GraphView/Views/Controller/VFXViewController.cs b/Packages/com.unity.visualeffectgraph/Editor/GraphView/Views/Controller/VFXViewController.cs
index 662c7fefbf2..362d7cee43d 100644
--- a/Packages/com.unity.visualeffectgraph/Editor/GraphView/Views/Controller/VFXViewController.cs
+++ b/Packages/com.unity.visualeffectgraph/Editor/GraphView/Views/Controller/VFXViewController.cs
@@ -1245,7 +1245,7 @@ public VFXParameter AddVFXParameter(Vector2 pos, Variant variant, bool parent =
order = m_ParameterControllers.Keys.Select(t => t.order).Max() + 1;
}
parameter.order = order;
- var candidateName = $"New {ObjectNames.NicifyVariableName(type.UserFriendlyName())}";
+ string candidateName = VFXParameterController.GetDefaultExposedName(type);
parameter.SetSettingValue("m_ExposedName", VFXParameterController.MakeNameUnique(this, candidateName, VFXParameterController.kMaxExposedNameLength));
if (!type.IsPrimitive)
@@ -1296,7 +1296,7 @@ public VFXNodeController AddNode(Vector2 tPos, Variant variant, VFXGroupNodeCont
if (newNode is VFXParameter newParameter)
{
// Set an exposed name on a new parameter so that uniqueness is ensured
- m_ParameterControllers[newParameter].exposedName = $"New {ObjectNames.NicifyVariableName(newParameter.type.UserFriendlyName())}";
+ m_ParameterControllers[newParameter].exposedName = VFXParameterController.GetDefaultExposedName(newParameter.type);
}
NotifyChange(AnyThing);
@@ -1451,22 +1451,29 @@ internal VFXViewController(VisualEffectResource vfx, bool initializeUndoStack =
void Sanitize()
{
VFXParameter[] parameters = m_ParameterControllers.Keys.OrderBy(t => t.order).ToArray();
- if (parameters.Length > 0)
- {
- var existingNames = new HashSet(StringComparer.OrdinalIgnoreCase);
-
- existingNames.Add(parameters[0].exposedName);
- m_ParameterControllers[parameters[0]].order = 0;
- for (int i = 1; i < parameters.Length; ++i)
- {
- var controller = m_ParameterControllers[parameters[i]];
- controller.order = i;
+ // A parameter keeps its name unless an earlier parameter has it or it breaks the naming rules
+ var takenNames = new HashSet(StringComparer.OrdinalIgnoreCase);
+ var renamedParameters = new List();
+ for (int i = 0; i < parameters.Length; ++i)
+ {
+ VFXParameter parameter = parameters[i];
+ m_ParameterControllers[parameter].order = i;
- controller.CheckNameUnique(existingNames);
+ string exposedName = parameter.exposedName;
+ string candidateName = VFXParameterController.MakeNameUnique(exposedName, takenNames, true, VFXParameterController.kMaxExposedNameLength);
+ if (candidateName == null || candidateName == exposedName)
+ takenNames.Add(exposedName);
+ else
+ renamedParameters.Add(parameter);
+ }
- existingNames.Add(parameters[i].exposedName);
- }
+ // New names avoid every kept name, including those of later parameters
+ foreach (var parameter in renamedParameters)
+ {
+ string newName = VFXParameterController.MakeNameUnique(parameter.exposedName, takenNames, true, VFXParameterController.kMaxExposedNameLength);
+ takenNames.Add(newName);
+ parameter.SetSettingValue("m_ExposedName", newName);
}
}
diff --git a/Packages/com.unity.visualeffectgraph/Editor/GraphView/Views/VFXView.cs b/Packages/com.unity.visualeffectgraph/Editor/GraphView/Views/VFXView.cs
index 18a51335355..330d7844991 100644
--- a/Packages/com.unity.visualeffectgraph/Editor/GraphView/Views/VFXView.cs
+++ b/Packages/com.unity.visualeffectgraph/Editor/GraphView/Views/VFXView.cs
@@ -3484,7 +3484,7 @@ public string DuplicateBlackBoardCategory(string category, string newCategoryNam
for (var i = 0; i < newParametersControllers.Length; i++)
{
var parameterController = newParametersControllers[i];
- var newParameterName = VFXParameterController.MakeNameUnique(m_Controller, parameterController.exposedName);
+ var newParameterName = VFXParameterController.MakeNameUnique(m_Controller, parameterController.exposedName, VFXParameterController.kMaxExposedNameLength);
var newVfxParameter = VFXParameter.Duplicate(newParameterName, parameterController.model);
controller.AddVFXModel(Vector2.zero, newVfxParameter);
diff --git a/Packages/com.unity.visualeffectgraph/Editor/Models/Blocks/Implementations/HLSL/HLSLParser.cs b/Packages/com.unity.visualeffectgraph/Editor/Models/Blocks/Implementations/HLSL/HLSLParser.cs
index 82b8c6170a2..02c045c901c 100644
--- a/Packages/com.unity.visualeffectgraph/Editor/Models/Blocks/Implementations/HLSL/HLSLParser.cs
+++ b/Packages/com.unity.visualeffectgraph/Editor/Models/Blocks/Implementations/HLSL/HLSLParser.cs
@@ -250,7 +250,8 @@ static HLSLFunction()
public static IEnumerable Parse(IVFXAttributesManager attributesManager, string hlsl)
{
- var matches = s_FunctionParser.Matches(hlsl.Trim());
+ string trimmedHLSL = hlsl.Trim();
+ var matches = s_FunctionParser.Matches(trimmedHLSL);
for (var i = 0; i < matches.Count; i++)
{
var match = matches[i];
@@ -258,8 +259,8 @@ public static IEnumerable Parse(IVFXAttributesManager attributesMa
if (!isHidden)
{
var bodyStartIndex = match.Index + match.Length;
- var bodyEndIndex = (i + 1) < matches.Count ? matches[i + 1].Index - 1 : hlsl.Length - 1;
- var body = hlsl.Substring(bodyStartIndex, bodyEndIndex - bodyStartIndex + 1).TrimEnd();
+ var bodyEndIndex = (i + 1) < matches.Count ? matches[i + 1].Index - 1 : trimmedHLSL.Length - 1;
+ var body = trimmedHLSL.Substring(bodyStartIndex, bodyEndIndex - bodyStartIndex + 1).TrimEnd();
yield return new HLSLFunction(attributesManager,
match.Index,
diff --git a/Tests/SRPTests/Packages/com.unity.testing.hdrp/RP_Assets/HDRP_Test_Both_FP16_PPAlpha_STP.asset b/Tests/SRPTests/Packages/com.unity.testing.hdrp/RP_Assets/HDRP_Test_Both_FP16_PPAlpha_STP.asset
new file mode 100644
index 00000000000..6ea1ff3c256
--- /dev/null
+++ b/Tests/SRPTests/Packages/com.unity.testing.hdrp/RP_Assets/HDRP_Test_Both_FP16_PPAlpha_STP.asset
@@ -0,0 +1,552 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &11400000
+MonoBehaviour:
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: 0cf1dab834d4ec34195b920ea7bbf9ec, type: 3}
+ m_Name: HDRP_Test_Both_FP16_PPAlpha_STP
+ m_EditorClassIdentifier:
+ m_RenderPipelineSettings:
+ supportShadowMask: 1
+ supportSSR: 1
+ supportSSRTransparent: 0
+ supportSSAO: 1
+ supportSSGI: 0
+ supportSubsurfaceScattering: 1
+ sssSampleBudget:
+ m_Values: 140000002800000050000000
+ m_SchemaId:
+ m_Id: With3Levels
+ sssDownsampleSteps:
+ m_Values: 000000000000000000000000
+ m_SchemaId:
+ m_Id: With3Levels
+ supportVolumetrics: 1
+ supportVolumetricClouds: 0
+ supportLightLayers: 1
+ renderingLayerMaskBuffer: 0
+ supportWater: 0
+ waterSimulationResolution: 128
+ supportWaterExclusion: 0
+ supportWaterDeformation: 0
+ deformationAtlasSize: 512
+ maximumDeformerCount: 64
+ supportWaterFoam: 0
+ foamAtlasSize: 512
+ waterCPUSimulation: 0
+ supportComputeThickness: 0
+ computeThicknessResolution: 1
+ computeThicknessLayerMask:
+ serializedVersion: 2
+ m_Bits: 0
+ supportDistortion: 1
+ supportTransparentBackface: 1
+ supportTransparentDepthPrepass: 1
+ supportTransparentDepthPostpass: 1
+ colorBufferFormat: 48
+ supportCustomPass: 1
+ customBufferFormat: 12
+ supportedLitShaderMode: 3
+ planarReflectionResolution:
+ m_Values: 000100000004000000080000
+ m_SchemaId:
+ m_Id: With3Levels
+ cubeReflectionResolution:
+ m_Values: 800000000001000000020000
+ m_SchemaId:
+ m_Id: With3Levels
+ supportDecals: 1
+ supportDecalLayers: 0
+ supportSurfaceGradient: 0
+ decalNormalBufferHP: 0
+ supportHighQualityLineRendering: 0
+ highQualityLineRenderingMemoryBudget: 128
+ msaaSampleCount: 1
+ supportMotionVectors: 1
+ supportScreenSpaceLensFlare: 1
+ supportDataDrivenLensFlare: 1
+ supportDitheringCrossFade: 0
+ supportRuntimeAOVAPI: 0
+ supportTerrainHole: 1
+ lightProbeSystem: 0
+ oldLightProbeSystem: 0
+ probeVolumeMemoryBudget: 1024
+ supportProbeVolumeGPUStreaming: 0
+ supportProbeVolumeDiskStreaming: 0
+ probeVolumeSHBands: 1
+ supportProbeVolumeScenarios: 0
+ supportProbeVolumeScenarioBlending: 1
+ probeVolumeBlendingMemoryBudget: 128
+ supportRayTracing: 0
+ supportVFXRayTracing: 0
+ supportedRayTracingMode: 3
+ lightLoopSettings:
+ cookieAtlasSize: 512
+ cookieFormat: 74
+ cookieAtlasLastValidMip: 0
+ cookieTexArraySize: 16
+ planarReflectionAtlasSize: 2048
+ reflectionProbeCacheSize: 128
+ reflectionCubemapSize: 128
+ maxEnvLightsOnScreen: 64
+ reflectionCacheCompressed: 0
+ reflectionProbeFormat: 74
+ reflectionProbeTexCacheSize: 4096
+ reflectionProbeTexLastValidCubeMip: 3
+ reflectionProbeTexLastValidPlanarMip: 0
+ reflectionProbeDecreaseResToFit: 1
+ skyReflectionSize: 256
+ skyLightingOverrideLayerMask:
+ serializedVersion: 2
+ m_Bits: 0
+ supportFabricConvolution: 0
+ maxDirectionalLightsOnScreen: 16
+ maxPunctualLightsOnScreen: 512
+ maxAreaLightsOnScreen: 64
+ maxCubeReflectionOnScreen: 48
+ maxPlanarReflectionOnScreen: 16
+ maxDecalsOnScreen: 512
+ maxLightsPerClusterCell: 8
+ maxLocalVolumetricFogSize: 32
+ maxLocalVolumetricFogOnScreen: 64
+ hdShadowInitParams:
+ maxShadowRequests: 128
+ directionalShadowsDepthBits: 32
+ punctualShadowFilteringQuality: 0
+ directionalShadowFilteringQuality: 0
+ areaShadowFilteringQuality: 0
+ punctualLightShadowAtlas:
+ shadowAtlasResolution: 4096
+ shadowAtlasDepthBits: 32
+ useDynamicViewportRescale: 0
+ areaLightShadowAtlas:
+ shadowAtlasResolution: 4096
+ shadowAtlasDepthBits: 32
+ useDynamicViewportRescale: 0
+ cachedPunctualLightShadowAtlas: 2048
+ cachedAreaLightShadowAtlas: 1024
+ allowDirectionalMixedCachedShadows: 0
+ shadowResolutionDirectional:
+ m_Values: 00010000000200000004000000080000
+ m_SchemaId:
+ m_Id: With4Levels
+ shadowResolutionPunctual:
+ m_Values: 00010000000200000004000000080000
+ m_SchemaId:
+ m_Id: With4Levels
+ shadowResolutionArea:
+ m_Values: 00010000000200000004000000080000
+ m_SchemaId:
+ m_Id: With4Levels
+ maxDirectionalShadowMapResolution: 2048
+ maxPunctualShadowMapResolution: 2048
+ maxAreaShadowMapResolution: 2048
+ supportScreenSpaceShadows: 0
+ maxScreenSpaceShadowSlots: 4
+ screenSpaceShadowBufferFormat: 48
+ decalSettings:
+ drawDistance: 1000
+ atlasWidth: 2048
+ atlasHeight: 1024
+ transparentTextureResolution:
+ m_Values: 000100000002000000040000
+ m_SchemaId:
+ m_Id: With3Levels
+ perChannelMask: 1
+ postProcessSettings:
+ m_LutSize: 32
+ lutFormat: 48
+ bufferFormat: 48
+ dynamicResolutionSettings:
+ enabled: 1
+ useMipBias: 1
+ advancedUpscalerNames:
+ - STP
+ enableDLSS: 0
+ DLSSPerfQualitySetting: 0
+ DLSSInjectionPoint: 0
+ DLSSUseOptimalSettings: 1
+ DLSSSharpness: 0.5
+ fsrOverrideSharpness: 0
+ fsrSharpness: 0.92
+ maxPercentage: 100
+ minPercentage: 100
+ dynResType: 0
+ upsampleFilter: 5
+ forceResolution: 1
+ forcedPercentage: 50
+ lowResTransparencyMinimumThreshold: 0
+ rayTracingHalfResThreshold: 50
+ lowresTransparentSettings:
+ enabled: 1
+ checkerboardDepthBuffer: 1
+ upsampleType: 1
+ xrSettings:
+ singlePass: 1
+ occlusionMesh: 1
+ cameraJitter: 1
+ allowMotionBlur: 0
+ postProcessQualitySettings:
+ NearBlurSampleCount: 030000000500000008000000
+ NearBlurMaxRadius:
+ - 2
+ - 4
+ - 7
+ FarBlurSampleCount: 04000000070000000e000000
+ FarBlurMaxRadius:
+ - 5
+ - 8
+ - 13
+ DoFResolution: 040000000200000001000000
+ DoFHighQualityFiltering: 000101
+ DoFPhysicallyBased: 000000
+ LimitManualRangeNearBlur: 000000
+ MotionBlurSampleCount: 04000000080000000c000000
+ BloomRes: 040000000200000002000000
+ BloomHighQualityFiltering: 000101
+ BloomHighQualityPrefiltering: 000001
+ ChromaticAberrationMaxSamples: 03000000060000000c000000
+ lightSettings:
+ useContactShadow:
+ m_Values: 000000
+ m_SchemaId:
+ m_Id:
+ maximumLODLevel:
+ m_Values: 000000000000000000000000
+ m_SchemaId:
+ m_Id: With3Levels
+ lodBias:
+ m_Values:
+ - 1
+ - 1
+ - 1
+ m_SchemaId:
+ m_Id: With3Levels
+ lightingQualitySettings:
+ AOStepCount: 040000000600000010000000
+ AOFullRes: 000001
+ AOMaximumRadiusPixels: 200000002800000050000000
+ AOBilateralUpsample: 000101
+ AODirectionCount: 010000000200000004000000
+ ContactShadowSampleCount: 060000000a00000010000000
+ SSRMaxRaySteps: 100000002000000040000000
+ SSGIRaySteps: 200000004000000080000000
+ SSGIDenoise: 010101
+ SSGIHalfResDenoise: 010000
+ SSGIDenoiserRadius:
+ - 0.75
+ - 0.5
+ - 0.5
+ SSGISecondDenoise: 010101
+ RTAORayLength:
+ - 0.5
+ - 3
+ - 20
+ RTAOSampleCount: 010000000200000008000000
+ RTAODenoise: 010101
+ RTAODenoiserRadius:
+ - 0.25
+ - 0.5
+ - 0.65
+ RTGIRayLength:
+ - 50
+ - 50
+ - 50
+ RTGIFullResolution: 000001
+ RTGIClampValue:
+ - 0.5
+ - 0.8
+ - 1.5
+ RTGIRaySteps: 200000003000000040000000
+ RTGIDenoise: 010101
+ RTGIHalfResDenoise: 010000
+ RTGIDenoiserRadius:
+ - 0.75
+ - 0.5
+ - 0.25
+ RTGISecondDenoise: 010101
+ RTRMinSmoothness:
+ - 0.6
+ - 0.4
+ - 0
+ RTRSmoothnessFadeStart:
+ - 0.7
+ - 0.5
+ - 0
+ RTRRayLength:
+ - 50
+ - 50
+ - 50
+ RTRClampValue:
+ - 0.8
+ - 1
+ - 1.2
+ RTRFullResolution: 000001
+ RTRRayMaxIterations: 200000003000000040000000
+ RTRDenoise: 010101
+ RTRDenoiserRadiusDimmer:
+ - 0.75
+ - 0.75
+ - 1
+ RTRDenoiserAntiFlicker:
+ - 1
+ - 1
+ - 1
+ Fog_ControlMode: 000000000000000000000000
+ Fog_Budget:
+ - 0.166
+ - 0.33
+ - 0.666
+ Fog_DepthRatio:
+ - 0.666
+ - 0.666
+ - 0.5
+ m_ObsoleteLightLayerName0: Light Layer default
+ m_ObsoleteLightLayerName1: Light Layer 1
+ m_ObsoleteLightLayerName2: Light Layer 2
+ m_ObsoleteLightLayerName3: Light Layer 3
+ m_ObsoleteLightLayerName4: Light Layer 4
+ m_ObsoleteLightLayerName5: Light Layer 5
+ m_ObsoleteLightLayerName6: Light Layer 6
+ m_ObsoleteLightLayerName7: Light Layer 7
+ m_ObsoleteDecalLayerName0:
+ m_ObsoleteDecalLayerName1:
+ m_ObsoleteDecalLayerName2:
+ m_ObsoleteDecalLayerName3:
+ m_ObsoleteDecalLayerName4:
+ m_ObsoleteDecalLayerName5:
+ m_ObsoleteDecalLayerName6:
+ m_ObsoleteDecalLayerName7:
+ m_ObsoleteSupportRuntimeDebugDisplay: 0
+ allowShaderVariantStripping: 1
+ enableSRPBatcher: 1
+ availableMaterialQualityLevels: -1
+ m_DefaultMaterialQualityLevel: 4
+ diffusionProfileSettings: {fileID: 11400000, guid: 802c802428a2d9640a87e821dfcdd9e8,
+ type: 2}
+ m_VolumeProfile: {fileID: 0}
+ virtualTexturingSettings:
+ streamingCpuCacheSizeInMegaBytes: 80
+ streamingMipPreloadTexturesPerFrame: 0
+ streamingPreloadMipCount: 1
+ streamingGpuCacheSettings:
+ - format: 0
+ sizeInMegaBytes: 32
+ m_UseRenderGraph: 1
+ m_Version: 26
+ m_ObsoleteFrameSettings:
+ overrides: 0
+ enableShadow: 0
+ enableContactShadows: 0
+ enableShadowMask: 0
+ enableSSR: 0
+ enableSSAO: 0
+ enableSubsurfaceScattering: 0
+ enableTransmission: 0
+ enableAtmosphericScattering: 0
+ enableVolumetrics: 0
+ enableReprojectionForVolumetrics: 0
+ enableLightLayers: 0
+ enableExposureControl: 1
+ diffuseGlobalDimmer: 0
+ specularGlobalDimmer: 0
+ shaderLitMode: 0
+ enableDepthPrepassWithDeferredRendering: 0
+ enableTransparentPrepass: 0
+ enableMotionVectors: 0
+ enableObjectMotionVectors: 0
+ enableDecals: 0
+ enableRoughRefraction: 0
+ enableTransparentPostpass: 0
+ enableDistortion: 0
+ enablePostprocess: 0
+ enableOpaqueObjects: 0
+ enableTransparentObjects: 0
+ enableRealtimePlanarReflection: 0
+ enableMSAA: 0
+ enableAsyncCompute: 0
+ runLightListAsync: 0
+ runSSRAsync: 0
+ runSSAOAsync: 0
+ runContactShadowsAsync: 0
+ runVolumeVoxelizationAsync: 0
+ lightLoopSettings:
+ overrides: 0
+ enableDeferredTileAndCluster: 0
+ enableComputeLightEvaluation: 0
+ enableComputeLightVariants: 0
+ enableComputeMaterialVariants: 0
+ enableFptlForForwardOpaque: 0
+ enableBigTilePrepass: 0
+ isFptlEnabled: 0
+ m_ObsoleteBakedOrCustomReflectionFrameSettings:
+ overrides: 0
+ enableShadow: 0
+ enableContactShadows: 0
+ enableShadowMask: 0
+ enableSSR: 0
+ enableSSAO: 0
+ enableSubsurfaceScattering: 0
+ enableTransmission: 0
+ enableAtmosphericScattering: 0
+ enableVolumetrics: 0
+ enableReprojectionForVolumetrics: 0
+ enableLightLayers: 0
+ enableExposureControl: 1
+ diffuseGlobalDimmer: 0
+ specularGlobalDimmer: 0
+ shaderLitMode: 0
+ enableDepthPrepassWithDeferredRendering: 0
+ enableTransparentPrepass: 0
+ enableMotionVectors: 0
+ enableObjectMotionVectors: 0
+ enableDecals: 0
+ enableRoughRefraction: 0
+ enableTransparentPostpass: 0
+ enableDistortion: 0
+ enablePostprocess: 0
+ enableOpaqueObjects: 0
+ enableTransparentObjects: 0
+ enableRealtimePlanarReflection: 0
+ enableMSAA: 0
+ enableAsyncCompute: 0
+ runLightListAsync: 0
+ runSSRAsync: 0
+ runSSAOAsync: 0
+ runContactShadowsAsync: 0
+ runVolumeVoxelizationAsync: 0
+ lightLoopSettings:
+ overrides: 0
+ enableDeferredTileAndCluster: 0
+ enableComputeLightEvaluation: 0
+ enableComputeLightVariants: 0
+ enableComputeMaterialVariants: 0
+ enableFptlForForwardOpaque: 0
+ enableBigTilePrepass: 0
+ isFptlEnabled: 0
+ m_ObsoleteRealtimeReflectionFrameSettings:
+ overrides: 0
+ enableShadow: 0
+ enableContactShadows: 0
+ enableShadowMask: 0
+ enableSSR: 0
+ enableSSAO: 0
+ enableSubsurfaceScattering: 0
+ enableTransmission: 0
+ enableAtmosphericScattering: 0
+ enableVolumetrics: 0
+ enableReprojectionForVolumetrics: 0
+ enableLightLayers: 0
+ enableExposureControl: 1
+ diffuseGlobalDimmer: 0
+ specularGlobalDimmer: 0
+ shaderLitMode: 0
+ enableDepthPrepassWithDeferredRendering: 0
+ enableTransparentPrepass: 0
+ enableMotionVectors: 0
+ enableObjectMotionVectors: 0
+ enableDecals: 0
+ enableRoughRefraction: 0
+ enableTransparentPostpass: 0
+ enableDistortion: 0
+ enablePostprocess: 0
+ enableOpaqueObjects: 0
+ enableTransparentObjects: 0
+ enableRealtimePlanarReflection: 0
+ enableMSAA: 0
+ enableAsyncCompute: 0
+ runLightListAsync: 0
+ runSSRAsync: 0
+ runSSAOAsync: 0
+ runContactShadowsAsync: 0
+ runVolumeVoxelizationAsync: 0
+ lightLoopSettings:
+ overrides: 0
+ enableDeferredTileAndCluster: 0
+ enableComputeLightEvaluation: 0
+ enableComputeLightVariants: 0
+ enableComputeMaterialVariants: 0
+ enableFptlForForwardOpaque: 0
+ enableBigTilePrepass: 0
+ isFptlEnabled: 0
+ m_ObsoleteDefaultVolumeProfile: {fileID: 0}
+ m_ObsoleteDefaultLookDevProfile: {fileID: 0}
+ m_ObsoleteFrameSettingsMovedToDefaultSettings:
+ bitDatas:
+ data1: 139549384114013
+ data2: 4539628425463136280
+ lodBias: 1
+ lodBiasMode: 0
+ lodBiasQualityLevel: 0
+ maximumLODLevel: 0
+ maximumLODLevelMode: 0
+ maximumLODLevelQualityLevel: 0
+ sssQualityMode: 0
+ sssQualityLevel: 0
+ sssCustomSampleBudget: 20
+ sssCustomDownsampleSteps: 0
+ msaaMode: 0
+ materialQuality: 0
+ m_ObsoleteBakedOrCustomReflectionFrameSettingsMovedToDefaultSettings:
+ bitDatas:
+ data1: 139713129348893
+ data2: 4539628424389459992
+ lodBias: 1
+ lodBiasMode: 0
+ lodBiasQualityLevel: 0
+ maximumLODLevel: 0
+ maximumLODLevelMode: 0
+ maximumLODLevelQualityLevel: 0
+ sssQualityMode: 0
+ sssQualityLevel: 0
+ sssCustomSampleBudget: 20
+ sssCustomDownsampleSteps: 0
+ msaaMode: 0
+ materialQuality: 0
+ m_ObsoleteRealtimeReflectionFrameSettingsMovedToDefaultSettings:
+ bitDatas:
+ data1: 140065316601629
+ data2: 4539628424389459992
+ lodBias: 1
+ lodBiasMode: 0
+ lodBiasQualityLevel: 0
+ maximumLODLevel: 0
+ maximumLODLevelMode: 0
+ maximumLODLevelQualityLevel: 0
+ sssQualityMode: 0
+ sssQualityLevel: 0
+ sssCustomSampleBudget: 20
+ sssCustomDownsampleSteps: 0
+ msaaMode: 0
+ materialQuality: 0
+ m_ObsoleteRenderPipelineResources: {fileID: 11400000, guid: 3ce144cff5783da45aa5d4fdc2da14b7,
+ type: 2}
+ m_ObsoleteRenderPipelineRayTracingResources: {fileID: 0}
+ m_ObsoleteBeforeTransparentCustomPostProcesses: []
+ m_ObsoleteBeforePostProcessCustomPostProcesses: []
+ m_ObsoleteAfterPostProcessCustomPostProcesses: []
+ m_ObsoleteBeforeTAACustomPostProcesses: []
+ m_ObsoleteShaderVariantLogLevel: 1
+ m_ObsoleteLensAttenuation: 0
+ m_ObsoleteDiffusionProfileSettingsList:
+ - {fileID: 11400000, guid: 802c802428a2d9640a87e821dfcdd9e8, type: 2}
+ - {fileID: 11400000, guid: 09c63d8f96a14884e8efd2f01004f491, type: 2}
+ - {fileID: 11400000, guid: 8471a5bfcdb8fff4f9406cd8079b8554, type: 2}
+ - {fileID: 11400000, guid: 968a3176000311d42af174756ece7f4d, type: 2}
+ - {fileID: 11400000, guid: 768484f758b6f7b4daf53a7d9949f5af, type: 2}
+ - {fileID: 11400000, guid: fcb8f92518ca5d14bbd7e6751b28cd24, type: 2}
+ - {fileID: 11400000, guid: 64ca25f51b132ea4093511f7456ea220, type: 2}
+ - {fileID: 11400000, guid: fd29a6d903d5eae4d94833c2048bfd9d, type: 2}
+ - {fileID: 11400000, guid: 76f34276e6d50dc4bb0762b87af8931e, type: 2}
+ - {fileID: 11400000, guid: cd1cd5a7c0527844dbca2b7d562b9049, type: 2}
+ - {fileID: 11400000, guid: 385fff18b5c61754188b49a485ecb84a, type: 2}
+ - {fileID: 11400000, guid: d3dd41407c183554ca54bded902d4b7b, type: 2}
+ - {fileID: 11400000, guid: 86c1c808ebce1cc4992b9b0fd197a0b3, type: 2}
+ - {fileID: 11400000, guid: 3506ae472b257f042af66a183fbaac6a, type: 2}
+ - {fileID: 11400000, guid: 6be2047feaba36945b8fd12f29e3a7b5, type: 2}
diff --git a/Tests/SRPTests/Packages/com.unity.testing.hdrp/RP_Assets/HDRP_Test_Both_FP16_PPAlpha_STP.asset.meta b/Tests/SRPTests/Packages/com.unity.testing.hdrp/RP_Assets/HDRP_Test_Both_FP16_PPAlpha_STP.asset.meta
new file mode 100644
index 00000000000..eef652c3cb9
--- /dev/null
+++ b/Tests/SRPTests/Packages/com.unity.testing.hdrp/RP_Assets/HDRP_Test_Both_FP16_PPAlpha_STP.asset.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 2fc7e7c78d3f4b29afb8f544ee1e1ae3
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 0
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Packages/local.gtf.references/package.json b/Tests/SRPTests/Packages/local.gtf.references/package.json
new file mode 100644
index 00000000000..2fcab8ae2f2
--- /dev/null
+++ b/Tests/SRPTests/Packages/local.gtf.references/package.json
@@ -0,0 +1,18 @@
+{
+ "displayName": "Graphics Test Framework (published v9)",
+ "name": "local.gtf.references",
+ "version": "1.0.0",
+ "unity": "6000.6",
+ "description": "Shim package that contains a reference to the com.unity.testframework.graphics package for easier version pinning.",
+ "keywords": [
+ "qa",
+ "test",
+ "testing",
+ "tests",
+ "graphics"
+ ],
+ "category": "Libraries",
+ "dependencies": {
+ "com.unity.testframework.graphics": "9.0.0-pre.32"
+ }
+}
diff --git a/Tests/SRPTests/Packages/local.gtf.references/package.json.meta b/Tests/SRPTests/Packages/local.gtf.references/package.json.meta
new file mode 100644
index 00000000000..592a323c294
--- /dev/null
+++ b/Tests/SRPTests/Packages/local.gtf.references/package.json.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 81773ed82dd27614a859d3f421000966
+PackageManifestImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/BatchRendererGroup_HDRP/Packages/manifest.json b/Tests/SRPTests/Projects/BatchRendererGroup_HDRP/Packages/manifest.json
index bd6a0bf0577..31bd9baed5a 100644
--- a/Tests/SRPTests/Projects/BatchRendererGroup_HDRP/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/BatchRendererGroup_HDRP/Packages/manifest.json
@@ -11,7 +11,7 @@
"com.unity.render-pipelines.high-definition-config": "file:../../../../../Packages/com.unity.render-pipelines.high-definition-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.brg": "file:../../../Packages/com.unity.testing.brg",
"com.unity.testing.xr": "file:../../../Packages/com.unity.testing.xr",
"com.unity.ugui": "2.0.0",
diff --git a/Tests/SRPTests/Projects/BatchRendererGroup_URP/Packages/manifest.json b/Tests/SRPTests/Projects/BatchRendererGroup_URP/Packages/manifest.json
index 502642ad240..741bf1f0cf3 100644
--- a/Tests/SRPTests/Projects/BatchRendererGroup_URP/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/BatchRendererGroup_URP/Packages/manifest.json
@@ -10,7 +10,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.brg": "file:../../../Packages/com.unity.testing.brg",
"com.unity.testing.xr": "file:../../../Packages/com.unity.testing.xr",
"com.unity.ugui": "2.0.0",
diff --git a/Tests/SRPTests/Projects/BuiltInGraphicsTest_Foundation/Packages/manifest.json b/Tests/SRPTests/Projects/BuiltInGraphicsTest_Foundation/Packages/manifest.json
index c362edb6515..6432b55f282 100644
--- a/Tests/SRPTests/Projects/BuiltInGraphicsTest_Foundation/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/BuiltInGraphicsTest_Foundation/Packages/manifest.json
@@ -15,7 +15,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.xr": "file:../../../Packages/com.unity.testing.xr",
"com.unity.ugui": "2.0.0",
"com.unity.modules.ai": "1.0.0",
diff --git a/Tests/SRPTests/Projects/BuiltInGraphicsTest_Lighting/Packages/manifest.json b/Tests/SRPTests/Projects/BuiltInGraphicsTest_Lighting/Packages/manifest.json
index c362edb6515..6432b55f282 100644
--- a/Tests/SRPTests/Projects/BuiltInGraphicsTest_Lighting/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/BuiltInGraphicsTest_Lighting/Packages/manifest.json
@@ -15,7 +15,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.xr": "file:../../../Packages/com.unity.testing.xr",
"com.unity.ugui": "2.0.0",
"com.unity.modules.ai": "1.0.0",
diff --git a/Tests/SRPTests/Projects/HDRP_DXR_Tests/Packages/manifest.json b/Tests/SRPTests/Projects/HDRP_DXR_Tests/Packages/manifest.json
index 2186089ad1b..e771fd52999 100644
--- a/Tests/SRPTests/Projects/HDRP_DXR_Tests/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/HDRP_DXR_Tests/Packages/manifest.json
@@ -10,7 +10,7 @@
"com.unity.rendering.denoising": "1.0.5",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.common-graphics": "file:../../../Packages/com.unity.testing.common-graphics",
"com.unity.testing.hdrp": "file:../../../Packages/com.unity.testing.hdrp",
"com.unity.testing.xr": "file:../../../Packages/com.unity.testing.xr",
diff --git a/Tests/SRPTests/Projects/HDRP_RuntimeTests/Packages/manifest.json b/Tests/SRPTests/Projects/HDRP_RuntimeTests/Packages/manifest.json
index 29d69aaa116..818d2e9f0ef 100644
--- a/Tests/SRPTests/Projects/HDRP_RuntimeTests/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/HDRP_RuntimeTests/Packages/manifest.json
@@ -9,7 +9,7 @@
"com.unity.render-pipelines.high-definition-config": "file:../../../../../Packages/com.unity.render-pipelines.high-definition-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.hdrp": "file:../../../Packages/com.unity.testing.hdrp",
"com.unity.testing.xr": "file:../../../Packages/com.unity.testing.xr",
"com.unity.ugui": "2.0.0",
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha.meta b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha.meta
new file mode 100644
index 00000000000..bb2a10f0509
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 1b7df8c4f3dd1544a9a89bcaed43f2ea
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha.unity b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha.unity
new file mode 100644
index 00000000000..fd2c99d3347
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha.unity
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:fcfa2368305c30b7da54eb93ca62ed4b33c2e9b592ea3a9032d7265bfb045b50
+size 30615
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha.unity.meta b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha.unity.meta
new file mode 100644
index 00000000000..be64d709bc8
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha.unity.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 861fa82a1b434385a3bf6f3536540712
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/.gitignore b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/.gitignore
new file mode 100644
index 00000000000..1c33e83589d
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/.gitignore
@@ -0,0 +1,3 @@
+Lightmap-*_comp*
+LightingData.*
+ReflectionProbe-*
\ No newline at end of file
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.mat b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.mat
new file mode 100644
index 00000000000..4acb4586790
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.mat
@@ -0,0 +1,29 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: DisplayRTTAlpha
+ m_Shader: {fileID: 4800000, guid: 3687b28368c049c7bf70c618b9eb3bdd, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords: []
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: -1
+ stringTagMap: {}
+ disabledShaderPasses: []
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs: []
+ m_Ints: []
+ m_Floats: []
+ m_Colors: []
+ m_BuildTextureStacks: []
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.mat.meta b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.mat.meta
new file mode 100644
index 00000000000..01fa6c2cb77
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 61293c857b814ebb982da40204ec4d6e
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.shader b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.shader
new file mode 100644
index 00000000000..d6b2318a5a6
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.shader
@@ -0,0 +1,61 @@
+Shader "FullScreen/DisplayRTTAlpha"
+{
+ HLSLINCLUDE
+
+ #pragma vertex Vert
+
+ #pragma target 4.5
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
+
+ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassCommon.hlsl"
+
+ float4 CopyAlphaPass(Varyings varyings) : SV_Target
+ {
+ UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(varyings);
+
+ float alpha = LOAD_TEXTURE2D_X_LOD(_AfterPostProcessColorBuffer, varyings.positionCS.xy, 0).a;
+
+ return float4(alpha.xxx, 1.0);
+ }
+
+ float4 DisplayAlphaPass(Varyings varyings) : SV_Target
+ {
+ UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(varyings);
+
+ return float4(CustomPassLoadCustomColor(varyings.positionCS.xy).rgb, 1.0);
+ }
+
+ ENDHLSL
+
+ SubShader
+ {
+ Pass
+ {
+ Name "Copy Alpha"
+
+ ZWrite Off
+ ZTest Always
+ Blend Off
+ Cull Off
+
+ HLSLPROGRAM
+ #pragma fragment CopyAlphaPass
+ ENDHLSL
+ }
+
+ Pass
+ {
+ Name "Display Alpha"
+
+ ZWrite Off
+ ZTest Always
+ Blend Off
+ Cull Off
+
+ HLSLPROGRAM
+ #pragma fragment DisplayAlphaPass
+ ENDHLSL
+ }
+ }
+ Fallback Off
+}
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.shader.meta b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.shader.meta
new file mode 100644
index 00000000000..be1d8474d5f
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/DisplayRTTAlpha.shader.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 3687b28368c049c7bf70c618b9eb3bdd
+ShaderImporter:
+ externalObjects: {}
+ defaultTextures: []
+ nonModifiableTextures: []
+ preprocessorOverride: 0
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterial.mat b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterial.mat
new file mode 100644
index 00000000000..f8766c655f4
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterial.mat
@@ -0,0 +1,307 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-5166128023983884676
+MonoBehaviour:
+ m_ObjectHideFlags: 11
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: da692e001514ec24dbc4cca1949ff7e8, type: 3}
+ m_Name:
+ m_EditorClassIdentifier:
+ version: 13
+ hdPluginSubTargetMaterialVersions:
+ m_Keys: []
+ m_Values:
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: SphereMaterial
+ m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords:
+ - _DISABLE_SSR_TRANSPARENT
+ - _NORMALMAP_TANGENT_SPACE
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: 2225
+ stringTagMap: {}
+ disabledShaderPasses:
+ - DistortionVectors
+ - MOTIONVECTORS
+ - ForwardEmissiveForDeferred
+ - TransparentDepthPrepass
+ - TransparentDepthPostpass
+ - TransparentBackface
+ - RayTracingPrepass
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _AnisotropyMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BaseColorMap:
+ m_Texture: {fileID: 2800000, guid: 97a5684bc72c1704fadc965467f242ea, type: 3}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BentNormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BentNormalMapOS:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _CoatMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DistortionVectorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _EmissiveColorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _HeightMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _IridescenceMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _IridescenceThicknessMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 2800000, guid: 97a5684bc72c1704fadc965467f242ea, type: 3}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _NormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _NormalMapOS:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _SpecularColorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _SubsurfaceMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TangentMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TangentMapOS:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _ThicknessMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TransmissionMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TransmittanceColorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_Lightmaps:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_LightmapsInd:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_ShadowMasks:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _AORemapMax: 1
+ - _AORemapMin: 0
+ - _ATDistance: 1
+ - _AddPrecomputedVelocity: 0
+ - _AlbedoAffectEmissive: 0
+ - _AlphaCutoff: 0.5
+ - _AlphaCutoffEnable: 0
+ - _AlphaCutoffPostpass: 0.5
+ - _AlphaCutoffPrepass: 0.5
+ - _AlphaCutoffShadow: 0.5
+ - _AlphaDstBlend: 0
+ - _AlphaRemapMax: 1
+ - _AlphaRemapMin: 0
+ - _AlphaSrcBlend: 1
+ - _AlphaToMask: 0
+ - _AlphaToMaskInspectorValue: 0
+ - _Anisotropy: 0
+ - _BlendMode: 0
+ - _CoatMask: 0
+ - _CullMode: 2
+ - _CullModeForward: 2
+ - _Cutoff: 0.5
+ - _DepthOffsetEnable: 0
+ - _DetailAlbedoScale: 1
+ - _DetailNormalScale: 1
+ - _DetailSmoothnessScale: 1
+ - _DiffusionProfile: 0
+ - _DiffusionProfileHash: 0
+ - _DisplacementLockObjectScale: 1
+ - _DisplacementLockTilingScale: 1
+ - _DisplacementMode: 0
+ - _DistortionBlendMode: 0
+ - _DistortionBlurBlendMode: 0
+ - _DistortionBlurDstBlend: 1
+ - _DistortionBlurRemapMax: 1
+ - _DistortionBlurRemapMin: 0
+ - _DistortionBlurScale: 1
+ - _DistortionBlurSrcBlend: 1
+ - _DistortionDepthTest: 1
+ - _DistortionDstBlend: 1
+ - _DistortionEnable: 0
+ - _DistortionScale: 1
+ - _DistortionSrcBlend: 1
+ - _DistortionVectorBias: -1
+ - _DistortionVectorScale: 2
+ - _DoubleSidedEnable: 0
+ - _DoubleSidedGIMode: 0
+ - _DoubleSidedNormalMode: 1
+ - _DstBlend: 0
+ - _DstBlend2: 0
+ - _EmissiveColorMode: 1
+ - _EmissiveExposureWeight: 1
+ - _EmissiveIntensity: 1
+ - _EmissiveIntensityUnit: 0
+ - _EnableBlendModePreserveSpecularLighting: 1
+ - _EnableFogOnTransparent: 1
+ - _EnableGeometricSpecularAA: 0
+ - _EnergyConservingSpecularColor: 1
+ - _ForceForwardEmissive: 0
+ - _HdrpVersion: 2
+ - _HeightAmplitude: 0.02
+ - _HeightCenter: 0.5
+ - _HeightMapParametrization: 0
+ - _HeightMax: 1
+ - _HeightMin: -1
+ - _HeightOffset: 0
+ - _HeightPoMAmplitude: 2
+ - _HeightTessAmplitude: 2
+ - _HeightTessCenter: 0.5
+ - _InvTilingScale: 1
+ - _Ior: 1.5
+ - _IridescenceMask: 1
+ - _IridescenceThickness: 1
+ - _LinkDetailsWithBase: 1
+ - _MaterialID: 1
+ - _Metallic: 0
+ - _MetallicRemapMax: 0
+ - _MetallicRemapMin: 0
+ - _NormalMapSpace: 0
+ - _NormalScale: 1
+ - _ObjectSpaceUVMapping: 0
+ - _ObjectSpaceUVMappingEmissive: 0
+ - _OpaqueCullMode: 2
+ - _PPDLodThreshold: 5
+ - _PPDMaxSamples: 15
+ - _PPDMinSamples: 5
+ - _PPDPrimitiveLength: 1
+ - _PPDPrimitiveWidth: 1
+ - _PerPixelSorting: 0
+ - _RayTracing: 0
+ - _ReceivesSSR: 1
+ - _ReceivesSSRTransparent: 0
+ - _RefractionModel: 0
+ - _SSRefractionProjectionModel: 0
+ - _Smoothness: 0.5
+ - _SmoothnessRemapMax: 1
+ - _SmoothnessRemapMin: 0
+ - _SpecularAAScreenSpaceVariance: 0.1
+ - _SpecularAAThreshold: 0.2
+ - _SpecularOcclusionMode: 1
+ - _SrcBlend: 1
+ - _StencilRef: 0
+ - _StencilRefDepth: 8
+ - _StencilRefDistortionVec: 4
+ - _StencilRefGBuffer: 10
+ - _StencilRefMV: 40
+ - _StencilWriteMask: 6
+ - _StencilWriteMaskDepth: 9
+ - _StencilWriteMaskDistortionVec: 4
+ - _StencilWriteMaskGBuffer: 15
+ - _StencilWriteMaskMV: 41
+ - _SubsurfaceMask: 1
+ - _SupportDecals: 1
+ - _SurfaceType: 0
+ - _TexWorldScale: 1
+ - _TexWorldScaleEmissive: 1
+ - _Thickness: 1
+ - _TransmissionEnable: 1
+ - _TransmissionMask: 1
+ - _TransparentBackfaceEnable: 0
+ - _TransparentCullMode: 2
+ - _TransparentDepthPostpassEnable: 0
+ - _TransparentDepthPrepassEnable: 0
+ - _TransparentSortPriority: 0
+ - _TransparentWritingMotionVec: 0
+ - _TransparentZWrite: 0
+ - _UVBase: 0
+ - _UVDetail: 0
+ - _UVEmissive: 0
+ - _UseEmissiveIntensity: 0
+ - _UseShadowThreshold: 0
+ - _ZTestDepthEqualForOpaque: 3
+ - _ZTestGBuffer: 4
+ - _ZTestModeDistortion: 4
+ - _ZTestTransparent: 4
+ - _ZWrite: 1
+ m_Colors:
+ - _BaseColor: {r: 1, g: 1, b: 1, a: 1}
+ - _BaseColorMap_MipInfo: {r: 0, g: 0, b: 0, a: 0}
+ - _Color: {r: 1, g: 1, b: 1, a: 1}
+ - _DiffusionProfileAsset: {r: 0, g: 0, b: 0, a: 0}
+ - _DoubleSidedConstants: {r: 1, g: 1, b: -1, a: 0}
+ - _EmissionColor: {r: 1, g: 1, b: 1, a: 1}
+ - _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
+ - _EmissiveColorLDR: {r: 0, g: 0, b: 0, a: 1}
+ - _InvPrimScale: {r: 1, g: 1, b: 0, a: 0}
+ - _IridescenceThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
+ - _SpecularColor: {r: 1, g: 1, b: 1, a: 1}
+ - _ThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
+ - _TransmittanceColor: {r: 1, g: 1, b: 1, a: 1}
+ - _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
+ - _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}
+ - _UVMappingMaskEmissive: {r: 1, g: 0, b: 0, a: 0}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterial.mat.meta b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterial.mat.meta
new file mode 100644
index 00000000000..174bac4c8d1
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterial.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 2fe7f1bc231935f4e87d147c6633aee5
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTransp.mat b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTransp.mat
new file mode 100644
index 00000000000..b1ed35860d4
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTransp.mat
@@ -0,0 +1,310 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-5166128023983884676
+MonoBehaviour:
+ m_ObjectHideFlags: 11
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: da692e001514ec24dbc4cca1949ff7e8, type: 3}
+ m_Name:
+ m_EditorClassIdentifier:
+ version: 13
+ hdPluginSubTargetMaterialVersions:
+ m_Keys: []
+ m_Values:
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: SphereMaterialTransp
+ m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords:
+ - _DISABLE_SSR_TRANSPARENT
+ - _ENABLE_FOG_ON_TRANSPARENT
+ - _NORMALMAP_TANGENT_SPACE
+ - _SURFACE_TYPE_TRANSPARENT
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: 3000
+ stringTagMap:
+ RenderType: Transparent
+ disabledShaderPasses:
+ - DistortionVectors
+ - MOTIONVECTORS
+ - ForwardEmissiveForDeferred
+ - TransparentDepthPrepass
+ - TransparentDepthPostpass
+ - TransparentBackface
+ - RayTracingPrepass
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _AnisotropyMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BaseColorMap:
+ m_Texture: {fileID: 2800000, guid: 97a5684bc72c1704fadc965467f242ea, type: 3}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BentNormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BentNormalMapOS:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _CoatMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DistortionVectorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _EmissiveColorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _HeightMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _IridescenceMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _IridescenceThicknessMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 2800000, guid: 97a5684bc72c1704fadc965467f242ea, type: 3}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _NormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _NormalMapOS:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _SpecularColorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _SubsurfaceMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TangentMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TangentMapOS:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _ThicknessMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TransmissionMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TransmittanceColorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_Lightmaps:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_LightmapsInd:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_ShadowMasks:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _AORemapMax: 1
+ - _AORemapMin: 0
+ - _ATDistance: 1
+ - _AddPrecomputedVelocity: 0
+ - _AlbedoAffectEmissive: 0
+ - _AlphaCutoff: 0.5
+ - _AlphaCutoffEnable: 0
+ - _AlphaCutoffPostpass: 0.5
+ - _AlphaCutoffPrepass: 0.5
+ - _AlphaCutoffShadow: 0.5
+ - _AlphaDstBlend: 10
+ - _AlphaRemapMax: 1
+ - _AlphaRemapMin: 0
+ - _AlphaSrcBlend: 1
+ - _AlphaToMask: 0
+ - _AlphaToMaskInspectorValue: 0
+ - _Anisotropy: 0
+ - _BlendMode: 0
+ - _CoatMask: 0
+ - _CullMode: 2
+ - _CullModeForward: 2
+ - _Cutoff: 0.5
+ - _DepthOffsetEnable: 0
+ - _DetailAlbedoScale: 1
+ - _DetailNormalScale: 1
+ - _DetailSmoothnessScale: 1
+ - _DiffusionProfile: 0
+ - _DiffusionProfileHash: 0
+ - _DisplacementLockObjectScale: 1
+ - _DisplacementLockTilingScale: 1
+ - _DisplacementMode: 0
+ - _DistortionBlendMode: 0
+ - _DistortionBlurBlendMode: 0
+ - _DistortionBlurDstBlend: 1
+ - _DistortionBlurRemapMax: 1
+ - _DistortionBlurRemapMin: 0
+ - _DistortionBlurScale: 1
+ - _DistortionBlurSrcBlend: 1
+ - _DistortionDepthTest: 1
+ - _DistortionDstBlend: 1
+ - _DistortionEnable: 0
+ - _DistortionScale: 1
+ - _DistortionSrcBlend: 1
+ - _DistortionVectorBias: -1
+ - _DistortionVectorScale: 2
+ - _DoubleSidedEnable: 0
+ - _DoubleSidedGIMode: 0
+ - _DoubleSidedNormalMode: 1
+ - _DstBlend: 10
+ - _DstBlend2: 10
+ - _EmissiveColorMode: 1
+ - _EmissiveExposureWeight: 1
+ - _EmissiveIntensity: 1
+ - _EmissiveIntensityUnit: 0
+ - _EnableBlendModePreserveSpecularLighting: 1
+ - _EnableFogOnTransparent: 1
+ - _EnableGeometricSpecularAA: 0
+ - _EnergyConservingSpecularColor: 1
+ - _ForceForwardEmissive: 0
+ - _HdrpVersion: 2
+ - _HeightAmplitude: 0.02
+ - _HeightCenter: 0.5
+ - _HeightMapParametrization: 0
+ - _HeightMax: 1
+ - _HeightMin: -1
+ - _HeightOffset: 0
+ - _HeightPoMAmplitude: 2
+ - _HeightTessAmplitude: 2
+ - _HeightTessCenter: 0.5
+ - _InvTilingScale: 1
+ - _Ior: 1.5
+ - _IridescenceMask: 1
+ - _IridescenceThickness: 1
+ - _LinkDetailsWithBase: 1
+ - _MaterialID: 1
+ - _Metallic: 0
+ - _MetallicRemapMax: 0
+ - _MetallicRemapMin: 0
+ - _NormalMapSpace: 0
+ - _NormalScale: 1
+ - _ObjectSpaceUVMapping: 0
+ - _ObjectSpaceUVMappingEmissive: 0
+ - _OpaqueCullMode: 2
+ - _PPDLodThreshold: 5
+ - _PPDMaxSamples: 15
+ - _PPDMinSamples: 5
+ - _PPDPrimitiveLength: 1
+ - _PPDPrimitiveWidth: 1
+ - _PerPixelSorting: 0
+ - _RayTracing: 0
+ - _ReceivesSSR: 1
+ - _ReceivesSSRTransparent: 0
+ - _RefractionModel: 0
+ - _SSRefractionProjectionModel: 0
+ - _Smoothness: 0.5
+ - _SmoothnessRemapMax: 1
+ - _SmoothnessRemapMin: 0
+ - _SpecularAAScreenSpaceVariance: 0.1
+ - _SpecularAAThreshold: 0.2
+ - _SpecularOcclusionMode: 1
+ - _SrcBlend: 1
+ - _StencilRef: 0
+ - _StencilRefDepth: 0
+ - _StencilRefDistortionVec: 4
+ - _StencilRefGBuffer: 2
+ - _StencilRefMV: 32
+ - _StencilWriteMask: 6
+ - _StencilWriteMaskDepth: 9
+ - _StencilWriteMaskDistortionVec: 4
+ - _StencilWriteMaskGBuffer: 15
+ - _StencilWriteMaskMV: 41
+ - _SubsurfaceMask: 1
+ - _SupportDecals: 1
+ - _SurfaceType: 1
+ - _TexWorldScale: 1
+ - _TexWorldScaleEmissive: 1
+ - _Thickness: 1
+ - _TransmissionEnable: 1
+ - _TransmissionMask: 1
+ - _TransparentBackfaceEnable: 0
+ - _TransparentCullMode: 2
+ - _TransparentDepthPostpassEnable: 0
+ - _TransparentDepthPrepassEnable: 0
+ - _TransparentSortPriority: 0
+ - _TransparentWritingMotionVec: 0
+ - _TransparentZWrite: 0
+ - _UVBase: 0
+ - _UVDetail: 0
+ - _UVEmissive: 0
+ - _UseEmissiveIntensity: 0
+ - _UseShadowThreshold: 0
+ - _ZTestDepthEqualForOpaque: 4
+ - _ZTestGBuffer: 4
+ - _ZTestModeDistortion: 4
+ - _ZTestTransparent: 4
+ - _ZWrite: 0
+ m_Colors:
+ - _BaseColor: {r: 1, g: 1, b: 1, a: 1}
+ - _BaseColorMap_MipInfo: {r: 0, g: 0, b: 0, a: 0}
+ - _Color: {r: 1, g: 1, b: 1, a: 1}
+ - _DiffusionProfileAsset: {r: 0, g: 0, b: 0, a: 0}
+ - _DoubleSidedConstants: {r: 1, g: 1, b: -1, a: 0}
+ - _EmissionColor: {r: 1, g: 1, b: 1, a: 1}
+ - _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
+ - _EmissiveColorLDR: {r: 0, g: 0, b: 0, a: 1}
+ - _InvPrimScale: {r: 1, g: 1, b: 0, a: 0}
+ - _IridescenceThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
+ - _SpecularColor: {r: 1, g: 1, b: 1, a: 1}
+ - _ThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
+ - _TransmittanceColor: {r: 1, g: 1, b: 1, a: 1}
+ - _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
+ - _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}
+ - _UVMappingMaskEmissive: {r: 1, g: 0, b: 0, a: 0}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTransp.mat.meta b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTransp.mat.meta
new file mode 100644
index 00000000000..8ecbc45b89e
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTransp.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 8904c5ec87b77374aa2bb5befbfe2284
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTranspWritesDepth.mat b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTranspWritesDepth.mat
new file mode 100644
index 00000000000..f43d7e5e160
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTranspWritesDepth.mat
@@ -0,0 +1,310 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-5166128023983884676
+MonoBehaviour:
+ m_ObjectHideFlags: 11
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: da692e001514ec24dbc4cca1949ff7e8, type: 3}
+ m_Name:
+ m_EditorClassIdentifier:
+ version: 13
+ hdPluginSubTargetMaterialVersions:
+ m_Keys: []
+ m_Values:
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: SphereMaterialTranspWritesDepth
+ m_Shader: {fileID: 4800000, guid: 6e4ae4064600d784cac1e41a9e6f2e59, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords:
+ - _DISABLE_SSR_TRANSPARENT
+ - _ENABLE_FOG_ON_TRANSPARENT
+ - _NORMALMAP_TANGENT_SPACE
+ - _SURFACE_TYPE_TRANSPARENT
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: 3000
+ stringTagMap:
+ RenderType: Transparent
+ disabledShaderPasses:
+ - DistortionVectors
+ - MOTIONVECTORS
+ - ForwardEmissiveForDeferred
+ - TransparentDepthPrepass
+ - TransparentDepthPostpass
+ - TransparentBackface
+ - RayTracingPrepass
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _AnisotropyMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BaseColorMap:
+ m_Texture: {fileID: 2800000, guid: 97a5684bc72c1704fadc965467f242ea, type: 3}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BentNormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BentNormalMapOS:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _CoatMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DistortionVectorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _EmissiveColorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _HeightMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _IridescenceMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _IridescenceThicknessMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 2800000, guid: 97a5684bc72c1704fadc965467f242ea, type: 3}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _NormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _NormalMapOS:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _SpecularColorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _SubsurfaceMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TangentMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TangentMapOS:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _ThicknessMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TransmissionMaskMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TransmittanceColorMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_Lightmaps:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_LightmapsInd:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_ShadowMasks:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _AORemapMax: 1
+ - _AORemapMin: 0
+ - _ATDistance: 1
+ - _AddPrecomputedVelocity: 0
+ - _AlbedoAffectEmissive: 0
+ - _AlphaCutoff: 0.5
+ - _AlphaCutoffEnable: 0
+ - _AlphaCutoffPostpass: 0.5
+ - _AlphaCutoffPrepass: 0.5
+ - _AlphaCutoffShadow: 0.5
+ - _AlphaDstBlend: 10
+ - _AlphaRemapMax: 1
+ - _AlphaRemapMin: 0
+ - _AlphaSrcBlend: 1
+ - _AlphaToMask: 0
+ - _AlphaToMaskInspectorValue: 0
+ - _Anisotropy: 0
+ - _BlendMode: 0
+ - _CoatMask: 0
+ - _CullMode: 2
+ - _CullModeForward: 2
+ - _Cutoff: 0.5
+ - _DepthOffsetEnable: 0
+ - _DetailAlbedoScale: 1
+ - _DetailNormalScale: 1
+ - _DetailSmoothnessScale: 1
+ - _DiffusionProfile: 0
+ - _DiffusionProfileHash: 0
+ - _DisplacementLockObjectScale: 1
+ - _DisplacementLockTilingScale: 1
+ - _DisplacementMode: 0
+ - _DistortionBlendMode: 0
+ - _DistortionBlurBlendMode: 0
+ - _DistortionBlurDstBlend: 1
+ - _DistortionBlurRemapMax: 1
+ - _DistortionBlurRemapMin: 0
+ - _DistortionBlurScale: 1
+ - _DistortionBlurSrcBlend: 1
+ - _DistortionDepthTest: 1
+ - _DistortionDstBlend: 1
+ - _DistortionEnable: 0
+ - _DistortionScale: 1
+ - _DistortionSrcBlend: 1
+ - _DistortionVectorBias: -1
+ - _DistortionVectorScale: 2
+ - _DoubleSidedEnable: 0
+ - _DoubleSidedGIMode: 0
+ - _DoubleSidedNormalMode: 1
+ - _DstBlend: 10
+ - _DstBlend2: 10
+ - _EmissiveColorMode: 1
+ - _EmissiveExposureWeight: 1
+ - _EmissiveIntensity: 1
+ - _EmissiveIntensityUnit: 0
+ - _EnableBlendModePreserveSpecularLighting: 1
+ - _EnableFogOnTransparent: 1
+ - _EnableGeometricSpecularAA: 0
+ - _EnergyConservingSpecularColor: 1
+ - _ForceForwardEmissive: 0
+ - _HdrpVersion: 2
+ - _HeightAmplitude: 0.02
+ - _HeightCenter: 0.5
+ - _HeightMapParametrization: 0
+ - _HeightMax: 1
+ - _HeightMin: -1
+ - _HeightOffset: 0
+ - _HeightPoMAmplitude: 2
+ - _HeightTessAmplitude: 2
+ - _HeightTessCenter: 0.5
+ - _InvTilingScale: 1
+ - _Ior: 1.5
+ - _IridescenceMask: 1
+ - _IridescenceThickness: 1
+ - _LinkDetailsWithBase: 1
+ - _MaterialID: 1
+ - _Metallic: 0
+ - _MetallicRemapMax: 0
+ - _MetallicRemapMin: 0
+ - _NormalMapSpace: 0
+ - _NormalScale: 1
+ - _ObjectSpaceUVMapping: 0
+ - _ObjectSpaceUVMappingEmissive: 0
+ - _OpaqueCullMode: 2
+ - _PPDLodThreshold: 5
+ - _PPDMaxSamples: 15
+ - _PPDMinSamples: 5
+ - _PPDPrimitiveLength: 1
+ - _PPDPrimitiveWidth: 1
+ - _PerPixelSorting: 0
+ - _RayTracing: 0
+ - _ReceivesSSR: 1
+ - _ReceivesSSRTransparent: 0
+ - _RefractionModel: 0
+ - _SSRefractionProjectionModel: 0
+ - _Smoothness: 0.5
+ - _SmoothnessRemapMax: 1
+ - _SmoothnessRemapMin: 0
+ - _SpecularAAScreenSpaceVariance: 0.1
+ - _SpecularAAThreshold: 0.2
+ - _SpecularOcclusionMode: 1
+ - _SrcBlend: 1
+ - _StencilRef: 0
+ - _StencilRefDepth: 0
+ - _StencilRefDistortionVec: 4
+ - _StencilRefGBuffer: 2
+ - _StencilRefMV: 32
+ - _StencilWriteMask: 6
+ - _StencilWriteMaskDepth: 9
+ - _StencilWriteMaskDistortionVec: 4
+ - _StencilWriteMaskGBuffer: 15
+ - _StencilWriteMaskMV: 41
+ - _SubsurfaceMask: 1
+ - _SupportDecals: 1
+ - _SurfaceType: 1
+ - _TexWorldScale: 1
+ - _TexWorldScaleEmissive: 1
+ - _Thickness: 1
+ - _TransmissionEnable: 1
+ - _TransmissionMask: 1
+ - _TransparentBackfaceEnable: 0
+ - _TransparentCullMode: 2
+ - _TransparentDepthPostpassEnable: 0
+ - _TransparentDepthPrepassEnable: 0
+ - _TransparentSortPriority: 0
+ - _TransparentWritingMotionVec: 0
+ - _TransparentZWrite: 1
+ - _UVBase: 0
+ - _UVDetail: 0
+ - _UVEmissive: 0
+ - _UseEmissiveIntensity: 0
+ - _UseShadowThreshold: 0
+ - _ZTestDepthEqualForOpaque: 4
+ - _ZTestGBuffer: 4
+ - _ZTestModeDistortion: 4
+ - _ZTestTransparent: 4
+ - _ZWrite: 1
+ m_Colors:
+ - _BaseColor: {r: 1, g: 1, b: 1, a: 1}
+ - _BaseColorMap_MipInfo: {r: 0, g: 0, b: 0, a: 0}
+ - _Color: {r: 1, g: 1, b: 1, a: 1}
+ - _DiffusionProfileAsset: {r: 0, g: 0, b: 0, a: 0}
+ - _DoubleSidedConstants: {r: 1, g: 1, b: -1, a: 0}
+ - _EmissionColor: {r: 1, g: 1, b: 1, a: 1}
+ - _EmissiveColor: {r: 0, g: 0, b: 0, a: 1}
+ - _EmissiveColorLDR: {r: 0, g: 0, b: 0, a: 1}
+ - _InvPrimScale: {r: 1, g: 1, b: 0, a: 0}
+ - _IridescenceThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
+ - _SpecularColor: {r: 1, g: 1, b: 1, a: 1}
+ - _ThicknessRemap: {r: 0, g: 1, b: 0, a: 0}
+ - _TransmittanceColor: {r: 1, g: 1, b: 1, a: 1}
+ - _UVDetailsMappingMask: {r: 1, g: 0, b: 0, a: 0}
+ - _UVMappingMask: {r: 1, g: 0, b: 0, a: 0}
+ - _UVMappingMaskEmissive: {r: 1, g: 0, b: 0, a: 0}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTranspWritesDepth.mat.meta b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTranspWritesDepth.mat.meta
new file mode 100644
index 00000000000..73ca9c2b61c
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/SphereMaterialTranspWritesDepth.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: c0725431a233e9e4cb2ac21116a04505
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/Volume.asset b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/Volume.asset
new file mode 100644
index 00000000000..1a6fff7c7f7
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/Volume.asset
@@ -0,0 +1,15 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &11400000
+MonoBehaviour:
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: d7fd9488000d3734a9e00ee676215985, type: 3}
+ m_Name: Volume
+ m_EditorClassIdentifier: Unity.RenderPipelines.Core.Runtime::UnityEngine.Rendering.VolumeProfile
+ components: []
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/Volume.asset.meta b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/Volume.asset.meta
new file mode 100644
index 00000000000..f190104cf19
--- /dev/null
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha/Volume.asset.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 36b37cc0d34d87649b49143e55b76a95
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 11400000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Tests/PostProcessing.cs b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Tests/PostProcessing.cs
index c0977f2e6c3..f2436ec6ed1 100644
--- a/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Tests/PostProcessing.cs
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/GraphicTests/Tests/PostProcessing.cs
@@ -124,7 +124,7 @@ public PostProcessingTests(GpuResidentDrawerContext grdContext) : base(grdContex
RuntimePlatform.WindowsEditor
)]
[IgnoreGraphicsTest(
- "^(?!.*(4088_DRS-DLSS-Hardware|4089_DRS-DLSS-Software|4090_DRS-Hardware|4096_DRS-TAAU-Hardware|4100_DRS-STP-Hardware|4102_DRS-CAS-AfterPost|4103_DRS-DLSS-AfterPost|4104_DRS-STP-AfterPost|4106_DRS-TAAU-AfterPost|4107_DRS-FSR2-Hardware|4109_DRS-FSR2-AfterPost|4110_DRS-FSR2-With-CustomPass|4111_DRS-DLSS-With-CustomPass)).*",
+ "^(?!.*(4088_DRS-DLSS-Hardware|4089_DRS-DLSS-Software|4090_DRS-Hardware|4096_DRS-TAAU-Hardware|4100_DRS-STP-Hardware|4102_DRS-CAS-AfterPost|4103_DRS-DLSS-AfterPost|4104_DRS-STP-AfterPost|4106_DRS-TAAU-AfterPost|4107_DRS-FSR2-Hardware|4109_DRS-FSR2-AfterPost|4110_DRS-FSR2-With-CustomPass|4111_DRS-DLSS-With-CustomPass|4112_AlphaUpscaling-FP16Alpha)).*",
"Upscaler-only job ā non-upscaler tests excluded when ENABLE_UPSCALER_FRAMEWORK is defined",
UpscalerFrameworkContext.UpscalerFrameworkEnabled
)]
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Assets/HDRPDefaultResources/HDRenderPipelineGlobalSettings.asset b/Tests/SRPTests/Projects/HDRP_Tests/Assets/HDRPDefaultResources/HDRenderPipelineGlobalSettings.asset
index a57449a4c4b..8db86d542e5 100644
--- a/Tests/SRPTests/Projects/HDRP_Tests/Assets/HDRPDefaultResources/HDRenderPipelineGlobalSettings.asset
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Assets/HDRPDefaultResources/HDRenderPipelineGlobalSettings.asset
@@ -211,6 +211,7 @@ MonoBehaviour:
- rid: 1748197788746514448
- rid: 1748197788746514449
- rid: 6636147933899653120
+ - rid: 7830723193898795008
m_RuntimeSettings:
m_List: []
renderingLayerNames:
@@ -1192,3 +1193,7 @@ MonoBehaviour:
data:
m_Version: 1
m_EnableMaskAndCurrentWaterDecals: 1
+ - rid: 7830723193898795008
+ type: {class: AlphaUpscaler/RuntimeResources, ns: UnityEngine.Rendering, asm: Unity.RenderPipelines.Core.Runtime}
+ data:
+ m_AlphaUpscaleCS: {fileID: 7200000, guid: f10c23179af641eea368ee165b2e97cf, type: 3}
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/Packages/manifest.json b/Tests/SRPTests/Projects/HDRP_Tests/Packages/manifest.json
index ad0460ec806..44e85b25941 100644
--- a/Tests/SRPTests/Projects/HDRP_Tests/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/HDRP_Tests/Packages/manifest.json
@@ -10,7 +10,7 @@
"com.unity.render-pipelines.high-definition-config": "file:../../../../../Packages/com.unity.render-pipelines.high-definition-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.common-graphics": "file:../../../Packages/com.unity.testing.common-graphics",
"com.unity.testing.hdrp": "file:../../../Packages/com.unity.testing.hdrp",
"com.unity.testing.xr": "file:../../../Packages/com.unity.testing.xr",
diff --git a/Tests/SRPTests/Projects/HDRP_Tests/ProjectSettings/EditorBuildSettings.asset b/Tests/SRPTests/Projects/HDRP_Tests/ProjectSettings/EditorBuildSettings.asset
index 0bd9ea8bebb..b41af613246 100644
--- a/Tests/SRPTests/Projects/HDRP_Tests/ProjectSettings/EditorBuildSettings.asset
+++ b/Tests/SRPTests/Projects/HDRP_Tests/ProjectSettings/EditorBuildSettings.asset
@@ -755,6 +755,9 @@ EditorBuildSettings:
- enabled: 1
path: Assets/GraphicTests/Scenes/4x_PostProcessing/4109_DRS-FSR2-AfterPost.unity
guid: cbd1f7bf59ae04b46afbfcb1188b43b4
+ - enabled: 1
+ path: Assets/GraphicTests/Scenes/4x_PostProcessing/4112_AlphaUpscaling-FP16Alpha.unity
+ guid: 861fa82a1b434385a3bf6f3536540712
- enabled: 1
path: Assets/GraphicTests/Scenes/5x_SkyAndFog/5001_Fog_FogFallback.unity
guid: d04c39af67e5e18449a44f6a7778862f
diff --git a/Tests/SRPTests/Projects/MultipleSRP_Tests/Packages/manifest.json b/Tests/SRPTests/Projects/MultipleSRP_Tests/Packages/manifest.json
index 33db285f4bb..f0b91860ffb 100644
--- a/Tests/SRPTests/Projects/MultipleSRP_Tests/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/MultipleSRP_Tests/Packages/manifest.json
@@ -11,7 +11,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.timeline": "1.8.11",
"com.unity.ugui": "2.0.0",
"com.unity.visualeffectgraph": "file:../../../../../Packages/com.unity.visualeffectgraph",
diff --git a/Tests/SRPTests/Projects/SRP_SmokeTest/Packages/manifest.json b/Tests/SRPTests/Projects/SRP_SmokeTest/Packages/manifest.json
index edbcd4dd71f..a13a3bad7e5 100644
--- a/Tests/SRPTests/Projects/SRP_SmokeTest/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/SRP_SmokeTest/Packages/manifest.json
@@ -13,7 +13,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../../../Tests/SRPTests/Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../../../Tests/SRPTests/Packages/local.gtf.references",
"com.unity.testing.common-graphics": "file:../../../Packages/com.unity.testing.common-graphics",
"com.unity.visualeffectgraph": "file:../../../../../Packages/com.unity.visualeffectgraph",
"com.unity.modules.uielements": "1.0.0"
diff --git a/Tests/SRPTests/Projects/ShaderGraph/Packages/manifest.json b/Tests/SRPTests/Projects/ShaderGraph/Packages/manifest.json
index 3fb8b4b1124..982233ac520 100644
--- a/Tests/SRPTests/Projects/ShaderGraph/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/ShaderGraph/Packages/manifest.json
@@ -9,7 +9,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.graph-authoring": "file:../../../../../Packages/com.unity.graph-authoring",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testtools.codecoverage": "1.3.0",
"com.unity.ugui": "2.0.0",
"com.unity.visualeffectgraph": "file:../../../../../Packages/com.unity.visualeffectgraph",
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Editor/RenderSpriteBatchingFrameDebuggerTests.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Editor/RenderSpriteBatchingFrameDebuggerTests.cs
new file mode 100644
index 00000000000..f186521d5ee
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Editor/RenderSpriteBatchingFrameDebuggerTests.cs
@@ -0,0 +1,322 @@
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using UnityEditor;
+using UnityEditorInternal.FrameDebuggerInternal;
+using UnityEngine;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.Universal;
+
+// Captures Graphics.RenderSprite draws with the Frame Debugger to check how Sprites that share a
+// MaterialPropertyBlock are batched, and reads the rendered pixels back to check what each Sprite drew.
+[TestFixture]
+class RenderSpriteBatchingFrameDebuggerTests
+{
+ const string k_UnlitMaterialPath = "Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Unlit-Default.mat";
+ const string k_MainTex = "_MainTex";
+ const int k_TextureSize = 4;
+
+ static readonly string[] k_TextureNames = { "BatchingRed", "BatchingGreen", "BatchingBlue", "BatchingYellow" };
+ static readonly Color[] k_Colors = { Color.red, Color.green, Color.blue, Color.yellow };
+
+ struct CapturedDraw
+ {
+ public FrameEventType type;
+ public string mainTexName;
+ public int drawCallCount;
+ public int instanceCount;
+ public string breakCause;
+
+ public override string ToString()
+ {
+ return type + " _MainTex=" + mainTexName + " drawCalls=" + drawCallCount + " instances=" + instanceCount + " cause=" + breakCause;
+ }
+ }
+
+ GameObject m_CameraObject;
+ Camera m_Camera;
+ RenderTexture m_RenderTarget;
+ Material m_Material;
+ Texture2D[] m_Textures;
+ Sprite[] m_Sprites;
+ MaterialPropertyBlock m_Block;
+ SpriteMaskInteraction m_MaskInteraction;
+ bool m_PreviousSRPBatcherEnabled;
+
+ [SetUp]
+ public void Setup()
+ {
+ m_PreviousSRPBatcherEnabled = GraphicsSettings.useScriptableRenderPipelineBatching;
+ GraphicsSettings.useScriptableRenderPipelineBatching = true;
+
+ m_RenderTarget = new RenderTexture(256, 256, 24);
+ m_CameraObject = new GameObject("BatchingCamera");
+ m_Camera = m_CameraObject.AddComponent();
+ m_Camera.transform.position = new Vector3(0, 0, -10);
+ m_Camera.orthographic = true;
+ m_Camera.orthographicSize = 6;
+ m_Camera.allowHDR = false;
+ m_Camera.targetTexture = m_RenderTarget;
+ var cameraData = m_CameraObject.AddComponent();
+ cameraData.SetRenderer(2); // 2D Renderer. See the list of Renderers in CommonAssets/UniversalRPAsset.
+ cameraData.renderType = CameraRenderType.Base;
+ cameraData.renderPostProcessing = false;
+
+ m_Material = new Material(AssetDatabase.LoadAssetAtPath(k_UnlitMaterialPath));
+
+ m_Textures = new Texture2D[k_Colors.Length];
+ m_Sprites = new Sprite[k_Colors.Length];
+ for (int i = 0; i < k_Colors.Length; ++i)
+ {
+ m_Textures[i] = new Texture2D(k_TextureSize, k_TextureSize, TextureFormat.RGBA32, false) { name = k_TextureNames[i] };
+ m_Textures[i].SetPixels(Enumerable.Repeat(k_Colors[i], k_TextureSize * k_TextureSize).ToArray());
+ m_Textures[i].Apply();
+ m_Sprites[i] = Sprite.Create(m_Textures[i], new Rect(0, 0, k_TextureSize, k_TextureSize), new Vector2(0.5f, 0.5f), k_TextureSize);
+ }
+
+ RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
+ }
+
+ [TearDown]
+ public void Cleanup()
+ {
+ RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
+ FrameDebuggerUtility.SetEnabled(false, -1);
+
+ GraphicsSettings.useScriptableRenderPipelineBatching = m_PreviousSRPBatcherEnabled;
+
+ if (m_Sprites != null)
+ {
+ for (int i = 0; i < m_Sprites.Length; ++i)
+ {
+ UnityEngine.Object.DestroyImmediate(m_Sprites[i]);
+ UnityEngine.Object.DestroyImmediate(m_Textures[i]);
+ }
+ }
+
+ UnityEngine.Object.DestroyImmediate(m_Material);
+ UnityEngine.Object.DestroyImmediate(m_CameraObject);
+ if (m_RenderTarget != null)
+ {
+ m_RenderTarget.Release();
+ UnityEngine.Object.DestroyImmediate(m_RenderTarget);
+ }
+ }
+
+ void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
+ {
+ if (camera != m_Camera)
+ return;
+
+ var renderParams = new RenderParams(m_Material) { matProps = m_Block };
+ for (int i = 0; i < m_Sprites.Length; ++i)
+ {
+ var spriteParams = new SpriteParams(m_Sprites[i], Color.white, m_MaskInteraction);
+ var objectToWorld = Matrix4x4.Translate(new Vector3((i - 1.5f) * 2f, 0, 0));
+ Graphics.RenderSprite(renderParams, spriteParams, 0, objectToWorld);
+ }
+ }
+
+ static bool IsDrawEvent(FrameEventType type) =>
+ type == FrameEventType.Mesh ||
+ type == FrameEventType.DynamicBatch ||
+ type == FrameEventType.DynamicGeometry ||
+ type == FrameEventType.InstancedMesh ||
+ type == FrameEventType.SRPBatch;
+
+ void RenderUnderCapture()
+ {
+ FrameDebuggerUtility.EnterCapturingScope();
+ m_Camera.Render();
+ FrameDebuggerUtility.LeaveCapturingScope();
+ }
+
+ // Every draw event that uses the test material's shader, with the _MainTex it bound.
+ List CaptureSpriteDraws()
+ {
+ if (!FrameDebuggerUtility.locallySupported)
+ Assert.Ignore("Frame Debugger requires threaded rendering. Run with -force-gfx-mt.");
+
+ // Warm-up: newly created materials need one render to become SRP Batcher compatible.
+ m_Camera.Render();
+
+ FrameDebuggerUtility.SetEnabled(true, -1);
+ RenderUnderCapture();
+
+ FrameDebuggerEvent[] events = FrameDebuggerUtility.GetFrameEvents();
+ Assert.That(events, Is.Not.Null.And.Not.Empty, "No Frame Debugger events were captured.");
+
+ string[] breakCauses = FrameDebuggerUtility.GetBatchBreakCauseStrings();
+ string shaderName = m_Material.shader.name;
+ var draws = new List();
+ for (int index = 0; index < events.Length; ++index)
+ {
+ if (!IsDrawEvent(events[index].m_Type))
+ continue;
+
+ FrameDebuggerUtility.limit = index + 1;
+ RenderUnderCapture();
+
+ var data = new FrameDebuggerEventData();
+ FrameDebuggerUtility.GetFrameEventData(index, data);
+ if (data.m_RealShaderName != shaderName)
+ continue;
+
+ var draw = new CapturedDraw
+ {
+ type = events[index].m_Type,
+ drawCallCount = data.m_DrawCallCount,
+ instanceCount = data.m_InstanceCount,
+ breakCause = breakCauses[data.m_BatchBreakCause],
+ };
+ foreach (var texture in data.m_ShaderInfo.m_Textures)
+ {
+ if (texture.m_Name == k_MainTex)
+ draw.mainTexName = texture.m_TextureName;
+ }
+
+ draws.Add(draw);
+ }
+
+ // Otherwise an assertion that no draw has some type would pass on an empty capture.
+ Assert.That(draws, Is.Not.Empty, $"No draws of '{shaderName}' were captured among {events.Length} events.");
+ return draws;
+ }
+
+ // Control: without a block the four Sprites take the SRP Batcher path.
+ [Test]
+ public void RenderSprite_WithoutMaterialPropertyBlock_IsSRPBatched()
+ {
+ m_Block = null;
+ m_MaskInteraction = SpriteMaskInteraction.None;
+
+ var draws = CaptureSpriteDraws();
+
+ Assert.That(draws.Any(d => d.type == FrameEventType.SRPBatch), Is.True, "Expected the Sprites to be SRP batched:\n" + string.Join("\n", draws));
+ }
+
+ // A shared block gives every node custom props, which must keep the Sprites out of the SRP Batcher.
+ [Test]
+ public void RenderSprite_SharedMaterialPropertyBlock_IsNotSRPBatched(
+ [Values(SpriteMaskInteraction.None, SpriteMaskInteraction.VisibleOutsideMask)] SpriteMaskInteraction maskInteraction,
+ [Values] bool enableInstancing)
+ {
+ m_Block = new MaterialPropertyBlock();
+ m_Block.SetFloat("_BatchProbe", 1f);
+ m_MaskInteraction = maskInteraction;
+ m_Material.enableInstancing = enableInstancing;
+
+ var draws = CaptureSpriteDraws();
+
+ Assert.That(draws.Any(d => d.type == FrameEventType.SRPBatch), Is.False, "Sprites with a MaterialPropertyBlock were SRP batched:\n" + string.Join("\n", draws));
+ }
+
+ // One plain render, so nothing from an earlier render in the same frame is drawn again.
+ [Test]
+ public void RenderSprite_SharedMaterialPropertyBlock_DrawsEachSpriteWithItsOwnTexture(
+ [Values(SpriteMaskInteraction.None, SpriteMaskInteraction.VisibleOutsideMask)] SpriteMaskInteraction maskInteraction,
+ [Values] bool enableInstancing)
+ {
+ m_Block = new MaterialPropertyBlock();
+ m_Block.SetFloat("_BatchProbe", 1f);
+ m_MaskInteraction = maskInteraction;
+ m_Material.enableInstancing = enableInstancing;
+
+ Color[] cellColors = RenderAndReadCellColors();
+
+ string report = "Cell colours: " + string.Join(", ", cellColors);
+ for (int i = 0; i < k_Colors.Length; ++i)
+ Assert.That(IsApproximately(cellColors[i], k_Colors[i]), Is.True, $"Sprite {i} ({k_TextureNames[i]}) was drawn wrongly. " + report);
+ }
+
+ // Control: without a block, with or without the SRP Batcher.
+ [Test]
+ public void RenderSprite_WithoutMaterialPropertyBlock_DrawsEachSpriteWithItsOwnTexture(
+ [Values(SpriteMaskInteraction.None, SpriteMaskInteraction.VisibleOutsideMask)] SpriteMaskInteraction maskInteraction,
+ [Values] bool useSRPBatcher,
+ [Values] bool enableInstancing)
+ {
+ m_Block = null;
+ m_MaskInteraction = maskInteraction;
+ m_Material.enableInstancing = enableInstancing;
+ GraphicsSettings.useScriptableRenderPipelineBatching = useSRPBatcher;
+
+ Color[] cellColors = RenderAndReadCellColors();
+
+ string report = "Cell colours: " + string.Join(", ", cellColors);
+ for (int i = 0; i < k_Colors.Length; ++i)
+ Assert.That(IsApproximately(cellColors[i], k_Colors[i]), Is.True, $"Sprite {i} ({k_TextureNames[i]}) was drawn wrongly. " + report);
+ }
+
+ // Replaces the four Sprites with four cut from the colour quadrants of one atlas texture.
+ void UseAtlasSprites()
+ {
+ for (int i = 0; i < m_Sprites.Length; ++i)
+ {
+ UnityEngine.Object.DestroyImmediate(m_Sprites[i]);
+ UnityEngine.Object.DestroyImmediate(m_Textures[i]);
+ m_Textures[i] = null;
+ }
+
+ const int atlasSize = k_TextureSize * 2;
+ var atlas = new Texture2D(atlasSize, atlasSize, TextureFormat.RGBA32, false) { name = "BatchingAtlas", filterMode = FilterMode.Point };
+ for (int i = 0; i < k_Colors.Length; ++i)
+ {
+ int x = (i % 2) * k_TextureSize;
+ int y = (i / 2) * k_TextureSize;
+ atlas.SetPixels(x, y, k_TextureSize, k_TextureSize, Enumerable.Repeat(k_Colors[i], k_TextureSize * k_TextureSize).ToArray());
+ m_Sprites[i] = Sprite.Create(atlas, new Rect(x, y, k_TextureSize, k_TextureSize), new Vector2(0.5f, 0.5f), k_TextureSize);
+ }
+
+ atlas.Apply();
+ m_Textures[0] = atlas;
+ }
+
+ // The texture in the batching key must not stop Sprites that share an atlas from dynamic batching.
+ [Test]
+ public void RenderSprite_SharedMaterialPropertyBlockSameAtlas_IsDynamicBatched(
+ [Values(SpriteMaskInteraction.None, SpriteMaskInteraction.VisibleOutsideMask)] SpriteMaskInteraction maskInteraction)
+ {
+ UseAtlasSprites();
+ m_Block = new MaterialPropertyBlock();
+ m_Block.SetFloat("_BatchProbe", 1f);
+ m_MaskInteraction = maskInteraction;
+ m_Material.enableInstancing = false;
+
+ var draws = CaptureSpriteDraws();
+
+ // With graphics jobs the Frame Debugger can also record an empty draw event, which is not a batch.
+ int batchCount = draws.Count(d => d.drawCallCount > 0);
+ Assert.That(batchCount, Is.EqualTo(1), "Expected the atlas Sprites in one dynamic batch:\n" + string.Join("\n", draws));
+ }
+
+ static bool IsApproximately(Color actual, Color expected)
+ {
+ const float tolerance = 0.2f;
+ return Mathf.Abs(actual.r - expected.r) < tolerance && Mathf.Abs(actual.g - expected.g) < tolerance && Mathf.Abs(actual.b - expected.b) < tolerance;
+ }
+
+ // The colour at the centre of each Sprite.
+ Color[] RenderAndReadCellColors()
+ {
+ m_Camera.Render();
+
+ var previous = RenderTexture.active;
+ RenderTexture.active = m_RenderTarget;
+ var readback = new Texture2D(m_RenderTarget.width, m_RenderTarget.height, TextureFormat.RGBA32, false);
+ readback.ReadPixels(new Rect(0, 0, m_RenderTarget.width, m_RenderTarget.height), 0, 0);
+ readback.Apply();
+ RenderTexture.active = previous;
+
+ float worldToPixels = m_RenderTarget.height / (2f * m_Camera.orthographicSize);
+ var colors = new Color[k_Colors.Length];
+ for (int i = 0; i < k_Colors.Length; ++i)
+ {
+ int x = Mathf.RoundToInt(m_RenderTarget.width * 0.5f + (i - 1.5f) * 2f * worldToPixels);
+ colors[i] = readback.GetPixel(x, m_RenderTarget.height / 2);
+ }
+
+ UnityEngine.Object.DestroyImmediate(readback);
+ return colors;
+ }
+}
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Editor/RenderSpriteBatchingFrameDebuggerTests.cs.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Editor/RenderSpriteBatchingFrameDebuggerTests.cs.meta
new file mode 100644
index 00000000000..e47b462b99d
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Editor/RenderSpriteBatchingFrameDebuggerTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 71bc3d7cea6849e0af201cc15cf2ca05
\ No newline at end of file
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/Renderer2DBackbufferDepthTests.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/Renderer2DBackbufferDepthTests.cs
index 5ae66800b2d..eda62cb932e 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/Renderer2DBackbufferDepthTests.cs
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/Renderer2DBackbufferDepthTests.cs
@@ -8,9 +8,10 @@
using UnityEngine.TestTools;
// Verifies what the 2D renderer actually puts in the frame's resources when depth usage is disallowed: the
-// back buffer depth must not be imported, and the rest of the frame must still record without errors (the
-// overlay UI pass in particular reads UniversalResourceData.backBufferDepth and has to cope with it being
-// invalid).
+// back buffer depth is not imported, except on OpenGL when the 2D passes draw straight into a back buffer that
+// has one (there it stays bound with the back buffer color whether a pass asks for it or not, so it must be
+// cleared, see UUM-159093), and the rest of the frame must still record without errors (the overlay UI pass in
+// particular reads UniversalResourceData.backBufferDepth and has to cope with it being invalid).
//
// A back buffer with no depth/stencil is not something a test can arrange - it is decided when the surface is
// created - so the disallowed case is driven here through the renderer's own "Depth/Stencil Buffer" setting,
@@ -81,6 +82,7 @@ public void SetUp()
public void TearDown()
{
RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
+ m_ProbePass.requiresIntermediateTexture = false;
if (m_RendererData != null)
Renderer2DDepthUsageTests.SetUseDepthStencilBuffer(m_RendererData, m_PreviousUseDepthStencilBuffer);
@@ -110,13 +112,44 @@ public IEnumerator BackbufferDepthIsImportedWhenDepthUsageIsAllowed()
}
[UnityTest]
- public IEnumerator BackbufferDepthIsNotImportedWhenDepthUsageIsDisallowed()
+ public IEnumerator BackbufferDepthIsImportedOnlyOnOpenGLWhenDepthUsageIsDisallowed()
{
Renderer2DDepthUsageTests.SetUseDepthStencilBuffer(m_RendererData, false);
yield return RecordFrame();
+ IgnoreIfNotRenderingStraightToTheBackbuffer();
- Assert.IsFalse(m_ProbePass.backBufferDepthIsValid, "The 2D renderer imported the back buffer depth even though depth usage is disallowed.");
+ // On OpenGL the renderer setting must not drop the back buffer depth: left unimported it is never cleared,
+ // and draws into the back buffer test against undefined contents (UUM-159093). Elsewhere it is not imported.
+ Assert.AreEqual(BackbufferDepthStaysBound(), m_ProbePass.backBufferDepthIsValid,
+ "The imported back buffer depth did not match whether the graphics API keeps it bound with the back buffer color.");
+ }
+
+ [UnityTest]
+ public IEnumerator ActiveDepthIsBackbufferDepthOnlyOnOpenGLWhenDepthUsageIsDisallowed()
+ {
+ Renderer2DDepthUsageTests.SetUseDepthStencilBuffer(m_RendererData, false);
+
+ yield return RecordFrame();
+ IgnoreIfNotRenderingStraightToTheBackbuffer();
+
+ // The 2D passes attach the active depth, which is what gets the back buffer depth cleared on first use
+ Assert.AreEqual(BackbufferDepthStaysBound(), m_ProbePass.activeDepthIsBackBufferDepth,
+ "The active depth did not match the back buffer depth when rendering straight to the back buffer.");
+ }
+
+ [UnityTest]
+ public IEnumerator NoActiveDepthWithIntermediateColorWhenDepthUsageIsDisallowed()
+ {
+ Renderer2DDepthUsageTests.SetUseDepthStencilBuffer(m_RendererData, false);
+ m_ProbePass.requiresIntermediateTexture = true;
+
+ yield return RecordFrame();
+
+ // The intermediate color target must not be paired with the back buffer depth, and the back buffer depth is
+ // not imported at all since no 2D pass would attach it and get it cleared
+ Assert.IsFalse(m_ProbePass.activeDepthIsValid, "An active depth was set for the intermediate color target even though depth usage is disallowed.");
+ Assert.IsFalse(m_ProbePass.backBufferDepthIsValid, "The back buffer depth was imported with an intermediate color target even though depth usage is disallowed.");
}
[UnityTest]
@@ -130,6 +163,22 @@ public IEnumerator RenderingSucceedsWhenDepthUsageIsDisallowed()
yield return null;
}
+ // OpenGL binds the default framebuffer's depth with its color, so the renderer imports it to get it cleared.
+ static bool BackbufferDepthStaysBound()
+ {
+ var deviceType = SystemInfo.graphicsDeviceType;
+ bool isOpenGL = deviceType == GraphicsDeviceType.OpenGLES3 || deviceType == GraphicsDeviceType.OpenGLCore;
+ return isOpenGL && Graphics.backBufferHasDepthStencil;
+ }
+
+ // The OpenGL import only applies without an intermediate color target, which the setup cannot rule out everywhere
+ // (e.g. a non-sRGB back buffer in Linear color space needs one for the sRGB conversion)
+ void IgnoreIfNotRenderingStraightToTheBackbuffer()
+ {
+ if (BackbufferDepthStaysBound() && !m_ProbePass.activeColorIsBackBuffer)
+ Assert.Ignore("The 2D renderer created an intermediate color target, so it does not render straight to the back buffer.");
+ }
+
// Renders frames until the probe pass has recorded one with the current settings.
IEnumerator RecordFrame()
{
@@ -151,23 +200,28 @@ void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
}
// Reads the frame's back buffer depth handle at record time; it adds no render pass of its own.
- class BackbufferDepthProbePass : ScriptableRenderPass
+ class BackbufferDepthProbePass : ScriptableRenderPass2D
{
public bool recorded;
public bool backBufferDepthIsValid;
+ public bool activeDepthIsValid;
+ public bool activeDepthIsBackBufferDepth;
+ public bool activeColorIsBackBuffer;
public BackbufferDepthProbePass()
{
- // The 2D renderer maps any event up to BeforeRenderingTransparents onto
- // RenderPassEvent2D.BeforeRendering, which it records right after CreateResources - so the probe
- // sees the back buffer depth as CreateResources left it.
- renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
+ // The 2D renderer records BeforeRendering passes right after CreateResources, so the probe sees the
+ // back buffer depth as CreateResources left it.
+ renderPassEvent2D = RenderPassEvent2D.BeforeRendering;
}
public void Reset()
{
recorded = false;
backBufferDepthIsValid = false;
+ activeDepthIsValid = false;
+ activeDepthIsBackBufferDepth = false;
+ activeColorIsBackBuffer = false;
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
@@ -176,6 +230,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
recorded = true;
backBufferDepthIsValid = resourceData.backBufferDepth.IsValid();
+ activeDepthIsValid = resourceData.activeDepthTexture.IsValid();
+ activeDepthIsBackBufferDepth = activeDepthIsValid && resourceData.activeDepthTexture == resourceData.backBufferDepth;
+ activeColorIsBackBuffer = resourceData.isActiveTargetBackBuffer;
}
}
}
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Packages/manifest.json b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Packages/manifest.json
index d6322fc806a..b4a3909be9f 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Packages/manifest.json
@@ -15,7 +15,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.common-graphics": "file:../../../Packages/com.unity.testing.common-graphics",
"com.unity.testing.hdr-faking": "file:../../../Packages/com.unity.testing.hdr-faking",
"com.unity.testing.urp": "file:../../../Packages/com.unity.testing.urp",
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/ForwardRenderer_MainlightShadowOutput.asset b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/ForwardRenderer_MainlightShadowOutput.asset
index 218a266b159..dce03f6591e 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/ForwardRenderer_MainlightShadowOutput.asset
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/ForwardRenderer_MainlightShadowOutput.asset
@@ -82,3 +82,4 @@ MonoBehaviour:
m_EditorClassIdentifier:
m_Active: 1
m_TextureType: 0
+ m_DepthBandsShader: {fileID: 4800000, guid: f7ceb50ed8d774f3ca49b3ee8f6a3f09, type: 3}
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/OutputURPTexture.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/OutputURPTexture.cs
index de95f932fce..dd1d1168cad 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/OutputURPTexture.cs
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/OutputURPTexture.cs
@@ -1,9 +1,9 @@
+using System;
using UnityEngine;
using UnityEngine.Rendering;
-using UnityEngine.Rendering.Universal;
using UnityEngine.Rendering.RenderGraphModule;
using UnityEngine.Rendering.RenderGraphModule.Util;
-using System;
+using UnityEngine.Rendering.Universal;
public class OutputURPTexture : ScriptableRendererFeature
{
@@ -17,9 +17,12 @@ enum TextureType
class OutputURPTexturePass : ScriptableRenderPass
{
TextureType m_TextureType;
- public OutputURPTexturePass(TextureType textureType)
+ Material m_DepthBandsMaterial;
+
+ public OutputURPTexturePass(TextureType textureType, Material depthBandsMaterial)
{
m_TextureType = textureType;
+ m_DepthBandsMaterial = depthBandsMaterial;
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
@@ -38,18 +41,23 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
default:
throw new ArgumentException("Doesn't handle texture type please exstend function to include the type.", "m_TextureType");
}
- RenderGraphUtils.AddBlitPass(renderGraph, sourceTexture, resourceData.activeColorTexture, Vector2.one, Vector2.zero, passName: passName);
-
+
+ var blitParameters = new RenderGraphUtils.BlitMaterialParameters(sourceTexture, resourceData.activeColorTexture, m_DepthBandsMaterial, 0);
+ renderGraph.AddBlitPass(blitParameters, passName);
}
}
[SerializeField]
TextureType m_TextureType;
+ [SerializeField]
+ Shader m_DepthBandsShader;
+ Material m_DepthBandsMaterial;
OutputURPTexturePass m_ScriptablePass;
public override void Create()
{
- m_ScriptablePass = new OutputURPTexturePass(m_TextureType);
+ m_DepthBandsMaterial = CoreUtils.CreateEngineMaterial(m_DepthBandsShader);
+ m_ScriptablePass = new OutputURPTexturePass(m_TextureType, m_DepthBandsMaterial);
m_ScriptablePass.renderPassEvent = RenderPassEvent.AfterRenderingSkybox;
}
@@ -57,4 +65,9 @@ public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingD
{
renderer.EnqueuePass(m_ScriptablePass);
}
+
+ protected override void Dispose(bool disposing)
+ {
+ CoreUtils.Destroy(m_DepthBandsMaterial);
+ }
}
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/ShadowmapDepthBands.shader b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/ShadowmapDepthBands.shader
new file mode 100644
index 00000000000..90ac3988dac
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/ShadowmapDepthBands.shader
@@ -0,0 +1,73 @@
+// Shows a shadow map as grey depth bands, brighter where a caster is closer to the light.
+// It reads the map only through depth comparisons, as URP does when it samples shadows, so the
+// output does not depend on how a graphics API exposes depth texels as colour.
+Shader "Hidden/Test/ShadowmapDepthBands"
+{
+ SubShader
+ {
+ Tags { "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" }
+ ZWrite Off ZTest Always Blend Off Cull Off
+
+ Pass
+ {
+ Name "ShadowmapDepthBands"
+
+ HLSLPROGRAM
+ #pragma vertex Vert
+ #pragma fragment Frag
+
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
+
+ #define DEPTH_BAND_COUNT 16
+
+ TEXTURE2D_SHADOW(_BlitTexture);
+ SAMPLER_CMP(sampler_LinearClampCompare);
+ float4 _BlitScaleBias;
+
+ struct Attributes
+ {
+ uint vertexID : SV_VertexID;
+ };
+
+ struct Varyings
+ {
+ float4 positionCS : SV_POSITION;
+ float2 texcoord : TEXCOORD0;
+ };
+
+ Varyings Vert(Attributes input)
+ {
+ Varyings output;
+ output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
+ output.texcoord = GetFullScreenTriangleTexCoord(input.vertexID) * _BlitScaleBias.xy + _BlitScaleBias.zw;
+ return output;
+ }
+
+ float4 Frag(Varyings input) : SV_Target
+ {
+ float occludedBands = 0.0;
+
+ [unroll]
+ for (int band = 0; band < DEPTH_BAND_COUNT; ++band)
+ {
+ // Distance from the light as a fraction of the shadow depth range, at the far edge of each band.
+ // The last one stops just short of the far plane, where empty texels are stored.
+ float distanceFromLight = min((band + 1.0) / DEPTH_BAND_COUNT, 0.9999);
+ #if UNITY_REVERSED_Z
+ float referenceDepth = 1.0 - distanceFromLight;
+ #else
+ float referenceDepth = distanceFromLight;
+ #endif
+
+ // The comparison returns 1 when nothing in the shadow map is closer to the light than the reference
+ float lit = SAMPLE_TEXTURE2D_SHADOW(_BlitTexture, sampler_LinearClampCompare, float3(input.texcoord, referenceDepth));
+ occludedBands += 1.0 - lit;
+ }
+
+ float brightness = occludedBands / DEPTH_BAND_COUNT;
+ return float4(brightness, brightness, brightness, 1.0);
+ }
+ ENDHLSL
+ }
+ }
+}
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/ShadowmapDepthBands.shader.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/ShadowmapDepthBands.shader.meta
new file mode 100644
index 00000000000..11dfd388b65
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull/ShadowmapDepthBands.shader.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: f7ceb50ed8d774f3ca49b3ee8f6a3f09
+ShaderImporter:
+ externalObjects: {}
+ defaultTextures: []
+ nonModifiableTextures: []
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_false.unity b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_false.unity
index 4b852aae1bd..d0ba4d61cc0 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_false.unity
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_false.unity
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:9238d92d3541409001b71d34533d05edf92c7438e7dfc0a440d2bed63211aa76
-size 20839
+oid sha256:30567e4b027bf8113558dd4ae04b73239a56a3183773e516b6a57589a0aac2c5
+size 20831
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_noCascades_false.unity b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_noCascades_false.unity
index 43dba755fa1..238009fff85 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_noCascades_false.unity
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_noCascades_false.unity
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:3a5388c2d45de586bf0b873cd163c06186f6f82b4ec59026497d8be3e987cb52
-size 20839
+oid sha256:d664d3a39fc32cbcf892eb47786266c2d6f008c15ed3f5e393de76d505feff05
+size 20832
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_noCascades_true.unity b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_noCascades_true.unity
index 92ea4eb70f9..dcc6da8cfd3 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_noCascades_true.unity
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_noCascades_true.unity
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:fdca9cb67acb9464c7acb33034cb4dc239b5c550e3cbeae1331697b50dd60119
-size 20839
+oid sha256:026b4ff77bcc5d1a8bead5c5ed02858a6fc09fa988b476c51732c54af568fe7c
+size 20832
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_true.unity b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_true.unity
index efda71b3971..74b8697b3c5 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_true.unity
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/301_useViewFrustumForShadowCasterCull_true.unity
@@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
-oid sha256:9f27ad48cbe3517f0616fc3fb8fc43ee47769f487d5541326694cf7be741912f
-size 20839
+oid sha256:28eb58485bf1c637eb8da9f286b2607341ce17cf650d2367c67c24f8d6f83652
+size 20831
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Test/Editor/BatchRendererGroupFilteredPickingTests.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Test/Editor/BatchRendererGroupFilteredPickingTests.cs
new file mode 100644
index 00000000000..dc376208bfc
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Test/Editor/BatchRendererGroupFilteredPickingTests.cs
@@ -0,0 +1,188 @@
+using System;
+using System.Collections;
+using NUnit.Framework;
+using Unity.Collections;
+using Unity.Collections.LowLevel.Unsafe;
+using Unity.Jobs;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.Rendering;
+using UnityEngine.TestTools;
+using Object = UnityEngine.Object;
+
+unsafe class BatchRendererGroupFilteredPickingTests
+{
+ const int k_InstanceCount = 2;
+ const int k_WarmUpFrameCount = 10;
+ const int k_SizeOfPackedMatrix = 48;
+ const int k_ObjectToWorldByteOffset = 96;
+ const int k_WorldToObjectByteOffset = k_ObjectToWorldByteOffset + k_InstanceCount * k_SizeOfPackedMatrix;
+ const int k_InstanceDataByteSize = k_WorldToObjectByteOffset + k_InstanceCount * k_SizeOfPackedMatrix;
+
+ static readonly Vector3 k_FrontAndBackOverlap = new Vector3(-0.125f, 0f, 0f);
+ static readonly Vector3 k_BackOnly = new Vector3(0.5f, 0f, 0f);
+
+ struct PackedMatrix
+ {
+ public float c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11;
+
+ public PackedMatrix(Matrix4x4 m)
+ {
+ c0 = m.m00; c1 = m.m10; c2 = m.m20;
+ c3 = m.m01; c4 = m.m11; c5 = m.m21;
+ c6 = m.m02; c7 = m.m12; c8 = m.m22;
+ c9 = m.m03; c10 = m.m13; c11 = m.m23;
+ }
+ }
+
+ SceneView m_SceneView;
+ bool m_PreviousAllowAsyncCompilation;
+
+ GameObject m_Front;
+ GameObject m_Back;
+
+ BatchRendererGroup m_BatchRendererGroup;
+ GraphicsBuffer m_InstanceData;
+ Material m_Material;
+ Material m_PickingMaterial;
+ BatchID m_BatchID;
+ BatchMeshID m_MeshID;
+ BatchMaterialID m_MaterialID;
+
+ [SetUp]
+ public void SetUp()
+ {
+ m_PreviousAllowAsyncCompilation = ShaderUtil.allowAsyncCompilation;
+ ShaderUtil.allowAsyncCompilation = false;
+
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+
+ m_Front = new GameObject("Front");
+ m_Front.transform.position = new Vector3(-0.5f, 0f, 0f);
+ m_Back = new GameObject("Back");
+ m_Back.transform.position = new Vector3(0.25f, 0f, 2f);
+
+ m_Material = new Material(Shader.Find("Universal Render Pipeline/Unlit"));
+ m_PickingMaterial = new Material(Shader.Find("Hidden/Universal Render Pipeline/BRGPicking"));
+
+ m_BatchRendererGroup = new BatchRendererGroup(OnPerformCulling, IntPtr.Zero);
+ m_BatchRendererGroup.SetEnabledViewTypes(new[] { BatchCullingViewType.Camera, BatchCullingViewType.Picking });
+ m_BatchRendererGroup.SetPickingMaterial(m_PickingMaterial);
+ m_MeshID = m_BatchRendererGroup.RegisterMesh(Resources.GetBuiltinResource("Cube.fbx"));
+ m_MaterialID = m_BatchRendererGroup.RegisterMaterial(m_Material);
+
+ m_InstanceData = new GraphicsBuffer(GraphicsBuffer.Target.Raw, k_InstanceDataByteSize / sizeof(int), sizeof(int));
+ m_InstanceData.SetData(new[] { Matrix4x4.zero }, 0, 0, 1);
+ var objectToWorld = new[] { new PackedMatrix(m_Front.transform.localToWorldMatrix), new PackedMatrix(m_Back.transform.localToWorldMatrix) };
+ var worldToObject = new[] { new PackedMatrix(m_Front.transform.worldToLocalMatrix), new PackedMatrix(m_Back.transform.worldToLocalMatrix) };
+ m_InstanceData.SetData(objectToWorld, 0, k_ObjectToWorldByteOffset / k_SizeOfPackedMatrix, k_InstanceCount);
+ m_InstanceData.SetData(worldToObject, 0, k_WorldToObjectByteOffset / k_SizeOfPackedMatrix, k_InstanceCount);
+
+ var metadata = new NativeArray(2, Allocator.Temp);
+ metadata[0] = new MetadataValue { NameID = Shader.PropertyToID("unity_ObjectToWorld"), Value = 0x80000000 | k_ObjectToWorldByteOffset };
+ metadata[1] = new MetadataValue { NameID = Shader.PropertyToID("unity_WorldToObject"), Value = 0x80000000 | k_WorldToObjectByteOffset };
+ m_BatchID = m_BatchRendererGroup.AddBatch(metadata, m_InstanceData.bufferHandle);
+ metadata.Dispose();
+
+ m_SceneView = EditorWindow.CreateWindow();
+ m_SceneView.position = new Rect(EditorGUIUtility.GetMainWindowPosition().position, new Vector2(512, 512));
+ m_SceneView.Focus();
+ }
+
+ [TearDown]
+ public void TearDown()
+ {
+ m_SceneView.Close();
+ m_SceneView = null;
+
+ m_BatchRendererGroup.Dispose();
+ m_InstanceData.Dispose();
+ Object.DestroyImmediate(m_PickingMaterial);
+ Object.DestroyImmediate(m_Material);
+
+ ShaderUtil.allowAsyncCompilation = m_PreviousAllowAsyncCompilation;
+ }
+
+ JobHandle OnPerformCulling(BatchRendererGroup rendererGroup, BatchCullingContext cullingContext, BatchCullingOutput cullingOutput, IntPtr userContext)
+ {
+ int alignment = UnsafeUtility.AlignOf();
+ var output = (BatchCullingOutputDrawCommands*)cullingOutput.drawCommands.GetUnsafePtr();
+
+ output->drawCommands = (BatchDrawCommand*)UnsafeUtility.Malloc(UnsafeUtility.SizeOf() * k_InstanceCount, alignment, Allocator.TempJob);
+ output->drawRanges = (BatchDrawRange*)UnsafeUtility.Malloc(UnsafeUtility.SizeOf(), alignment, Allocator.TempJob);
+ output->visibleInstances = (int*)UnsafeUtility.Malloc(sizeof(int) * k_InstanceCount, alignment, Allocator.TempJob);
+ output->drawCommandPickingEntityIds = null;
+ output->instanceSortingPositions = null;
+ output->instanceSortingPositionFloatCount = 0;
+ output->drawCommandCount = k_InstanceCount;
+ output->drawRangeCount = 1;
+ output->visibleInstanceCount = k_InstanceCount;
+
+ for (int i = 0; i < k_InstanceCount; ++i)
+ {
+ output->visibleInstances[i] = i;
+ output->drawCommands[i] = new BatchDrawCommand
+ {
+ visibleOffset = (uint)i,
+ visibleCount = 1,
+ batchID = m_BatchID,
+ materialID = m_MaterialID,
+ meshID = m_MeshID,
+ submeshIndex = 0,
+ splitVisibilityMask = 0xff,
+ flags = BatchDrawCommandFlags.None,
+ sortingPosition = 0
+ };
+ }
+
+ output->drawRanges[0] = new BatchDrawRange
+ {
+ drawCommandsBegin = 0,
+ drawCommandsCount = k_InstanceCount,
+ filterSettings = new BatchFilterSettings { renderingLayerMask = 0xffffffff }
+ };
+
+ if (cullingContext.viewType == BatchCullingViewType.Picking)
+ {
+ output->drawCommandPickingEntityIds = (EntityId*)UnsafeUtility.Malloc(UnsafeUtility.SizeOf() * k_InstanceCount, alignment, Allocator.TempJob);
+ output->drawCommandPickingEntityIds[0] = m_Front.GetEntityId();
+ output->drawCommandPickingEntityIds[1] = m_Back.GetEntityId();
+ }
+
+ return default;
+ }
+
+ GameObject Pick(Vector3 worldPosition, GameObject[] filter)
+ {
+ GameObject picked = null;
+
+ Action pick = null;
+ pick = _ =>
+ {
+ picked = HandleUtility.PickGameObject(HandleUtility.WorldToGUIPoint(worldPosition), false, null, filter);
+ SceneView.duringSceneGui -= pick;
+ };
+ SceneView.duringSceneGui += pick;
+ m_SceneView.SendEvent(EditorGUIUtility.CommandEvent("TestEvent"));
+
+ return picked;
+ }
+
+ [UnityTest]
+ public IEnumerator PickGameObject_WithFilter_OnlyPicksFilteredBatchRendererGroupDraws()
+ {
+ m_SceneView.LookAt(Vector3.zero, Quaternion.LookRotation(Vector3.forward, Vector3.up), 2f, true, true);
+
+ for (int i = 0; i < k_WarmUpFrameCount && Pick(k_FrontAndBackOverlap, null) != m_Front; ++i)
+ {
+ m_SceneView.RepaintImmediately();
+ yield return null;
+ }
+
+ Assert.AreEqual(m_Front, Pick(k_FrontAndBackOverlap, null), "Unfiltered pick didn't return the front BatchRendererGroup object");
+ Assert.AreEqual(m_Front, Pick(k_FrontAndBackOverlap, new[] { m_Front }), "Filtered pick didn't return the filtered BatchRendererGroup object");
+ Assert.AreEqual(m_Back, Pick(k_FrontAndBackOverlap, new[] { m_Back }), "Excluded BatchRendererGroup object occluded the filtered one");
+ Assert.IsNull(Pick(k_BackOnly, new[] { m_Front }), "Excluded BatchRendererGroup object was picked");
+ }
+}
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Test/Editor/BatchRendererGroupFilteredPickingTests.cs.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Test/Editor/BatchRendererGroupFilteredPickingTests.cs.meta
new file mode 100644
index 00000000000..8698ba80f74
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Test/Editor/BatchRendererGroupFilteredPickingTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 8717b72790a64019b326c1d93e31311b
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Test/Editor/Unity.Testing.SRP.Universal.Foundation.Editor.asmdef b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Test/Editor/Unity.Testing.SRP.Universal.Foundation.Editor.asmdef
index 3d33a7d8dfa..f620d88866a 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Test/Editor/Unity.Testing.SRP.Universal.Foundation.Editor.asmdef
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Test/Editor/Unity.Testing.SRP.Universal.Foundation.Editor.asmdef
@@ -21,7 +21,7 @@
"Editor"
],
"excludePlatforms": [],
- "allowUnsafeCode": false,
+ "allowUnsafeCode": true,
"overrideReferences": true,
"precompiledReferences": [
"nunit.framework.dll"
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Packages/manifest.json b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Packages/manifest.json
index f2014e649f0..bb6675184ba 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Packages/manifest.json
@@ -14,7 +14,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.common-graphics": "file:../../../Packages/com.unity.testing.common-graphics",
"com.unity.testing.urp": "file:../../../Packages/com.unity.testing.urp",
"com.unity.testing.xr": "file:../../../Packages/com.unity.testing.xr",
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Lighting/Packages/manifest.json b/Tests/SRPTests/Projects/UniversalGraphicsTest_Lighting/Packages/manifest.json
index ab8ef8af0dc..99c06feb7b2 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Lighting/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Lighting/Packages/manifest.json
@@ -14,7 +14,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.urp": "file:../../../Packages/com.unity.testing.urp",
"com.unity.testing.common-graphics": "file:../../../Packages/com.unity.testing.common-graphics",
"com.unity.testing.xr": "file:../../../Packages/com.unity.testing.xr",
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/CommonAssets/ForwardRenderer.asset b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/CommonAssets/ForwardRenderer.asset
index 9f38699a3bf..8816ce8ce6c 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/CommonAssets/ForwardRenderer.asset
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/CommonAssets/ForwardRenderer.asset
@@ -188,7 +188,8 @@ MonoBehaviour:
- {fileID: -3335404936333121951}
- {fileID: -6013470097145452660}
- {fileID: -3626063803437354403}
- m_RendererFeatureMap: a53e77578376031beeb81c22f96decc1b449cb42e29eab32e724dd8896132ae9aa54f039e62662935813bc18adacf219a61d2aa0fd28d0fe61a6c7d3e142b6d18c2736b0cedc8bac5df236b72ea2adcd
+ - {fileID: 2833333333333333333}
+ m_RendererFeatureMap: a53e77578376031beeb81c22f96decc1b449cb42e29eab32e724dd8896132ae9aa54f039e62662935813bc18adacf219a61d2aa0fd28d0fe61a6c7d3e142b6d18c2736b0cedc8bac5df236b72ea2adcd55559bafa7055227
m_UseNativeRenderPass: 0
postProcessData: {fileID: 11400000, guid: 41439944d30ece34e96484bdb6645b55, type: 2}
xrSystemData: {fileID: 11400000, guid: 60e1133243b97e347b653163a8c01b64, type: 2}
@@ -294,9 +295,29 @@ MonoBehaviour:
passIndex: 0
bindDepthStencilAttachment: 0
m_Version: 1
+--- !u!114 &2833333333333333333
+MonoBehaviour:
+ m_ObjectHideFlags: 1
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: b00045f12942b46c698459096c89274e, type: 3}
+ m_Name: 283DisplayAlpha
+ m_EditorClassIdentifier:
+ m_Active: 0
+ injectionPoint: 600
+ fetchColorBuffer: 1
+ requirements: 0
+ passMaterial: {fileID: 2100000, guid: 0bc87505314942309c92f5f08614e5ad, type: 2}
+ passIndex: 0
+ bindDepthStencilAttachment: 0
+ m_Version: 1
--- !u!114 &3651186617534335412
MonoBehaviour:
- m_ObjectHideFlags: 0
+ m_ObjectHideFlags: 1
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/CommonAssets/URPAssets/URP_Asset_UpScaling_STP_Alpha_NoHDR.asset b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/CommonAssets/URPAssets/URP_Asset_UpScaling_STP_Alpha_NoHDR.asset
new file mode 100644
index 00000000000..0ccb329b5b6
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/CommonAssets/URPAssets/URP_Asset_UpScaling_STP_Alpha_NoHDR.asset
@@ -0,0 +1,192 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-8662253974725994463
+MonoBehaviour:
+ m_ObjectHideFlags: 1
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: 03be459180a06974d8583254adb17471, type: 3}
+ m_Name: STPOptions
+ m_EditorClassIdentifier: Unity.RenderPipelines.Core.Runtime::STPOptions
+ m_UpscalerName: Spatial-Temporal Post-Processing
+ m_InjectionPoint: 0
+ m_ResolutionMode: 0
+ m_EnableReactiveMaskPass: 0
+ m_ReactiveMaskUseComponentMax: 0
+ m_ReactiveMaskScale: 1
+ m_ApplyReactiveMaskThreshold: 0
+ m_ReactiveMaskThreshold: 0.2
+ m_ReactiveMaskBinaryValue: 1
+--- !u!114 &11400000
+MonoBehaviour:
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: bf2edee5c58d82540a51f03df9d42094, type: 3}
+ m_Name: URP_Asset_UpScaling_STP_Alpha_NoHDR
+ m_EditorClassIdentifier:
+ k_AssetVersion: 13
+ k_AssetPreviousVersion: 13
+ m_RendererType: 1
+ m_RendererData: {fileID: 0}
+ m_RendererDataList:
+ - {fileID: 11400000, guid: f59607d3476b54858a594ea904187fb5, type: 2}
+ m_DefaultRendererIndex: 0
+ m_RequireDepthTexture: 1
+ m_RequireOpaqueTexture: 1
+ m_OpaqueDownsampling: 1
+ m_SupportsTerrainHoles: 0
+ m_SupportsHDR: 0
+ m_HDRColorBufferPrecision: 0
+ m_MSAA: 1
+ m_RenderScale: 0.5
+ m_UpscalingFilter: 4
+ m_SelectedUpscalerName: Spatial-Temporal Post-Processing
+ m_UpscalerOptions:
+ - {fileID: -8662253974725994463}
+ - {fileID: 3746925265284549404}
+ m_FsrOverrideSharpness: 0
+ m_FsrSharpness: 0.92
+ m_EnableLODCrossFade: 0
+ m_LODCrossFadeDitheringType: 1
+ m_ShEvalMode: 0
+ m_LightProbeSystem: 0
+ m_ProbeVolumeMemoryBudget: 1024
+ m_ProbeVolumeBlendingMemoryBudget: 128
+ m_SupportProbeVolumeGPUStreaming: 0
+ m_SupportProbeVolumeDiskStreaming: 0
+ m_SupportProbeVolumeScenarios: 0
+ m_SupportProbeVolumeScenarioBlending: 0
+ m_ProbeVolumeSHBands: 1
+ m_MainLightRenderingMode: 1
+ m_MainLightShadowsSupported: 0
+ m_MainLightShadowmapResolution: 2048
+ m_AdditionalLightsRenderingMode: 0
+ m_AdditionalLightsPerObjectLimit: 8
+ m_AdditionalLightShadowsSupported: 0
+ m_AdditionalLightsShadowmapResolution: 512
+ m_AdditionalLightsShadowResolutionTierLow: 128
+ m_AdditionalLightsShadowResolutionTierMedium: 256
+ m_AdditionalLightsShadowResolutionTierHigh: 512
+ m_ReflectionProbeBlending: 0
+ m_ReflectionProbeBoxProjection: 0
+ m_ReflectionProbeAtlas: 0
+ m_ShadowDistance: 56
+ m_ShadowCascadeCount: 4
+ m_Cascade2Split: 0.25
+ m_Cascade3Split: {x: 0.154, y: 0.478}
+ m_Cascade4Split: {x: 0.067, y: 0.2, z: 0.467}
+ m_CascadeBorder: 0.1
+ m_ShadowDepthBias: 1
+ m_ShadowNormalBias: 1
+ m_AnyShadowsSupported: 1
+ m_SoftShadowsSupported: 1
+ m_ConservativeEnclosingSphere: 0
+ m_NumIterationsEnclosingSphere: 64
+ m_SoftShadowQuality: 2
+ m_AdditionalLightsCookieResolution: 2048
+ m_AdditionalLightsCookieFormat: 3
+ m_UseSRPBatcher: 1
+ m_SupportsDynamicBatching: 0
+ m_MixedLightingSupported: 0
+ m_SupportsLightCookies: 0
+ m_SupportsLightLayers: 0
+ m_StoreActionsOptimization: 0
+ m_UseAdaptivePerformance: 1
+ m_ColorGradingMode: 0
+ m_ColorGradingLutSize: 32
+ m_AllowPostProcessAlphaOutput: 1
+ m_UseFastSRGBLinearConversion: 0
+ m_SupportDataDrivenLensFlare: 1
+ m_SupportScreenSpaceLensFlare: 1
+ m_GPUResidentDrawerMode: 0
+ m_SmallMeshScreenPercentage: 0
+ m_ShadowSmallMeshScreenPercentages: {x: 0, y: 0, z: 0, w: 0}
+ m_GPUResidentDrawerEnableOcclusionCullingInCameras: 0
+ m_ShadowType: 0
+ m_LocalShadowsSupported: 1
+ m_LocalShadowsAtlasResolution: 512
+ m_MaxPixelLights: 4
+ m_ShadowAtlasResolution: 2048
+ m_VolumeFrameworkUpdateMode: 0
+ m_VolumeProfile: {fileID: 0}
+ apvScenesData:
+ obsoleteSceneBounds:
+ m_Keys: []
+ m_Values: []
+ obsoleteHasProbeVolumes:
+ m_Keys: []
+ m_Values:
+ m_PrefilteringModeMainLightShadows: 2
+ m_PrefilteringModeAdditionalLight: 0
+ m_PrefilteringModeAdditionalLightShadows: 1
+ m_PrefilterXRKeywords: 1
+ m_PrefilteringModeForwardPlus: 0
+ m_PrefilteringModeDeferredRendering: 1
+ m_PrefilteringModeScreenSpaceOcclusion: 0
+ m_PrefilteringModeScreenSpaceReflection: 1
+ m_PrefilterWriteSmoothness: 1
+ m_PrefilterDebugKeywords: 1
+ m_PrefilterWriteRenderingLayers: 1
+ m_PrefilterHDROutput: 1
+ m_PrefilterAlphaOutput: 0
+ m_PrefilterSSAODepthNormals: 1
+ m_PrefilterSSAOSourceDepthLow: 1
+ m_PrefilterSSAOSourceDepthMedium: 1
+ m_PrefilterSSAOSourceDepthHigh: 1
+ m_PrefilterSSAOInterleaved: 1
+ m_PrefilterSSAOBlueNoise: 1
+ m_PrefilterSSAOSampleCountLow: 1
+ m_PrefilterSSAOSampleCountMedium: 1
+ m_PrefilterSSAOSampleCountHigh: 1
+ m_PrefilterDBufferMRT1: 1
+ m_PrefilterDBufferMRT2: 1
+ m_PrefilterDBufferMRT3: 1
+ m_PrefilterSoftShadowsQualityLow: 0
+ m_PrefilterSoftShadowsQualityMedium: 0
+ m_PrefilterSoftShadowsQualityHigh: 0
+ m_PrefilterSoftShadows: 0
+ m_PrefilterScreenCoord: 0
+ m_PrefilterScreenSpaceIrradiance: 0
+ m_PrefilterNativeRenderPass: 1
+ m_PrefilterUseLegacyLightmaps: 0
+ m_PrefilterBicubicLightmapSampling: 0
+ m_PrefilterReflectionProbeRotation: 0
+ m_PrefilterReflectionProbeBlending: 0
+ m_PrefilterReflectionProbeBoxProjection: 0
+ m_PrefilterReflectionProbeAtlas: 0
+ m_PrefilterPointSamplingUpsampling: 0
+ m_PrefilterExposure: 0
+ m_Light2DPrefilteringMode: 0
+ m_Light2DKeptVariantCombos: []
+ m_ShaderVariantLogLevel: 0
+ m_ShadowCascades: 3
+ m_Textures:
+ blueNoise64LTex: {fileID: 2800000, guid: e3d24661c1e055f45a7560c033dbb837, type: 3}
+ bayerMatrixTex: {fileID: 2800000, guid: f9ee4ed84c1d10c49aabb9b210b0fc44, type: 3}
+--- !u!114 &3746925265284549404
+MonoBehaviour:
+ m_ObjectHideFlags: 1
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: 1b516656c1bb6634192a33e967e54491, type: 3}
+ m_Name: FSR2Options
+ m_EditorClassIdentifier: Unity.RenderPipelines.Core.Runtime::FSR2Options
+ m_UpscalerName: FidelityFX Super Resolution 2
+ m_InjectionPoint: 0
+ m_ResolutionMode: 0
+ m_FSR2QualityMode: 0
+ m_EnableSharpening: 0
+ m_Sharpness: 0.92
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/CommonAssets/URPAssets/URP_Asset_UpScaling_STP_Alpha_NoHDR.asset.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/CommonAssets/URPAssets/URP_Asset_UpScaling_STP_Alpha_NoHDR.asset.meta
new file mode 100644
index 00000000000..fe08efaa958
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/CommonAssets/URPAssets/URP_Asset_UpScaling_STP_Alpha_NoHDR.asset.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 7ad10d5bd7127ec46900338a5b6cd5c5
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 0
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaOutput_RGBA8_RenderScale_Up_STP.unity b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaOutput_RGBA8_RenderScale_Up_STP.unity
new file mode 100644
index 00000000000..318c09c12d0
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaOutput_RGBA8_RenderScale_Up_STP.unity
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:eba2264fbe69ecec8c3de4a09a74449bfc8c180e22c346c03715e858a8792003
+size 19973
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaOutput_RGBA8_RenderScale_Up_STP.unity.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaOutput_RGBA8_RenderScale_Up_STP.unity.meta
new file mode 100644
index 00000000000..ab031ba182e
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaOutput_RGBA8_RenderScale_Up_STP.unity.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: be536423526b4dd4aa210e86c248ac80
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling.meta
new file mode 100644
index 00000000000..922209241ee
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: a6e6150900025b7419a0d71e7159943f
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.mat b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.mat
new file mode 100644
index 00000000000..700a98ea46c
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.mat
@@ -0,0 +1,29 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: 283_DisplayAlpha
+ m_Shader: {fileID: 4800000, guid: 267738cafd8c497ba7512f69d36bd77a, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords: []
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: -1
+ stringTagMap: {}
+ disabledShaderPasses: []
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs: []
+ m_Ints: []
+ m_Floats: []
+ m_Colors: []
+ m_BuildTextureStacks: []
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.mat.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.mat.meta
new file mode 100644
index 00000000000..ae707f44706
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 0bc87505314942309c92f5f08614e5ad
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.shader b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.shader
new file mode 100644
index 00000000000..8f2ab2a513e
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.shader
@@ -0,0 +1,36 @@
+Shader "Hidden/Test/283_DisplayAlpha"
+{
+ SubShader
+ {
+ Tags
+ {
+ "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline"
+ }
+ LOD 100
+
+ Pass
+ {
+ Name "DisplayAlpha"
+ ZTest Always
+ ZWrite Off
+ Cull Off
+
+ HLSLPROGRAM
+ #pragma vertex Vert
+ #pragma fragment Fragment
+
+ #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
+ #include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blit.hlsl"
+
+ // Visualizes the alpha channel of the camera color as grayscale, so the graphics
+ // test compares the upscaled alpha instead of the composited color.
+ half4 Fragment(Varyings input) : SV_Target
+ {
+ UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
+ half alpha = SAMPLE_TEXTURE2D_X(_BlitTexture, sampler_PointClamp, input.texcoord.xy).a;
+ return half4(alpha.xxx, 1);
+ }
+ ENDHLSL
+ }
+ }
+}
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.shader.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.shader.meta
new file mode 100644
index 00000000000..5097d523505
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/283_DisplayAlpha.shader.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 267738cafd8c497ba7512f69d36bd77a
+ShaderImporter:
+ externalObjects: {}
+ defaultTextures: []
+ nonModifiableTextures: []
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatDiscardGreen.mat b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatDiscardGreen.mat
new file mode 100644
index 00000000000..525133c4c8a
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatDiscardGreen.mat
@@ -0,0 +1,147 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-2240418698902554757
+MonoBehaviour:
+ m_ObjectHideFlags: 11
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
+ m_Name:
+ m_EditorClassIdentifier:
+ version: 11
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: MatDiscardGreen
+ m_Shader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords:
+ - _ALPHATEST_ON
+ - _SURFACE_TYPE_TRANSPARENT
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: 3000
+ stringTagMap:
+ RenderType: Transparent
+ disabledShaderPasses:
+ - MOTIONVECTORS
+ - DepthOnly
+ - SHADOWCASTER
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _BaseMap:
+ m_Texture: {fileID: 2800000, guid: b2cde6ec2e345ab44bf0fc256c819fad, type: 3}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BumpMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailAlbedoMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailMask:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailNormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _EmissionMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 2800000, guid: b2cde6ec2e345ab44bf0fc256c819fad, type: 3}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MetallicGlossMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _OcclusionMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _ParallaxMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _SpecGlossMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_Lightmaps:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_LightmapsInd:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_ShadowMasks:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _AddPrecomputedVelocity: 0
+ - _AlphaClip: 1
+ - _AlphaToMask: 0
+ - _Blend: 0
+ - _BlendModePreserveSpecular: 0
+ - _BumpScale: 1
+ - _ClearCoatMask: 0
+ - _ClearCoatSmoothness: 0
+ - _Cull: 2
+ - _Cutoff: 0.5
+ - _DetailAlbedoMapScale: 1
+ - _DetailNormalMapScale: 1
+ - _DstBlend: 10
+ - _DstBlendAlpha: 10
+ - _EnvironmentReflections: 1
+ - _GlossMapScale: 0
+ - _Glossiness: 0
+ - _GlossinessSource: 0
+ - _GlossyReflections: 0
+ - _Metallic: 0
+ - _OcclusionStrength: 1
+ - _Parallax: 0.005
+ - _QueueOffset: 0
+ - _ReceiveShadows: 1
+ - _ScreenSpaceReflections: 1
+ - _ScreenSpaceReflectionsContributeTransparent: 1
+ - _Shininess: 0
+ - _Smoothness: 0.685
+ - _SmoothnessSource: 0
+ - _SmoothnessTextureChannel: 1
+ - _SpecSource: 0
+ - _SpecularHighlights: 1
+ - _SrcBlend: 5
+ - _SrcBlendAlpha: 1
+ - _Surface: 1
+ - _WorkflowMode: 1
+ - _XRMotionVectorsPass: 1
+ - _ZWrite: 0
+ m_Colors:
+ - _BaseColor: {r: 0, g: 1, b: 0, a: 1}
+ - _Color: {r: 0, g: 1, b: 0, a: 1}
+ - _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
+ - _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatDiscardGreen.mat.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatDiscardGreen.mat.meta
new file mode 100644
index 00000000000..69da709e752
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatDiscardGreen.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 2d86341ffbb979f4a867545bc32ecec6
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatOpaqueRed.mat b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatOpaqueRed.mat
new file mode 100644
index 00000000000..edc607eda09
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatOpaqueRed.mat
@@ -0,0 +1,136 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-3963434338821335712
+MonoBehaviour:
+ m_ObjectHideFlags: 11
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
+ m_Name:
+ m_EditorClassIdentifier:
+ version: 11
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: MatOpaqueRed
+ m_Shader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords: []
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: -1
+ stringTagMap:
+ RenderType: Opaque
+ disabledShaderPasses:
+ - MOTIONVECTORS
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _BaseMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BumpMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailAlbedoMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailMask:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailNormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _EmissionMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MetallicGlossMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _OcclusionMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _ParallaxMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _SpecGlossMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_Lightmaps:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_LightmapsInd:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_ShadowMasks:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _AddPrecomputedVelocity: 0
+ - _AlphaClip: 0
+ - _AlphaToMask: 0
+ - _Blend: 0
+ - _BlendModePreserveSpecular: 1
+ - _BumpScale: 1
+ - _ClearCoatMask: 0
+ - _ClearCoatSmoothness: 0
+ - _Cull: 2
+ - _Cutoff: 0.5
+ - _DetailAlbedoMapScale: 1
+ - _DetailNormalMapScale: 1
+ - _DstBlend: 0
+ - _DstBlendAlpha: 0
+ - _EnvironmentReflections: 1
+ - _GlossMapScale: 0
+ - _Glossiness: 0
+ - _GlossyReflections: 0
+ - _Metallic: 0
+ - _OcclusionStrength: 1
+ - _Parallax: 0.005
+ - _QueueOffset: 0
+ - _ReceiveShadows: 1
+ - _Smoothness: 0.5
+ - _SmoothnessTextureChannel: 0
+ - _SpecularHighlights: 1
+ - _SrcBlend: 1
+ - _SrcBlendAlpha: 1
+ - _Surface: 0
+ - _WorkflowMode: 1
+ - _ZWrite: 1
+ m_Colors:
+ - _BaseColor: {r: 1, g: 0, b: 0, a: 1}
+ - _Color: {r: 1, g: 0, b: 0, a: 1}
+ - _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
+ - _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatOpaqueRed.mat.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatOpaqueRed.mat.meta
new file mode 100644
index 00000000000..11feac4e2b6
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatOpaqueRed.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: c5508f84bea0f274f9ba8af7072ec6ae
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatTransparentBlue.mat b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatTransparentBlue.mat
new file mode 100644
index 00000000000..a1dc5996e76
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatTransparentBlue.mat
@@ -0,0 +1,140 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-1414899553356948808
+MonoBehaviour:
+ m_ObjectHideFlags: 11
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
+ m_Name:
+ m_EditorClassIdentifier:
+ version: 11
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: MatTransparentBlue
+ m_Shader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords:
+ - _ALPHAPREMULTIPLY_ON
+ - _SURFACE_TYPE_TRANSPARENT
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: 3000
+ stringTagMap:
+ RenderType: Transparent
+ disabledShaderPasses:
+ - MOTIONVECTORS
+ - DepthOnly
+ - SHADOWCASTER
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _BaseMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BumpMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailAlbedoMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailMask:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailNormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _EmissionMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MetallicGlossMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _OcclusionMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _ParallaxMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _SpecGlossMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_Lightmaps:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_LightmapsInd:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_ShadowMasks:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _AddPrecomputedVelocity: 0
+ - _AlphaClip: 0
+ - _AlphaToMask: 0
+ - _Blend: 0
+ - _BlendModePreserveSpecular: 1
+ - _BumpScale: 1
+ - _ClearCoatMask: 0
+ - _ClearCoatSmoothness: 0
+ - _Cull: 2
+ - _Cutoff: 0.5
+ - _DetailAlbedoMapScale: 1
+ - _DetailNormalMapScale: 1
+ - _DstBlend: 10
+ - _DstBlendAlpha: 10
+ - _EnvironmentReflections: 1
+ - _GlossMapScale: 0
+ - _Glossiness: 0
+ - _GlossyReflections: 0
+ - _Metallic: 0
+ - _OcclusionStrength: 1
+ - _Parallax: 0.005
+ - _QueueOffset: 0
+ - _ReceiveShadows: 1
+ - _Smoothness: 0.5
+ - _SmoothnessTextureChannel: 0
+ - _SpecularHighlights: 1
+ - _SrcBlend: 1
+ - _SrcBlendAlpha: 1
+ - _Surface: 1
+ - _WorkflowMode: 1
+ - _ZWrite: 0
+ m_Colors:
+ - _BaseColor: {r: 0, g: 0, b: 1, a: 0.37254903}
+ - _Color: {r: 0, g: 0, b: 1, a: 0.37254903}
+ - _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
+ - _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatTransparentBlue.mat.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatTransparentBlue.mat.meta
new file mode 100644
index 00000000000..31baefd1593
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/MatTransparentBlue.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: af310f5e2b32bc44c8e1cea42b9d97f4
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/checkerboard_alpha0.png b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/checkerboard_alpha0.png
new file mode 100644
index 00000000000..613002df862
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/checkerboard_alpha0.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a52ce7723cc34779583eefe56e5d4fd97460f6934ea23b8f5fbe06fcac9a7935
+size 335
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/checkerboard_alpha0.png.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/checkerboard_alpha0.png.meta
new file mode 100644
index 00000000000..31fe78eeada
--- /dev/null
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/283_AlphaUpscaling/checkerboard_alpha0.png.meta
@@ -0,0 +1,154 @@
+fileFormatVersion: 2
+guid: b2cde6ec2e345ab44bf0fc256c819fad
+TextureImporter:
+ internalIDToNameTable: []
+ externalObjects: {}
+ serializedVersion: 13
+ mipmaps:
+ mipMapMode: 0
+ enableMipMap: 0
+ sRGBTexture: 1
+ linearTexture: 0
+ fadeOut: 0
+ borderMipMap: 0
+ mipMapsPreserveCoverage: 0
+ alphaTestReferenceValue: 0.5
+ mipMapFadeDistanceStart: 1
+ mipMapFadeDistanceEnd: 3
+ bumpmap:
+ convertToNormalMap: 0
+ externalNormalMap: 0
+ heightScale: 0.25
+ normalMapFilter: 0
+ flipGreenChannel: 0
+ isReadable: 0
+ streamingMipmaps: 0
+ streamingMipmapsPriority: 0
+ vTOnly: 0
+ ignoreMipmapLimit: 0
+ grayScaleToAlpha: 0
+ generateCubemap: 6
+ cubemapConvolution: 0
+ seamlessCubemap: 0
+ textureFormat: 1
+ maxTextureSize: 2048
+ textureSettings:
+ serializedVersion: 2
+ filterMode: 1
+ aniso: 1
+ mipBias: 0
+ wrapU: 0
+ wrapV: 0
+ wrapW: 0
+ nPOTScale: 1
+ lightmap: 0
+ compressionQuality: 50
+ spriteMode: 0
+ spriteExtrude: 1
+ spriteMeshType: 1
+ alignment: 0
+ spritePivot: {x: 0.5, y: 0.5}
+ spritePixelsToUnits: 100
+ spriteBorder: {x: 0, y: 0, z: 0, w: 0}
+ spriteGenerateFallbackPhysicsShape: 1
+ alphaUsage: 1
+ alphaIsTransparency: 0
+ spriteTessellationDetail: -1
+ textureType: 0
+ textureShape: 1
+ singleChannelComponent: 0
+ flipbookRows: 1
+ flipbookColumns: 1
+ maxTextureSizeSet: 0
+ compressionQualitySet: 0
+ textureFormatSet: 0
+ ignorePngGamma: 0
+ applyGammaDecoding: 0
+ swizzle: 50462976
+ cookieLightType: 0
+ platformSettings:
+ - serializedVersion: 4
+ buildTarget: DefaultTexturePlatform
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 0
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: Android
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: iOS
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: OSXUniversal
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: Standalone
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ spriteSheet:
+ serializedVersion: 2
+ sprites: []
+ outline: []
+ customData:
+ physicsShape: []
+ bones: []
+ spriteID:
+ internalID: 0
+ vertices: []
+ indices:
+ edges: []
+ weights: []
+ secondaryTextures: []
+ nameFileIdTable: {}
+ mipmapLimitGroupName:
+ pSDRemoveMatte: 0
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Packages/manifest.json b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Packages/manifest.json
index b218ccb4e92..9c24c1388e1 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Packages/manifest.json
@@ -14,7 +14,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.common-graphics": "file:../../../Packages/com.unity.testing.common-graphics",
"com.unity.testing.hdr-faking": "file:../../../Packages/com.unity.testing.hdr-faking",
"com.unity.testing.urp": "file:../../../Packages/com.unity.testing.urp",
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/ProjectSettings/EditorBuildSettings.asset b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/ProjectSettings/EditorBuildSettings.asset
index 1f6c5e28c20..bf6e21e1fd0 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/ProjectSettings/EditorBuildSettings.asset
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/ProjectSettings/EditorBuildSettings.asset
@@ -221,6 +221,9 @@ EditorBuildSettings:
- enabled: 1
path: Assets/Scenes/282_AlphaOutput_RGBA8_Stack_RenderScale_Up_FSR.unity
guid: 33738bb1cfc644b2882c51fa88268a4f
+ - enabled: 1
+ path: Assets/Scenes/283_AlphaOutput_RGBA8_RenderScale_Up_STP.unity
+ guid: febbdb38e483470cb3c6b69d4d9704dc
- enabled: 1
path: Assets/Scenes/373_HDROutput_ColorGamut.unity
guid: cef44dde9c315e54fa9e5cfe6a04edbb
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/ProjectSettings/QualitySettings.asset b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/ProjectSettings/QualitySettings.asset
index f392b10c1ec..15bf0e9a247 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/ProjectSettings/QualitySettings.asset
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/ProjectSettings/QualitySettings.asset
@@ -960,6 +960,59 @@ QualitySettings:
terrainFadeLength: 5
terrainMaxTrees: 50
excludedTargetPlatforms: []
+ - serializedVersion: 5
+ name: 18-URP_Asset_UpScaling_STP_Alpha_NoHDR
+ pixelLightCount: 4
+ shadows: 2
+ shadowResolution: 2
+ shadowProjection: 1
+ shadowCascades: 4
+ shadowDistance: 150
+ shadowNearPlaneOffset: 3
+ shadowCascade2Split: 0.33333334
+ shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667}
+ shadowmaskMode: 1
+ skinWeights: 4
+ globalTextureMipmapLimit: 0
+ textureMipmapLimitSettings: []
+ anisotropicTextures: 2
+ antiAliasing: 0
+ softParticles: 1
+ softVegetation: 1
+ realtimeReflectionProbes: 1
+ billboardsFaceCameraPosition: 1
+ useLegacyDetailDistribution: 1
+ adaptiveVsync: 0
+ vSyncCount: 1
+ realtimeGICPUUsage: 25
+ adaptiveVsyncExtraA: 0
+ adaptiveVsyncExtraB: 0
+ lodBias: 2
+ meshLodThreshold: 1
+ maximumLODLevel: 0
+ enableLODCrossFade: 0
+ streamingMipmapsActive: 0
+ streamingMipmapsAddAllCameras: 1
+ streamingMipmapsMemoryBudget: 512
+ streamingMipmapsRenderersPerFrame: 512
+ streamingMipmapsMaxLevelReduction: 2
+ streamingMipmapsMaxFileIORequests: 1024
+ particleRaycastBudget: 4096
+ asyncUploadTimeSlice: 2
+ asyncUploadBufferSize: 4
+ asyncUploadPersistentBuffer: 1
+ resolutionScalingFixedDPIFactor: 1
+ customRenderPipeline: {fileID: 11400000, guid: 7ad10d5bd7127ec46900338a5b6cd5c5, type: 2}
+ terrainQualityOverrides: 0
+ terrainPixelError: 1
+ terrainDetailDensityScale: 1
+ terrainBasemapDistance: 1000
+ terrainDetailDistance: 80
+ terrainTreeDistance: 5000
+ terrainBillboardStart: 50
+ terrainFadeLength: 5
+ terrainMaxTrees: 50
+ excludedTargetPlatforms: []
m_TextureMipmapLimitGroupNames: []
m_PerPlatformDefaultQuality:
Android: 0
diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Terrain/Packages/manifest.json b/Tests/SRPTests/Projects/UniversalGraphicsTest_Terrain/Packages/manifest.json
index b0e4eb02b1d..4dc7ca1cce3 100644
--- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Terrain/Packages/manifest.json
+++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Terrain/Packages/manifest.json
@@ -14,7 +14,7 @@
"com.unity.render-pipelines.universal-config": "file:../../../../../Packages/com.unity.render-pipelines.universal-config",
"com.unity.shadergraph": "file:../../../../../Packages/com.unity.shadergraph",
"com.unity.test-framework": "file:../../../../../Packages/com.unity.test-framework",
- "com.unity.testframework.graphics": "file:../../../Packages/com.unity.test-framework.graphics",
+ "local.gtf.references": "file:../../../Packages/local.gtf.references",
"com.unity.testing.urp": "file:../../../Packages/com.unity.testing.urp",
"com.unity.testing.common-graphics": "file:../../../Packages/com.unity.testing.common-graphics",
"com.unity.testing.xr": "file:../../../Packages/com.unity.testing.xr",
diff --git a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/HLSLParserTest.cs b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/HLSLParserTest.cs
index c45c22f3fa1..6b348706a1f 100644
--- a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/HLSLParserTest.cs
+++ b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/HLSLParserTest.cs
@@ -500,6 +500,58 @@ public void HLSL_Many_Comments_HLSL_File()
Assert.AreEqual("TotalTime", parameters[5].name);
Assert.AreEqual(HLSLAccess.IN, parameters[5].access);
}
+
+ [TestCase("\n")]
+ [TestCase("\r\n")]
+ [TestCase(" ")]
+ [TestCase("\t")]
+ [TestCase("\n\n\n")]
+ [TestCase(" \n\t\n")]
+ [Test, Description("Covers issue UUM-158603")]
+ public void HLSL_Check_Leading_Whitespace(string leadingWhitespace)
+ {
+ // Arrange
+ string hlslCode = leadingWhitespace +
+ "float FloatFunction(in float value)\n" +
+ "{\n" +
+ " return value;\n" +
+ "}\n";
+
+ // Act
+ HLSLFunction function = HLSLFunction.Parse(this.attributesManager, hlslCode).Single();
+
+ // Assert
+ Assert.AreEqual("FloatFunction", function.name);
+ Assert.AreEqual(0, function.index);
+ Assert.AreEqual("{\n return value;\n}", function.body);
+ }
+
+ [Test, Description("Covers issue UUM-158603")]
+ public void HLSL_Check_Leading_Whitespace_Multiple_Functions()
+ {
+ // Arrange
+ string hlslCode =
+ "\n\n" +
+ "float First(in float value)\n" +
+ "{\n" +
+ " return value;\n" +
+ "}\n" +
+ "\n" +
+ "float Second(in float value)\n" +
+ "{\n" +
+ " return value * 2;\n" +
+ "}\n";
+
+ // Act
+ HLSLFunction[] functions = HLSLFunction.Parse(this.attributesManager, hlslCode).ToArray();
+
+ // Assert
+ Assert.AreEqual(2, functions.Length);
+ Assert.AreEqual(0, functions[0].index);
+ Assert.AreEqual(51, functions[1].index);
+ Assert.AreEqual("{\n return value;\n}", functions[0].body);
+ Assert.AreEqual("{\n return value * 2;\n}", functions[1].body);
+ }
}
}
#endif
diff --git a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXAttributeTests.cs b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXAttributeTests.cs
index 67532fde81e..00800883c27 100644
--- a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXAttributeTests.cs
+++ b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXAttributeTests.cs
@@ -247,6 +247,18 @@ public void Sanitize_Custom_Attribute_With_Same_Name_As_BuiltIn()
Assert.AreEqual("Seed_1", getAttributeOp.attribute);
}
+ [TestCase("_heat", ExpectedResult = "_heat_1")]
+ [TestCase("heat_", ExpectedResult = "heat__1")]
+ public string DuplicateCustomAttribute_WithUnderscoreAtEnd_KeepsUnderscore(string name)
+ {
+ VFXGraph graph = VFXTestCommon.MakeTemporaryGraph();
+ Assert.IsTrue(graph.TryAddCustomAttribute(name, VFXValueType.Float, string.Empty, false, out _));
+
+ VFXAttribute copy = graph.DuplicateCustomAttribute(name);
+
+ return copy.name;
+ }
+
private string CheckCustomAttributeName(string name) where T : VFXModel
{
var graph = VFXTestCommon.MakeTemporaryGraph();
diff --git a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXBlackboardTests.cs b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXBlackboardTests.cs
index 4e7e639ce57..caa46e99d62 100644
--- a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXBlackboardTests.cs
+++ b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXBlackboardTests.cs
@@ -176,10 +176,43 @@ public IEnumerator Duplicate_Category_And_Rename()
yield return null;
// Assert
- cat = blackboard.Query().Where(x => x.title == categoryName + " 1").First();
+ cat = blackboard.Query().Where(x => x.title == categoryName + " (1)").First();
Assert.NotNull(cat);
}
+ [UnityTest]
+ public IEnumerator Duplicate_Category_With_Long_Parameter_Name_Keeps_Name_Length_Limit()
+ {
+ // Arrange
+ BoardPreferenceHelper.SetVisible(BoardPreferenceHelper.Board.blackboard, true);
+ string categoryName = "new category";
+ VFXGraph graph = VFXTestCommon.MakeTemporaryGraph();
+ VFXViewWindow window = VFXTestCommon.GetWindow(graph, true);
+ window.LoadResource(graph.visualEffectResource);
+ VFXBlackboard blackboard = window.graphView.blackboard;
+ yield return null;
+
+ blackboard.Update();
+ blackboard.AddCategory(categoryName);
+ yield return null;
+
+ VFXViewController viewController = window.graphView.controller;
+ VFXParameter parameter = viewController.AddVFXParameter(Vector2.zero, VFXLibrary.GetParameters().First(d => d.modelType == typeof(float)).variant);
+ viewController.ApplyChanges();
+ var longName = new string('a', VFXParameterController.kMaxExposedNameLength);
+ parameter.SetSettingValue("m_ExposedName", longName);
+ parameter.category = categoryName;
+ yield return null;
+
+ // Act
+ blackboard.DuplicateCategory(categoryName);
+ yield return null;
+
+ // Assert
+ VFXParameterController copy = viewController.parameterControllers.Single(x => x.model != parameter);
+ Assert.AreEqual(new string('a', VFXParameterController.kMaxExposedNameLength - 4) + " (1)", copy.exposedName);
+ }
+
[UnityTest]
public IEnumerator Add_Custom_Attribute()
{
@@ -552,14 +585,14 @@ public IEnumerator Rename_Parameter_With_Existing_Name_Gets_Unique_Name()
yield return null;
// Assert
- Assert.AreEqual($"{existingName} 1", parameterFields[1].controller.exposedName);
+ Assert.AreEqual($"{existingName} (1)", parameterFields[1].controller.exposedName);
// Renaming again to the same existing name must give the same suffix, not alternate between 1 and 2
for (var i = 0; i < 3; i++)
{
parameterFields[1].controller.exposedName = existingName;
yield return null;
- Assert.AreEqual($"{existingName} 1", parameterFields[1].controller.exposedName);
+ Assert.AreEqual($"{existingName} (1)", parameterFields[1].controller.exposedName);
}
}
diff --git a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXControllerTests.cs b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXControllerTests.cs
index dd3a68c0ef2..07e53b08ea6 100644
--- a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXControllerTests.cs
+++ b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXControllerTests.cs
@@ -2213,6 +2213,265 @@ public void MakeNameUnique_WithConflict_AndZeroMaxLength_DoesNotThrow()
Assert.AreNotEqual("Speed", uniqueName);
Assert.IsFalse(existingNames.Contains(uniqueName));
}
+
+ [TestCase("New Vector 3", ExpectedResult = "New Vector 3 (1)")]
+ [TestCase("X (1)", ExpectedResult = "X (2)")]
+ [TestCase("Speed 2", ExpectedResult = "Speed 2 (1)")]
+ [TestCase("SPEED 2", ExpectedResult = "SPEED 2 (1)")]
+ [TestCase("X (-1)", ExpectedResult = "X (-1) (1)")]
+ [TestCase("X ( 1)", ExpectedResult = "X ( 1) (1)")]
+ public string MakeNameUnique_WithSpaces_OnlyReadsParenthesizedCounter(string name)
+ {
+ var existingNames = new HashSet(StringComparer.OrdinalIgnoreCase) { "New Vector 3", "X (1)", "Speed 2", "X (-1)", "X ( 1)" };
+
+ return VFXParameterController.MakeNameUnique(name, existingNames, true, VFXParameterController.kMaxExposedNameLength, null);
+ }
+
+ [Test]
+ public void MakeNameUnique_WithConflictAtMaxLength_CutsNameToFitCounter()
+ {
+ var name = new string('a', VFXParameterController.kMaxExposedNameLength);
+ var existingNames = new HashSet(StringComparer.OrdinalIgnoreCase) { name };
+
+ string uniqueName = VFXParameterController.MakeNameUnique(name, existingNames, true, VFXParameterController.kMaxExposedNameLength, null);
+
+ Assert.AreEqual(new string('a', VFXParameterController.kMaxExposedNameLength - 4) + " (1)", uniqueName);
+ }
+
+ [TestCase("Seed", ExpectedResult = "Seed_1")]
+ [TestCase("Speed_1", ExpectedResult = "Speed_2")]
+ public string MakeNameUnique_WithoutSpaces_AppendsUnderscoreCounter(string name)
+ {
+ var existingNames = new HashSet(StringComparer.OrdinalIgnoreCase) { "Seed", "Speed_1" };
+
+ return VFXParameterController.MakeNameUnique(name, existingNames, false, VFXParameterController.kMaxExposedNameLength, null);
+ }
+
+ [TestCase("Group (2147483647)", true, ExpectedResult = "Group (2147483648)")]
+ [TestCase("X (99999999999999999999)", true, ExpectedResult = "X (100000000000000000000)")]
+ [TestCase("Seed_2147483647", false, ExpectedResult = "Seed_2147483648")]
+ [TestCase("Seed_99999999999999999999", false, ExpectedResult = "Seed_100000000000000000000")]
+ public string MakeNameUnique_WithCounterBeyondInt_IncrementsCounter(string name, bool allowSpace)
+ {
+ var existingNames = new HashSet(StringComparer.OrdinalIgnoreCase) { name };
+
+ return VFXParameterController.MakeNameUnique(name, existingNames, allowSpace, VFXParameterController.kMaxExposedNameLength, null);
+ }
+
+ [TestCase("_free", ExpectedResult = "_free")]
+ [TestCase("_velocity", ExpectedResult = "_velocity_1")]
+ [TestCase("velocity_", ExpectedResult = "velocity__1")]
+ [TestCase("_1", ExpectedResult = "_2")]
+ [TestCase("___", ExpectedResult = null)]
+ public string MakeNameUnique_WithoutSpaces_KeepsUnderscores(string name)
+ {
+ var existingNames = new HashSet(StringComparer.OrdinalIgnoreCase) { "_velocity", "velocity_", "_1" };
+
+ return VFXParameterController.MakeNameUnique(name, existingNames, false, VFXParameterController.kMaxExposedNameLength, null);
+ }
+
+ [TestCase("\tSpeed", ExpectedResult = "Speed")]
+ [TestCase("SpeedĀ ", ExpectedResult = "Speed")]
+ [TestCase(" \nSpeed \t", ExpectedResult = "Speed")]
+ [TestCase("Taken\t", ExpectedResult = "Taken (1)")]
+ [TestCase("\t", ExpectedResult = null)]
+ public string MakeNameUnique_WithSpaces_TrimsWhitespace(string name)
+ {
+ var existingNames = new HashSet(StringComparer.OrdinalIgnoreCase) { "Taken" };
+
+ return VFXParameterController.MakeNameUnique(name, existingNames, true, VFXParameterController.kMaxExposedNameLength, null);
+ }
+
+ [Test]
+ public void MakeNameUnique_WithCutEndingInWhitespace_DropsWhitespaceBeforeCounter()
+ {
+ var prefix = new string('a', VFXParameterController.kMaxExposedNameLength - 6);
+ string name = prefix + " b (9)";
+ var existingNames = new HashSet(StringComparer.OrdinalIgnoreCase) { name };
+
+ string uniqueName = VFXParameterController.MakeNameUnique(name, existingNames, true, VFXParameterController.kMaxExposedNameLength, null);
+
+ Assert.AreEqual(prefix + " (10)", uniqueName);
+ }
+
+ [TestCase(true)]
+ [TestCase(false)]
+ public void MakeNameUnique_WithCounterFillingMaxLength_RestartsCounter(bool allowSpace)
+ {
+ int maxLength = VFXParameterController.kMaxExposedNameLength;
+ string name = allowSpace ? "a (" + new string('9', maxLength - 4) + ")" : "a_" + new string('9', maxLength - 2);
+ var existingNames = new HashSet(StringComparer.OrdinalIgnoreCase) { name };
+
+ string uniqueName = VFXParameterController.MakeNameUnique(name, existingNames, allowSpace, maxLength, null);
+
+ string expectedName = allowSpace ? name.Substring(0, maxLength - 4) + " (1)" : name.Substring(0, maxLength - 2) + "_1";
+ Assert.AreEqual(expectedName, uniqueName);
+ }
+
+ [TestCase(true)]
+ [TestCase(false)]
+ public void MakeNameUnique_DuplicatedTenTimesAtMaxLength_CountsFromOne(bool allowSpace)
+ {
+ int maxLength = VFXParameterController.kMaxExposedNameLength;
+ string name = allowSpace ? "a (" + new string('9', maxLength - 4) + ")" : "a_" + new string('9', maxLength - 2);
+ var existingNames = new HashSet(StringComparer.OrdinalIgnoreCase) { name };
+
+ string uniqueName = null;
+ for (int i = 0; i < 10; ++i)
+ {
+ uniqueName = VFXParameterController.MakeNameUnique(name, existingNames, allowSpace, maxLength, null);
+ Assert.LessOrEqual(uniqueName.Length, maxLength);
+ existingNames.Add(uniqueName);
+ }
+
+ string expectedName = allowSpace ? name.Substring(0, maxLength - 5) + " (10)" : name.Substring(0, maxLength - 3) + "_10";
+ Assert.AreEqual(expectedName, uniqueName);
+ }
+
+ [Test]
+ public void AddVFXParameter_Vector3Twice_KeepsTypeNameInDefaultName()
+ {
+ VFXModelDescriptorParameters vector3Descriptor = VFXLibrary.GetParameters().First(x => x.modelType == typeof(Vector3));
+
+ VFXParameter first = m_ViewController.AddVFXParameter(Vector2.zero, vector3Descriptor.variant);
+ m_ViewController.ApplyChanges();
+ VFXParameter second = m_ViewController.AddVFXParameter(Vector2.zero, vector3Descriptor.variant);
+ m_ViewController.ApplyChanges();
+
+ Assert.AreEqual("New Vector 3", first.exposedName);
+ Assert.AreEqual("New Vector 3 (1)", second.exposedName);
+ }
+
+ [Test]
+ public void OpenGraph_WithDuplicateParameterNames_UsesParenthesizedCounter()
+ {
+ VFXModelDescriptorParameters floatDescriptor = VFXLibrary.GetParameters().First(x => x.modelType == typeof(float));
+
+ VFXParameter first = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+ VFXParameter second = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+ VFXParameter third = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+
+ first.SetSettingValue("m_ExposedName", "Speed");
+ second.SetSettingValue("m_ExposedName", "Speed");
+ third.SetSettingValue("m_ExposedName", "_Value_");
+
+ // A new controller sanitizes the parameter names of the graph
+ VisualEffectResource resource = m_ViewController.model;
+ m_ViewController.useCount--;
+ m_ViewController = VFXViewController.GetController(resource);
+ m_ViewController.useCount++;
+
+ Assert.AreEqual("Speed", first.exposedName);
+ Assert.AreEqual("Speed (1)", second.exposedName);
+ Assert.AreEqual("_Value_", third.exposedName);
+ }
+
+ [Test]
+ public void OpenGraph_WithDuplicateName_DoesNotTakeNameOfLaterParameter()
+ {
+ VFXModelDescriptorParameters floatDescriptor = VFXLibrary.GetParameters().First(x => x.modelType == typeof(float));
+
+ VFXParameter first = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+ VFXParameter second = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+ VFXParameter third = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+
+ first.SetSettingValue("m_ExposedName", "Speed");
+ second.SetSettingValue("m_ExposedName", "Speed");
+ third.SetSettingValue("m_ExposedName", "Speed (1)");
+
+ // A new controller sanitizes the parameter names of the graph
+ VisualEffectResource resource = m_ViewController.model;
+ m_ViewController.useCount--;
+ m_ViewController = VFXViewController.GetController(resource);
+ m_ViewController.useCount++;
+
+ Assert.AreEqual("Speed", first.exposedName);
+ Assert.AreEqual("Speed (2)", second.exposedName);
+ Assert.AreEqual("Speed (1)", third.exposedName);
+ }
+
+ [Test]
+ public void OpenGraph_WithOverLengthName_DoesNotTakeNameOfLaterParameter()
+ {
+ var longName = new string('a', VFXParameterController.kMaxExposedNameLength);
+ string cutName = new('a', VFXParameterController.kMaxExposedNameLength - 4);
+ VFXModelDescriptorParameters floatDescriptor = VFXLibrary.GetParameters().First(x => x.modelType == typeof(float));
+
+ VFXParameter original = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+ VFXParameter copy = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+ VFXParameter later = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+
+ // Duplicating a category didn't apply the length limit to the copied parameters
+ original.SetSettingValue("m_ExposedName", longName);
+ copy.SetSettingValue("m_ExposedName", longName + " 1");
+ later.SetSettingValue("m_ExposedName", cutName + " (1)");
+
+ // A new controller sanitizes the parameter names of the graph
+ VisualEffectResource resource = m_ViewController.model;
+ m_ViewController.useCount--;
+ m_ViewController = VFXViewController.GetController(resource);
+ m_ViewController.useCount++;
+
+ Assert.AreEqual(longName, original.exposedName);
+ Assert.AreEqual(cutName + " (2)", copy.exposedName);
+ Assert.AreEqual(cutName + " (1)", later.exposedName);
+ }
+
+ [Test]
+ public void OpenGraph_WithOverLengthFirstName_CutsName()
+ {
+ string cutName = new('a', VFXParameterController.kMaxExposedNameLength - 4);
+ VFXModelDescriptorParameters floatDescriptor = VFXLibrary.GetParameters().First(x => x.modelType == typeof(float));
+
+ VFXParameter first = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+ VFXParameter second = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+
+ first.SetSettingValue("m_ExposedName", new string('a', VFXParameterController.kMaxExposedNameLength + 1));
+ second.SetSettingValue("m_ExposedName", "Speed");
+
+ // A new controller sanitizes the parameter names of the graph
+ VisualEffectResource resource = m_ViewController.model;
+ m_ViewController.useCount--;
+ m_ViewController = VFXViewController.GetController(resource);
+ m_ViewController.useCount++;
+
+ Assert.AreEqual(cutName + " (1)", first.exposedName);
+ Assert.AreEqual("Speed", second.exposedName);
+ }
+
+ [Test]
+ public void OpenGraph_WithWhitespaceAroundName_TrimsName()
+ {
+ VFXModelDescriptorParameters floatDescriptor = VFXLibrary.GetParameters().First(x => x.modelType == typeof(float));
+
+ VFXParameter first = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+ VFXParameter second = m_ViewController.AddVFXParameter(Vector2.zero, floatDescriptor.variant);
+ m_ViewController.ApplyChanges();
+
+ first.SetSettingValue("m_ExposedName", "SpeedĀ ");
+ second.SetSettingValue("m_ExposedName", "\tAngle");
+
+ // A new controller sanitizes the parameter names of the graph
+ VisualEffectResource resource = m_ViewController.model;
+ m_ViewController.useCount--;
+ m_ViewController = VFXViewController.GetController(resource);
+ m_ViewController.useCount++;
+
+ Assert.AreEqual("Speed", first.exposedName);
+ Assert.AreEqual("Angle", second.exposedName);
+ }
}
}
#endif
diff --git a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXPreviewCompileBuildTests.cs b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXPreviewCompileBuildTests.cs
new file mode 100644
index 00000000000..7b48829f2f9
--- /dev/null
+++ b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/VFXPreviewCompileBuildTests.cs
@@ -0,0 +1,108 @@
+using System.Collections.Generic;
+using System.IO;
+using NUnit.Framework;
+using UnityEngine;
+using UnityEngine.VFX;
+
+namespace UnityEditor.VFX.Test
+{
+ [TestFixture]
+ class VFXPreviewCompileBuildTests
+ {
+ const string k_BundleFolder = "Temp/VFXPreviewCompileBuildTests";
+ const string k_BundleName = "vfxpreviewcompile";
+
+ AssetBundle m_Bundle;
+
+ [OneTimeSetUp]
+ public void OneTimeSetUp()
+ {
+ var buildTarget = EditorUserBuildSettings.activeBuildTarget;
+ if (!BuildPipeline.IsBuildTargetSupported(BuildPipeline.GetBuildTargetGroup(buildTarget), buildTarget))
+ Assert.Ignore($"Requires player support for {buildTarget} to build AssetBundles.");
+ }
+
+ [TearDown]
+ public void TearDown()
+ {
+ if (m_Bundle != null)
+ m_Bundle.Unload(true);
+ m_Bundle = null;
+ VFXTestCommon.CloseAllVFXWindow();
+ VFXTestCommon.DeleteAllTemporaryGraph();
+ if (Directory.Exists(k_BundleFolder))
+ Directory.Delete(k_BundleFolder, true);
+ }
+
+ // Only m_Systems is in builds, m_EditorSystems also references shaders but is editor only
+ static List