This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 686bcd471035ed641a36aa69aacb76a9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,104 @@
#ifndef DECODE_SH
# define DECODE_SH
// TODO: We're working on irradiance instead of radiance coefficients
// Add safety margin 2 to avoid out-of-bounds values
#define APV_L1_ENCODING_SCALE 2.0 // Should be: 3/(2*sqrt(3)) * 2, but rounding to 2 to issues we are observing.
#define APV_L2_ENCODING_SCALE 3.5777088 // 4/sqrt(5) * 2
float3 DecodeSH(float l0, float3 l1)
{
return (l1 - 0.5f) * (2.0f * APV_L1_ENCODING_SCALE * l0);
}
void DecodeSH_L2(inout float3 l0, inout float4 l2_R, inout float4 l2_G, inout float4 l2_B, inout float3 l2_C)
{
l2_R = (l2_R - 0.5f) * (APV_L2_ENCODING_SCALE * l0.r);
l2_G = (l2_G - 0.5f) * (APV_L2_ENCODING_SCALE * l0.g);
l2_B = (l2_B - 0.5f) * (APV_L2_ENCODING_SCALE * l0.b);
l2_C = (l2_C - 0.5f) * APV_L2_ENCODING_SCALE;
l2_C.rgb *= l0;
// Account for how L2 is encoded.
l0.r -= l2_R.z;
l0.g -= l2_G.z;
l0.b -= l2_B.z;
l2_R.z *= 3.0f;
l2_G.z *= 3.0f;
l2_B.z *= 3.0f;
}
void DecodeSH_L2(inout float3 l0, inout float4 l2_R, inout float4 l2_G, inout float4 l2_B, inout float4 l2_C)
{
float3 outL2_C = l2_C.xyz;
DecodeSH_L2(l0, l2_R, l2_G, l2_B, outL2_C);
l2_C = float4(outL2_C.xyz, 0);
}
half3 DecodeSH(half l0, half3 l1)
{
return (l1 - 0.5) * (2.0 * APV_L1_ENCODING_SCALE * l0);
}
void DecodeSH_L2(inout half3 l0, inout half4 l2_R, inout half4 l2_G, inout half4 l2_B, inout half3 l2_C)
{
l2_R = (l2_R - 0.5) * (APV_L2_ENCODING_SCALE * l0.r);
l2_G = (l2_G - 0.5) * (APV_L2_ENCODING_SCALE * l0.g);
l2_B = (l2_B - 0.5) * (APV_L2_ENCODING_SCALE * l0.b);
l2_C = (l2_C - 0.5) * APV_L2_ENCODING_SCALE;
l2_C.rgb *= l0;
// Account for how L2 is encoded.
l0.r -= l2_R.z;
l0.g -= l2_G.z;
l0.b -= l2_B.z;
l2_R.z *= 3.0;
l2_G.z *= 3.0;
l2_B.z *= 3.0;
}
void DecodeSH_L2(inout half3 l0, inout half4 l2_R, inout half4 l2_G, inout half4 l2_B, inout half4 l2_C)
{
half3 outL2_C = l2_C.xyz;
DecodeSH_L2(l0, l2_R, l2_G, l2_B, outL2_C);
l2_C = half4(outL2_C.xyz, 0);
}
float3 EncodeSH(float l0, float3 l1)
{
return l0 == 0.0f ? 0.5f : l1 * rcp(l0) / (2.0f * APV_L1_ENCODING_SCALE) + 0.5f;
}
#if !HALF_IS_FLOAT
half3 EncodeSH(half l0, half3 l1)
{
// UUM-92338: To prevent rcp(l0) from going to infinity, 1.0/l0 must be smaller than 65504 (HALF_MAX)
// => l0 must be greater than than 1.0/65504 = 0.00001526624(0x0100) which is a subnormal number
// To ensure robustness and avoid issues, we need a bigger threshold value.
// 0.00006103515625 (HALF_MIN) would be a decent choice but we select 0.0001 instead, which was already used in ProbeVolume.hlsl
return (l0 < 0.0001 ? 0.5 : l1 * rcp(l0) / (2.0 * APV_L1_ENCODING_SCALE) + 0.5);
}
#endif
void EncodeSH_L2(inout float3 l0, inout float4 l2_R, inout float4 l2_G, inout float4 l2_B, inout float3 l2_C)
{
// Account for how L2 is encoded.
l2_R.z /= 3.0f;
l2_G.z /= 3.0f;
l2_B.z /= 3.0f;
l0.r += l2_R.z;
l0.g += l2_G.z;
l0.b += l2_B.z;
float3 rcpl0 = rcp(l0);
rcpl0 = float3(l0.x == 0.0f ? 0.0f : rcpl0.x, l0.y == 0.0f ? 0.0f : rcpl0.y, l0.z == 0.0f ? 0.0f : rcpl0.z);
l2_R = 0.5f + l2_R * rcp(APV_L2_ENCODING_SCALE) * rcpl0.r;
l2_G = 0.5f + l2_G * rcp(APV_L2_ENCODING_SCALE) * rcpl0.g;
l2_B = 0.5f + l2_B * rcp(APV_L2_ENCODING_SCALE) * rcpl0.b;
l2_C = 0.5f + l2_C * rcp(APV_L2_ENCODING_SCALE) * rcpl0;
}
#endif // DECODE_SH
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 6646f462aeb8278489c25fda24fd2db8
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,24 @@
namespace UnityEngine.Rendering
{
/// <summary>
/// By implementing this interface, a render pipeline can indicate to its usage of the Adaptive Probe Volume system..
/// </summary>
public interface IProbeVolumeEnabledRenderPipeline
{
/// <summary>
/// Indicates if this render pipeline instance supports Adaptive Probe Volume.
/// </summary>
bool supportProbeVolume { get; }
/// <summary>
/// Indicates the maximum number of SH Bands used by this render pipeline instance.
/// </summary>
ProbeVolumeSHBands maxSHBands { get; }
/// <summary>
/// Returns the projects global ProbeVolumeSceneData instance.
/// </summary>
[System.Obsolete("This field is no longer necessary. #from(2023.3)")]
ProbeVolumeSceneData probeVolumeSceneData { get; }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 69fb8499dac69054b912c0d501c0c3ec
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,271 @@
using System;
namespace UnityEngine.Rendering
{
/// <summary>
/// A marker to adjust probes in an area of the scene.
/// </summary>
[CoreRPHelpURL("probevolumes-adjustment-volume-component-reference", "com.unity.render-pipelines.high-definition")]
[ExecuteAlways]
[AddComponentMenu("Rendering/Probe Adjustment Volume")]
public partial class ProbeAdjustmentVolume : MonoBehaviour, ISerializationCallbackReceiver
{
/// <summary>The type of shape that an adjustment volume can take. </summary>
public enum Shape
{
/// <summary>A Box shape.</summary>
Box,
/// <summary>A Sphere shape.</summary>
Sphere,
};
/// <summary>The shape of the adjustment volume</summary>
[Tooltip("Select the shape used for this Probe Adjustment Volume.")]
public Shape shape = Shape.Box;
/// <summary>
/// The size for box shape.
/// </summary>
[Min(0.0f), Tooltip("Modify the size of this Probe Adjustment Volume. This is unaffected by the GameObject's Transform's Scale property.")]
public Vector3 size = new Vector3(1, 1, 1);
/// <summary>
/// The size for sphere shape.
/// </summary>
[Min(0.0f), Tooltip("Modify the radius of this Probe Adjustment Volume. This is unaffected by the GameObject's Transform's Scale property.")]
public float radius = 1.0f;
/// <summary>The mode that adjustment volume will operate in. It determines what probes falling within the volume will do. </summary>
public enum Mode
{
/// <summary>Invalidate the probes within the adjustment volume.</summary>
InvalidateProbes,
/// <summary>Override the dilation validity threshold for the probes within the adjustment volume.</summary>
OverrideValidityThreshold,
/// <summary>Apply an explicit virtual offset to the probes within the adjustment volume.</summary>
ApplyVirtualOffset,
/// <summary>Override the virtual offset settings for the probes within the adjustment volume.</summary>
OverrideVirtualOffsetSettings,
/// <summary>Override the dynamic sky shading direction for the probes within the adjustment volume.</summary>
OverrideSkyDirection,
/// <summary>Override the Lightmapper sample count for the probes within the adjustment volume.</summary>
OverrideSampleCount,
/// <summary>Control the rendering layer masks for the probes within the adjustment volume.</summary>
OverrideRenderingLayerMask,
/// <summary>Scale probe intensity.</summary>
IntensityScale = 99, // make sure this appears last
};
/// <summary>The mode that adjustment volume will operate in. It determines what probes falling within the volume will do. </summary>
public enum RenderingLayerMaskOperation
{
/// <summary>Overrides the rendering layer mask for the probes within the adjustment volume.</summary>
Override,
/// <summary>Add a rendering layer to the probes within the adjustment volume.</summary>
Add,
/// <summary>Removes a rendering layer to the probes within the adjustment volume.</summary>
Remove,
};
/// <summary>Choose what to do with probes falling inside this volume</summary>
public Mode mode = Mode.InvalidateProbes;
/// <summary>
/// A scale to apply to probes falling within the invalidation volume. It is really important to use this with caution as it can lead to inconsistent lighting.
/// </summary>
[Range(0.0001f, 2.0f), Tooltip("A multiplier applied to the intensity of probes covered by this Probe Adjustment Volume.")]
public float intensityScale = 1.0f;
/// <summary>
/// The overridden dilation threshold.
/// </summary>
[Range(0.0f, 0.95f)]
public float overriddenDilationThreshold = 0.75f;
/// <summary>The rotation angles for the virtual offset direction.</summary>
public Vector3 virtualOffsetRotation = Vector3.zero;
/// <summary>Determines how far probes are pushed along the specified virtual offset direction.</summary>
[Min(0.0f)]
public float virtualOffsetDistance = 1.0f;
/// <summary>Determines how far Unity pushes a probe out of geometry after a ray hit.</summary>
[Range(0f, 1f), Tooltip("Determines how far Unity pushes a probe out of geometry after a ray hit.")]
public float geometryBias = 0.01f;
/// <summary>Virtual Offset validity threshold.</summary>
[Range(0f, 0.95f)]
public float virtualOffsetThreshold = 0.75f;
/// <summary>Distance from the probe position used to determine the origin of the sampling ray.</summary>
[Range(-0.05f, 0f), Tooltip("Distance from the probe position used to determine the origin of the sampling ray.")]
public float rayOriginBias = -0.001f;
/// <summary>The sky direction.</summary>
[Tooltip("The direction for sampling the ambient probe in worldspace when using the Sky Visibility feature.")]
public Vector3 skyDirection = Vector3.zero;
internal Vector3 skyShadingDirectionRotation = Vector3.zero;
/// <summary>Number of samples for direct lighting computations.</summary>
[Logarithmic(1, 1024), Tooltip("Number of samples for direct lighting computations.")]
public int directSampleCount = 32;
/// <summary>Number of samples for indirect lighting computations. This includes environment samples.</summary>
[Logarithmic(1, 8192), Tooltip("Number of samples for indirect lighting computations. This includes environment samples.")]
public int indirectSampleCount = 512;
/// <summary>Multiplier for the number of samples specified above.</summary>
[Min(0), Tooltip("Multiplier for the number of samples specified above.")]
public int sampleCountMultiplier = 4;
/// <summary>Maximum number of bounces for indirect lighting.</summary>
[Min(0), Tooltip("Maximum number of bounces for indirect lighting.")]
public int maxBounces = 2;
/// <summary>Controls the number of samples per probe for sky occlusion baking.</summary>
[Logarithmic(1, ProbeVolumeBakingSet.k_MaxSkyOcclusionBakingSamples)]
public int skyOcclusionSampleCount = 2048;
/// <summary>Controls the number of bounces per light path for sky occlusion baking.</summary>
[Range(0, 5)]
public int skyOcclusionMaxBounces = 2;
/// <summary>Rendering Layer Mask operation.</summary>
public RenderingLayerMaskOperation renderingLayerMaskOperation;
/// <summary>Rendering layer mask used for the combine operation with the probes inside the volume.</summary>
public byte renderingLayerMask;
#if UNITY_EDITOR
[SerializeField] internal int cachedHashCode = 0;
public override int GetHashCode()
{
int hash = 17;
unchecked
{
hash = hash * 23 + gameObject.transform.worldToLocalMatrix.GetHashCode();
hash = hash * 23 + shape.GetHashCode();
hash = hash * 23 + size.GetHashCode();
hash = hash * 23 + radius.GetHashCode();
hash = hash * 23 + mode.GetHashCode();
hash = hash * 23 + intensityScale.GetHashCode();
hash = hash * 23 + overriddenDilationThreshold.GetHashCode();
hash = hash * 23 + virtualOffsetRotation.GetHashCode();
hash = hash * 23 + virtualOffsetDistance.GetHashCode();
hash = hash * 23 + geometryBias.GetHashCode();
hash = hash * 23 + rayOriginBias.GetHashCode();
hash = hash * 23 + skyDirection.GetHashCode();
hash = hash * 23 + skyShadingDirectionRotation.GetHashCode();
hash = hash * 23 + directSampleCount.GetHashCode();
hash = hash * 23 + indirectSampleCount.GetHashCode();
hash = hash * 23 + sampleCountMultiplier.GetHashCode();
hash = hash * 23 + maxBounces.GetHashCode();
hash = hash * 23 + skyOcclusionSampleCount.GetHashCode();
hash = hash * 23 + skyOcclusionMaxBounces.GetHashCode();
}
return hash;
}
#endif
#if UNITY_EDITOR
/// <summary>
/// Returns the extents of the volume.
/// </summary>
/// <returns>The extents of the ProbeVolume.</returns>
public Vector3 GetExtents()
{
return size;
}
internal void GetOBBandAABB(out ProbeReferenceVolume.Volume volume, out Bounds bounds)
{
if (shape == Shape.Box)
{
volume = new ProbeReferenceVolume.Volume(Matrix4x4.TRS(transform.position, transform.rotation, GetExtents()), 0, 0);
bounds = volume.CalculateAABB();
}
else
{
volume = default;
bounds = new Bounds(transform.position, radius * Vector3.up);
}
}
internal float ComputeVolume(in ProbeReferenceVolume.Volume touchupOBB)
{
if (shape == Shape.Box)
return touchupOBB.X.magnitude * touchupOBB.Y.magnitude * touchupOBB.Z.magnitude;
else
return (4.0f / 3.0f) * Mathf.PI * radius * radius * radius;
}
internal bool IntersectsVolume(in ProbeReferenceVolume.Volume touchupOBB, in Bounds touchupBounds, Bounds volumeBounds)
{
if (shape == Shape.Box)
return ProbeVolumePositioning.OBBAABBIntersect(touchupOBB, volumeBounds, touchupBounds);
else
return volumeBounds.SqrDistance(touchupBounds.center) < radius * radius;
}
internal bool ContainsPoint(in ProbeReferenceVolume.Volume touchupOBB, in Vector3 touchupCenter, in Vector3 position)
{
if (shape == Shape.Box)
return ProbeVolumePositioning.OBBContains(touchupOBB, position);
else
return (touchupCenter - position).sqrMagnitude < radius * radius;
}
internal Vector3 GetVirtualOffset()
{
if (mode != Mode.ApplyVirtualOffset)
return Vector3.zero;
return (transform.rotation * Quaternion.Euler(virtualOffsetRotation) * Vector3.forward) * virtualOffsetDistance;
}
#endif
// Migration related stuff
enum Version
{
Initial,
Mode,
Count
}
[SerializeField]
Version version = Version.Count;
// This piece of code is needed because some objects could have been created before existence of Version enum
/// <summary>OnBeforeSerialize needed to handle migration before the versioning system was in place.</summary>
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
if (version == Version.Count) // serializing a newly created object
version = Version.Count - 1; // mark as up to date
}
/// <summary>OnAfterDeserialize needed to handle migration before the versioning system was in place.</summary>
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
if (version == Version.Count) // deserializing and object without version
version = Version.Initial; // reset to run the migration
if (version < Version.Mode)
{
#pragma warning disable 618 // Type or member is obsolete
if (invalidateProbes)
mode = Mode.InvalidateProbes;
else if (overrideDilationThreshold)
mode = Mode.OverrideValidityThreshold;
#pragma warning restore 618
version = Version.Mode;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 55f90731af2ebc94fb7fdaebe2a9a409
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 92bd54f0441984747b65b6505c9f6ebb, type: 2}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
using System;
namespace UnityEngine.Rendering
{
public partial class ProbeAdjustmentVolume
{
/// <summary>Whether to invalidate all probes falling within this volume.</summary>
[Obsolete("This field is only kept for migration purpose. Use mode instead. #from(2023.1)")] public bool invalidateProbes = false;
/// <summary>Whether to use a custom threshold for dilation for probes falling withing this volume.</summary>
[Obsolete("This field is only kept for migration purpose. Use mode instead. #from(2023.1)")] public bool overrideDilationThreshold = false;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a91edae7e71f48b9880e1bda95128cfd
timeCreated: 1739986118
@@ -0,0 +1,510 @@
//#define USE_INDEX_NATIVE_ARRAY
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Profiling;
using Unity.Profiling.LowLevel;
using System.Collections;
using Chunk = UnityEngine.Rendering.ProbeBrickPool.BrickChunkAlloc;
using CellIndexInfo = UnityEngine.Rendering.ProbeReferenceVolume.CellIndexInfo;
namespace UnityEngine.Rendering
{
internal class ProbeBrickIndex
{
/// <summary>
/// Allocates the physical index <c>ComputeBuffer</c>, the backing CPU
/// <c>NativeArray</c>, and the chunk free-list, then runs <c>Clear</c> to
/// zero-initialize the buffer. Cost scales with the memory budget.
/// </summary>
static readonly ProfilerMarker k_CreateProbeBrickIndex =
new ProfilerMarker(ProfilerCategory.Render, "Create ProbeBrickIndex",
MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Zeroes the physical index CPU array, marks all index chunks as free, and resets the
/// dirty range so the full buffer is re-uploaded on the next GPU sync.
/// </summary>
static readonly ProfilerMarker k_ClearIndex =
new ProfilerMarker(ProfilerCategory.Render, "Clear Index",
MarkerFlags.VerbosityAdvanced);
// a few constants
internal const int kMaxSubdivisionLevels = 7; // 3 bits
internal const int kIndexChunkSize = 243;
internal const int kFailChunkIndex = -1;
internal const int kEmptyIndex = -2; // This is a tag value used to say that we have a valid entry but with no data.
BitArray m_IndexChunks;
BitArray m_IndexChunksCopyForChecks;
int m_ChunksCount;
int m_AvailableChunkCount;
ComputeBuffer m_PhysicalIndexBuffer;
NativeArray<int> m_PhysicalIndexBufferData;
ComputeBuffer m_DebugFragmentationBuffer;
int[] m_DebugFragmentationData;
bool m_NeedUpdateIndexComputeBuffer;
int m_UpdateMinIndex = int.MaxValue;
int m_UpdateMaxIndex = int.MinValue;
internal int estimatedVMemCost { get; private set; }
internal ComputeBuffer GetDebugFragmentationBuffer() => m_DebugFragmentationBuffer;
internal float fragmentationRate { get; private set; }
[DebuggerDisplay("Brick [{position}, {subdivisionLevel}]")]
[Serializable]
public struct Brick : IEquatable<Brick>
{
public Vector3Int position; // refspace index, indices are brick coordinates at max resolution
public int subdivisionLevel; // size as factor covered elementary cells
internal Brick(Vector3Int position, int subdivisionLevel)
{
this.position = position;
this.subdivisionLevel = subdivisionLevel;
}
public bool Equals(Brick other) => position == other.position && subdivisionLevel == other.subdivisionLevel;
// Important boundInBricks needs to be in min brick size so we can be agnostic of profile information.
public bool IntersectArea(Bounds boundInBricksToCheck)
{
int sizeInMinBricks = ProbeReferenceVolume.CellSize(subdivisionLevel);
Bounds brickBounds = new Bounds();
brickBounds.min = position;
brickBounds.max = position + new Vector3Int(sizeInMinBricks, sizeInMinBricks, sizeInMinBricks);
brickBounds.extents *= 0.99f; // Extend a bit to avoid issues.
bool intersectionHappens = boundInBricksToCheck.Intersects(brickBounds);
return intersectionHappens;
}
}
Vector3Int m_CenterRS; // the anchor in ref space, around which the index is defined. [IMPORTANT NOTE! For now we always have it at 0, so is not passed to the shader, but is kept here until development is active in case we find it useful]
int SizeOfPhysicalIndexFromBudget(ProbeVolumeTextureMemoryBudget memoryBudget)
{
switch (memoryBudget)
{
case ProbeVolumeTextureMemoryBudget.MemoryBudgetLow:
// 16 MB - 4 million of bricks worth of space. At full resolution and a distance of 1 meter between probes, this is roughly 474 * 474 * 474 meters worth of bricks. If 0.25x on Y axis, this is equivalent to 948 * 118 * 948 meters
return 4000000;
case ProbeVolumeTextureMemoryBudget.MemoryBudgetMedium:
// 32 MB - 8 million of bricks worth of space. At full resolution and a distance of 1 meter between probes, this is roughly 600 * 600 * 600 meters worth of bricks. If 0.25x on Y axis, this is equivalent to 1200 * 150 * 1200 meters
return 8000000;
case ProbeVolumeTextureMemoryBudget.MemoryBudgetHigh:
// 64 MB - 16 million of bricks worth of space. At full resolution and a distance of 1 meter between probes, this is roughly 756 * 756 * 756 meters worth of bricks. If 0.25x on Y axis, this is equivalent to 1512 * 184 * 1512 meters
return 16000000;
}
return 32000000;
}
internal ProbeBrickIndex(ProbeVolumeTextureMemoryBudget memoryBudget)
{
using var _ = k_CreateProbeBrickIndex.Auto();
m_CenterRS = new Vector3Int(0, 0, 0);
m_NeedUpdateIndexComputeBuffer = false;
m_ChunksCount = Mathf.Max(1, Mathf.CeilToInt((float)SizeOfPhysicalIndexFromBudget(memoryBudget) / kIndexChunkSize));
m_AvailableChunkCount = m_ChunksCount;
m_IndexChunks = new BitArray(m_ChunksCount);
m_IndexChunksCopyForChecks = new BitArray(m_ChunksCount);
int physicalBufferSize = m_ChunksCount * kIndexChunkSize;
m_PhysicalIndexBufferData = new NativeArray<int>(physicalBufferSize, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
m_PhysicalIndexBuffer = new ComputeBuffer(physicalBufferSize, sizeof(int), ComputeBufferType.Structured);
estimatedVMemCost = physicalBufferSize * sizeof(int);
Clear();
}
public int GetRemainingChunkCount()
{
return m_AvailableChunkCount;
}
internal void UploadIndexData()
{
var count = m_UpdateMaxIndex - m_UpdateMinIndex + 1;
Debug.Assert(m_UpdateMinIndex >= 0 && m_UpdateMaxIndex < m_PhysicalIndexBufferData.Length, "Out of bounds");
Debug.Assert(count >= 0, "Negative index");
m_PhysicalIndexBuffer.SetData(m_PhysicalIndexBufferData, m_UpdateMinIndex, m_UpdateMinIndex, count);
m_NeedUpdateIndexComputeBuffer = false;
m_UpdateMaxIndex = int.MinValue;
m_UpdateMinIndex = int.MaxValue;
}
void UpdateDebugData()
{
if (m_DebugFragmentationData == null || m_DebugFragmentationData.Length != m_IndexChunks.Length)
{
m_DebugFragmentationData = new int[m_IndexChunks.Length];
CoreUtils.SafeRelease(m_DebugFragmentationBuffer);
m_DebugFragmentationBuffer = new ComputeBuffer(m_IndexChunks.Length, 4);
}
for (int i = 0; i < m_IndexChunks.Length; ++i)
{
m_DebugFragmentationData[i] = m_IndexChunks[i] ? 1 : -1;
}
m_DebugFragmentationBuffer.SetData(m_DebugFragmentationData);
}
internal void Clear()
{
using var _ = k_ClearIndex.Auto();
m_IndexChunks.SetAll(false);
m_AvailableChunkCount = m_ChunksCount;
// Clear the physical buffer
// This is not needed but cleaner i guess
unsafe
{
uint* pBuffer = (uint*)NativeArrayUnsafeUtility.GetUnsafePtr(m_PhysicalIndexBufferData);
UnsafeUtility.MemSet(pBuffer, 0xFF, m_PhysicalIndexBufferData.Length * 4);
m_NeedUpdateIndexComputeBuffer = true;
m_UpdateMinIndex = 0;
m_UpdateMaxIndex = m_PhysicalIndexBufferData.Length - 1;
}
}
internal void GetRuntimeResources(ref ProbeReferenceVolume.RuntimeResources rr)
{
bool displayFrag = ProbeReferenceVolume.instance.probeVolumeDebug.displayIndexFragmentation;
// If we are pending an update of the actual compute buffer we do it here
if (m_NeedUpdateIndexComputeBuffer)
{
UploadIndexData();
if (displayFrag)
UpdateDebugData();
}
if (displayFrag && m_DebugFragmentationBuffer == null)
UpdateDebugData();
rr.index = m_PhysicalIndexBuffer;
}
internal void Cleanup()
{
m_PhysicalIndexBufferData.Dispose();
CoreUtils.SafeRelease(m_PhysicalIndexBuffer);
m_PhysicalIndexBuffer = null;
CoreUtils.SafeRelease(m_DebugFragmentationBuffer);
m_DebugFragmentationBuffer = null;
}
internal void ComputeFragmentationRate()
{
// Clearly suboptimal, will need to be profiled before trying to make it smarter.
int highestAllocatedChunk = 0;
for (int i = m_ChunksCount - 1; i >= 0; i--)
{
if (m_IndexChunks[i])
{
highestAllocatedChunk = i + 1;
break;
}
}
int tailFreeChunks = m_ChunksCount - highestAllocatedChunk;
int holes = m_AvailableChunkCount - tailFreeChunks;
fragmentationRate = (float)holes / highestAllocatedChunk;
}
public struct IndirectionEntryUpdateInfo
{
public int firstChunkIndex;
public int numberOfChunks;
public int minSubdivInCell;
// IMPORTANT, These values should be at max resolution, independent of minSubdivInCell. This means that
// The map to the lower possible resolution is done after. However they are still in local space.
public Vector3Int minValidBrickIndexForCellAtMaxRes;
public Vector3Int maxValidBrickIndexForCellAtMaxResPlusOne;
public Vector3Int entryPositionInBricksAtMaxRes;
public bool hasOnlyBiggerBricks; // True if it has only bricks that are bigger than the entry itself
}
public struct CellIndexUpdateInfo
{
public IndirectionEntryUpdateInfo[] entriesInfo;
public int GetNumberOfChunks()
{
int chunkCount = 0;
foreach (var entry in entriesInfo)
{
chunkCount += entry.numberOfChunks;
}
return chunkCount;
}
}
int MergeIndex(int index, int size)
{
const int mask = kMaxSubdivisionLevels;
const int shift = 28;
return (index & ~(mask << shift)) | ((size & mask) << shift);
}
internal int GetNumberOfChunks(int brickCount)
{
return Mathf.CeilToInt((float)brickCount / kIndexChunkSize);
}
internal bool FindSlotsForEntries(ref IndirectionEntryUpdateInfo[] entriesInfo)
{
using var _ = new Unity.Profiling.ProfilerMarker("FindSlotsForEntries").Auto();
// This is not great, but the alternative is making the always in memory m_IndexChunks bigger.
// The other alternative is to temporary mark m_IndexChunks and unmark, but that is going to be slower.
// The copy here is temporary and while it is created upon loading all the time, it is going to occupy mnemory
// only when a load operation happens.
m_IndexChunksCopyForChecks.SetAll(false);
m_IndexChunksCopyForChecks.Or(m_IndexChunks);
int numberOfEntries = entriesInfo.Length;
for (int entry = 0; entry < numberOfEntries; ++entry)
{
entriesInfo[entry].firstChunkIndex = kEmptyIndex;
int numberOfChunksForEntry = entriesInfo[entry].numberOfChunks;
if (numberOfChunksForEntry == 0) continue;
for (int i = 0; i < m_ChunksCount - numberOfChunksForEntry; ++i)
{
if (!m_IndexChunksCopyForChecks[i])
{
int firstSlot = i, lastSlot = i + numberOfChunksForEntry;
while (i + 1 < lastSlot)
{
if (m_IndexChunksCopyForChecks[++i])
break;
}
if (!m_IndexChunksCopyForChecks[i])
{
entriesInfo[entry].firstChunkIndex = firstSlot;
break;
}
}
}
if (entriesInfo[entry].firstChunkIndex < 0)
{
for (int e = 0; e < numberOfEntries; ++e)
entriesInfo[e].firstChunkIndex = kFailChunkIndex;
return false;
}
// Sucessful allocation - We need to markup the copy.
for (int i = entriesInfo[entry].firstChunkIndex; i < (entriesInfo[entry].firstChunkIndex + numberOfChunksForEntry); ++i)
{
Debug.Assert(!m_IndexChunksCopyForChecks[i]);
m_IndexChunksCopyForChecks[i] = true;
}
}
return true;
}
internal bool ReserveChunks(IndirectionEntryUpdateInfo[] entriesInfo, bool ignoreErrorLog)
{
int entryCount = entriesInfo.Length;
// Sanity check that shouldn't be needed.
for (int entry = 0; entry < entryCount; ++entry)
{
int firstChunkForEntry = entriesInfo[entry].firstChunkIndex;
int numberOfChunkForEntry = entriesInfo[entry].numberOfChunks;
if (numberOfChunkForEntry == 0) continue;
if (firstChunkForEntry < 0)
{
if (!ignoreErrorLog)
Debug.LogError("APV Index Allocation failed.");
return false;
}
for (int i = firstChunkForEntry; i < (firstChunkForEntry + numberOfChunkForEntry); ++i)
{
Debug.Assert(!m_IndexChunks[i]);
m_IndexChunks[i] = true;
}
m_AvailableChunkCount -= numberOfChunkForEntry;
}
return true;
}
static internal bool BrickOverlapEntry(Vector3Int brickMin, Vector3Int brickMax, Vector3Int entryMin, Vector3Int entryMax)
{
return brickMax.x > entryMin.x && entryMax.x > brickMin.x &&
brickMax.y > entryMin.y && entryMax.y > brickMin.y &&
brickMax.z > entryMin.z && entryMax.z > brickMin.z;
}
static int LocationToIndex(int x, int y, int z, Vector3Int sizeOfValid)
{
return z * (sizeOfValid.x * sizeOfValid.y) + x * sizeOfValid.y + y;
}
void MarkBrickInPhysicalBuffer(in IndirectionEntryUpdateInfo entry, Vector3Int brickMin, Vector3Int brickMax, int brickSubdivLevel, int entrySubdivLevel, int idx)
{
m_NeedUpdateIndexComputeBuffer = true;
// An indirection entry might have only a single brick that is actually bigger than the entry itself. This is a bit of simpler use case
// that doesn't fit what happens otherwise in this function where the assumption is that minSubdivInCell is equal or less the size of the entry.
// In this special case, we can do things much simpler as we *know* by construction that we will always have only a single relevant brick
// and so we do the update in a simpler fashion.
if (entry.hasOnlyBiggerBricks)
{
int singleEntry = entry.firstChunkIndex * kIndexChunkSize;
m_UpdateMinIndex = Math.Min(m_UpdateMinIndex, singleEntry);
m_UpdateMaxIndex = Math.Max(m_UpdateMaxIndex, singleEntry);
m_PhysicalIndexBufferData[singleEntry] = idx;
}
else
{
int minBrickSize = ProbeReferenceVolume.CellSize(entry.minSubdivInCell);
// Map the brick to the voxel, essentially the inverse of GetIndexData in hlsl
// The size of valid data in the entry might be smaller than the entry size
var entryMinIndex = entry.minValidBrickIndexForCellAtMaxRes / minBrickSize;
var entryMaxIndex = entry.maxValidBrickIndexForCellAtMaxResPlusOne / minBrickSize;
var sizeOfValid = (entryMaxIndex - entryMinIndex);
if (brickSubdivLevel >= entrySubdivLevel)
{
brickMin = Vector3Int.zero;
brickMax = sizeOfValid;
}
else
{
// We need to do our calculations in local space to the cell, so we move the brick to local space as a first step.
// Reminder that at this point we are still operating at highest resolution possible, not necessarily the one that will be
// the final resolution for the chunk.
brickMin -= entry.entryPositionInBricksAtMaxRes;
brickMax -= entry.entryPositionInBricksAtMaxRes;
// Since the index is spurious (not same resolution, but varying per cell) we need to bring to the output resolution the brick coordinates
// Before finding the locations inside the Index for the current cell/chunk.
brickMin /= minBrickSize;
brickMax /= minBrickSize;
// Verify we are actually in local space now.
int maxCellSizeInOutputRes = ProbeReferenceVolume.CellSize(entrySubdivLevel - entry.minSubdivInCell);
Debug.Assert(brickMin.x >= 0 && brickMin.y >= 0 && brickMin.z >= 0, "Brick is out of bounds");
Debug.Assert(brickMax.x <= maxCellSizeInOutputRes && brickMax.y <= maxCellSizeInOutputRes && brickMax.z <= maxCellSizeInOutputRes, "Brick out of bounds");
// Then perform the rescale of the local indices for min and max.
brickMin -= entryMinIndex;
brickMax -= entryMinIndex;
}
// Analytically compute min and max because doing it in the inner loop with Math.Min/Max is costly (not inlined)
int chunkStart = entry.firstChunkIndex * kIndexChunkSize;
int newMin = chunkStart + LocationToIndex(brickMin.x, brickMin.y, brickMin.z, sizeOfValid);
int newMax = chunkStart + LocationToIndex(brickMax.x - 1, brickMax.y - 1, brickMax.z - 1, sizeOfValid);
m_UpdateMinIndex = Math.Min(m_UpdateMinIndex, newMin);
m_UpdateMaxIndex = Math.Max(m_UpdateMaxIndex, newMax);
// Loop through all touched voxels
for (int x = brickMin.x; x < brickMax.x; ++x)
{
for (int z = brickMin.z; z < brickMax.z; ++z)
{
for (int y = brickMin.y; y < brickMax.y; ++y)
{
int localFlatIdx = LocationToIndex(x, y, z, sizeOfValid);
m_PhysicalIndexBufferData[chunkStart + localFlatIdx] = idx;
}
}
}
}
}
public void AddBricks(CellIndexInfo cellInfo, NativeArray<Brick> bricks, List<Chunk> allocations, int allocationSize, int poolWidth, int poolHeight)
{
Debug.Assert(bricks.Length <= ushort.MaxValue, "Cannot add more than 65K bricks per RegId.");
// Updates the physical buffer
// Note that bricks in a cell are sorted with biggest subdivisions first in the list
// They are placed in the same order inside the chunks of the brick pool
// This can still be improved but is not the bottleneck currently
// Compute some stuff
var prv = ProbeReferenceVolume.instance;
int entrySubdivLevel = prv.GetEntrySubdivLevel();
// Iterate over all bricks, while tracking allocated coords in the pool
int brick_idx = 0;
for (int i = 0; i < allocations.Count; i++)
{
Chunk alloc = allocations[i];
int last_brick = brick_idx + Mathf.Min(allocationSize, bricks.Length - brick_idx);
while (brick_idx != last_brick)
{
// Fetch brick and increment counters
Brick brick = bricks[brick_idx++];
int idx = MergeIndex(alloc.flattenIndex(poolWidth, poolHeight), brick.subdivisionLevel);
alloc.x += ProbeBrickPool.kBrickProbeCountPerDim;
// Brick bounds
int brickSize = ProbeReferenceVolume.CellSize(brick.subdivisionLevel);
Vector3Int brickMin = brick.position;
Vector3Int brickMax = brick.position + new Vector3Int(brickSize, brickSize, brickSize);
// Find all entries that this brick touch (usually only one, but several in case of bigger bricks)
foreach (var entry in cellInfo.updateInfo.entriesInfo)
{
// We might have the brick completely out of the entry. In those case, we must skip.
var minEntryPosition = entry.entryPositionInBricksAtMaxRes + entry.minValidBrickIndexForCellAtMaxRes;
var maxEntryPosition = entry.entryPositionInBricksAtMaxRes + entry.maxValidBrickIndexForCellAtMaxResPlusOne - Vector3Int.one;
if (BrickOverlapEntry(brickMin, brickMax, minEntryPosition, maxEntryPosition))
MarkBrickInPhysicalBuffer(entry, brickMin, brickMax, brick.subdivisionLevel, entrySubdivLevel, idx);
}
}
}
}
public void RemoveBricks(CellIndexInfo cellInfo)
{
// Clear allocated chunks
for (int e = 0; e < cellInfo.updateInfo.entriesInfo.Length; e++)
{
ref var entryInfo = ref cellInfo.updateInfo.entriesInfo[e];
if (entryInfo.firstChunkIndex < 0) continue;
for (int i = entryInfo.firstChunkIndex; i < (entryInfo.firstChunkIndex + entryInfo.numberOfChunks); ++i)
{
m_IndexChunks[i] = false;
}
m_AvailableChunkCount += entryInfo.numberOfChunks;
entryInfo.numberOfChunks = 0;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c1a832f1bbd6c0248844c604b55947b0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,862 @@
using System.Diagnostics;
using System.Collections.Generic;
using Unity.Profiling;
using Unity.Profiling.LowLevel;
using UnityEngine.Experimental.Rendering;
using Cell = UnityEngine.Rendering.ProbeReferenceVolume.Cell;
using CellStreamingScratchBuffer = UnityEngine.Rendering.ProbeReferenceVolume.CellStreamingScratchBuffer;
using CellStreamingScratchBufferLayout = UnityEngine.Rendering.ProbeReferenceVolume.CellStreamingScratchBufferLayout;
namespace UnityEngine.Rendering
{
internal class ProbeBrickPool
{
/// <summary>
/// Allocates all SH data texture arrays (L0/L1, optional L2), validity, sky occlusion,
/// sky shading direction, probe occlusion, and rendering layer textures based on the
/// memory budget and enabled feature set.
/// </summary>
static readonly ProfilerMarker k_CreateProbeBrickPool =
new ProfilerMarker(ProfilerCategory.Render, "Create ProbeBrickPool",
MarkerFlags.VerbosityAdvanced);
internal static readonly int _Out_L0_L1Rx = Shader.PropertyToID("_Out_L0_L1Rx");
internal static readonly int _Out_L1G_L1Ry = Shader.PropertyToID("_Out_L1G_L1Ry");
internal static readonly int _Out_L1B_L1Rz = Shader.PropertyToID("_Out_L1B_L1Rz");
internal static readonly int _Out_Shared = Shader.PropertyToID("_Out_Shared");
internal static readonly int _Out_ProbeOcclusion = Shader.PropertyToID("_Out_ProbeOcclusion");
internal static readonly int _Out_SkyOcclusionL0L1 = Shader.PropertyToID("_Out_SkyOcclusionL0L1");
internal static readonly int _Out_SkyShadingDirectionIndices = Shader.PropertyToID("_Out_SkyShadingDirectionIndices");
internal static readonly int _Out_L2_0 = Shader.PropertyToID("_Out_L2_0");
internal static readonly int _Out_L2_1 = Shader.PropertyToID("_Out_L2_1");
internal static readonly int _Out_L2_2 = Shader.PropertyToID("_Out_L2_2");
internal static readonly int _Out_L2_3 = Shader.PropertyToID("_Out_L2_3");
internal static readonly int _ProbeVolumeScratchBufferLayout = Shader.PropertyToID(nameof(ProbeReferenceVolume.CellStreamingScratchBufferLayout));
internal static readonly int _ProbeVolumeScratchBuffer= Shader.PropertyToID("_ScratchBuffer");
internal static int DivRoundUp(int x, int y) => (x + y - 1) / y;
const int kChunkSizeInBricks = 128;
[DebuggerDisplay("Chunk ({x}, {y}, {z})")]
public struct BrickChunkAlloc
{
public int x, y, z;
internal int flattenIndex(int sx, int sy) { return z * (sx * sy) + y * sx + x; }
}
public struct DataLocation
{
internal Texture TexL0_L1rx;
internal Texture TexL1_G_ry;
internal Texture TexL1_B_rz;
internal Texture TexL2_0;
internal Texture TexL2_1;
internal Texture TexL2_2;
internal Texture TexL2_3;
internal Texture TexProbeOcclusion;
internal Texture TexValidity;
internal Texture TexSkyOcclusion;
internal Texture TexSkyShadingDirectionIndices;
internal int width;
internal int height;
internal int depth;
internal void Cleanup()
{
CoreUtils.Destroy(TexL0_L1rx);
CoreUtils.Destroy(TexL1_G_ry);
CoreUtils.Destroy(TexL1_B_rz);
CoreUtils.Destroy(TexL2_0);
CoreUtils.Destroy(TexL2_1);
CoreUtils.Destroy(TexL2_2);
CoreUtils.Destroy(TexL2_3);
CoreUtils.Destroy(TexProbeOcclusion);
CoreUtils.Destroy(TexValidity);
CoreUtils.Destroy(TexSkyOcclusion);
CoreUtils.Destroy(TexSkyShadingDirectionIndices);
TexL0_L1rx = null;
TexL1_G_ry = null;
TexL1_B_rz = null;
TexL2_0 = null;
TexL2_1 = null;
TexL2_2 = null;
TexL2_3 = null;
TexProbeOcclusion = null;
TexValidity = null;
TexSkyOcclusion = null;
TexSkyShadingDirectionIndices = null;
}
}
internal const int kBrickCellCount = 3;
internal const int kBrickProbeCountPerDim = kBrickCellCount + 1;
internal const int kBrickProbeCountTotal = kBrickProbeCountPerDim * kBrickProbeCountPerDim * kBrickProbeCountPerDim;
internal const int kChunkProbeCountPerDim = kChunkSizeInBricks * kBrickProbeCountPerDim;
internal int estimatedVMemCost { get; private set; }
const int kMaxPoolWidth = 1 << 11; // 2048 texels is a d3d11 limit for tex3d in all dimensions
internal DataLocation m_Pool; // internal to access it from blending pool only
BrickChunkAlloc m_NextFreeChunk;
Stack<BrickChunkAlloc> m_FreeList;
int m_AvailableChunkCount;
ProbeVolumeSHBands m_SHBands;
bool m_ContainsValidity;
bool m_ContainsProbeOcclusion;
bool m_ContainsRenderingLayers;
bool m_ContainsSkyOcclusion;
bool m_ContainsSkyShadingDirection;
static ComputeShader s_DataUploadCS;
static int s_DataUploadKernel;
static ComputeShader s_DataUploadL2CS;
static int s_DataUploadL2Kernel;
static LocalKeyword s_DataUpload_Shared;
static LocalKeyword s_DataUpload_ProbeOcclusion;
static LocalKeyword s_DataUpload_SkyOcclusion;
static LocalKeyword s_DataUpload_SkyShadingDirection;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
s_DataUploadCS = null;
s_DataUploadKernel = -1;
s_DataUploadL2CS = null;
s_DataUploadL2Kernel = -1;
s_DataUpload_Shared = default;
s_DataUpload_ProbeOcclusion = default;
s_DataUpload_SkyOcclusion = default;
s_DataUpload_SkyShadingDirection = default;
}
#endif
internal static void Initialize()
{
if (!SystemInfo.supportsComputeShaders)
return;
s_DataUploadCS = GraphicsSettings.GetRenderPipelineSettings<ProbeVolumeRuntimeResources>()?.probeVolumeUploadDataCS;
s_DataUploadL2CS = GraphicsSettings.GetRenderPipelineSettings<ProbeVolumeRuntimeResources>()?.probeVolumeUploadDataL2CS;
if (s_DataUploadCS != null)
{
s_DataUploadKernel = s_DataUploadCS ? s_DataUploadCS.FindKernel("UploadData") : -1;
s_DataUpload_Shared = new LocalKeyword(s_DataUploadCS, "PROBE_VOLUMES_SHARED_DATA");
s_DataUpload_ProbeOcclusion = new LocalKeyword(s_DataUploadCS, "PROBE_VOLUMES_PROBE_OCCLUSION");
s_DataUpload_SkyOcclusion = new LocalKeyword(s_DataUploadCS, "PROBE_VOLUMES_SKY_OCCLUSION");
s_DataUpload_SkyShadingDirection = new LocalKeyword(s_DataUploadCS, "PROBE_VOLUMES_SKY_SHADING_DIRECTION");
}
if (s_DataUploadL2CS != null)
{
s_DataUploadL2Kernel = s_DataUploadL2CS ? s_DataUploadL2CS.FindKernel("UploadDataL2") : -1;
}
}
internal Texture GetValidityTexture()
{
return m_Pool.TexValidity;
}
internal Texture GetSkyOcclusionTexture()
{
return m_Pool.TexSkyOcclusion;
}
internal Texture GetSkyShadingDirectionIndicesTexture()
{
return m_Pool.TexSkyShadingDirectionIndices;
}
internal Texture GetProbeOcclusionTexture()
{
return m_Pool.TexProbeOcclusion;
}
internal ProbeBrickPool(ProbeVolumeTextureMemoryBudget memoryBudget, ProbeVolumeSHBands shBands, bool allocateValidityData = false, bool allocateRenderingLayerData = false, bool allocateSkyOcclusion = false, bool allocateSkyShadingData = false, bool allocateProbeOcclusionData = false)
{
using var _ = k_CreateProbeBrickPool.Auto();
m_NextFreeChunk.x = m_NextFreeChunk.y = m_NextFreeChunk.z = 0;
m_SHBands = shBands;
m_ContainsValidity = allocateValidityData;
m_ContainsProbeOcclusion = allocateProbeOcclusionData;
m_ContainsRenderingLayers = allocateRenderingLayerData;
m_ContainsSkyOcclusion = allocateSkyOcclusion;
m_ContainsSkyShadingDirection = allocateSkyShadingData;
m_FreeList = new Stack<BrickChunkAlloc>(256);
DerivePoolSizeFromBudget(memoryBudget, out int width, out int height, out int depth);
AllocatePool(width, height, depth);
m_AvailableChunkCount = (m_Pool.width / (kChunkSizeInBricks * kBrickProbeCountPerDim)) * (m_Pool.height / kBrickProbeCountPerDim) * (m_Pool.depth / kBrickProbeCountPerDim);
}
internal void AllocatePool(int width, int height, int depth)
{
m_Pool = CreateDataLocation(width * height * depth, false, m_SHBands, "APV", true,
m_ContainsValidity, m_ContainsRenderingLayers, m_ContainsSkyOcclusion, m_ContainsSkyShadingDirection, m_ContainsProbeOcclusion, out int estimatedCost);
estimatedVMemCost = estimatedCost;
}
public int GetRemainingChunkCount()
{
return m_AvailableChunkCount;
}
internal void EnsureTextureValidity()
{
// We assume that if a texture is null, all of them are. In any case we reboot them altogether.
if (m_Pool.TexL0_L1rx == null)
{
m_Pool.Cleanup();
AllocatePool(m_Pool.width, m_Pool.height, m_Pool.depth);
}
}
internal bool EnsureTextureValidity(bool renderingLayers, bool skyOcclusion, bool skyDirection, bool probeOcclusion)
{
if (m_ContainsRenderingLayers != renderingLayers || m_ContainsSkyOcclusion != skyOcclusion || m_ContainsSkyShadingDirection != skyDirection || m_ContainsProbeOcclusion != probeOcclusion)
{
m_Pool.Cleanup();
m_ContainsRenderingLayers = renderingLayers;
m_ContainsSkyOcclusion = skyOcclusion;
m_ContainsSkyShadingDirection = skyDirection;
m_ContainsProbeOcclusion = probeOcclusion;
AllocatePool(m_Pool.width, m_Pool.height, m_Pool.depth);
return false;
}
return true;
}
internal static int GetChunkSizeInBrickCount() { return kChunkSizeInBricks; }
internal static int GetChunkSizeInProbeCount() { return kChunkSizeInBricks * kBrickProbeCountTotal; }
internal int GetPoolWidth() { return m_Pool.width; }
internal int GetPoolHeight() { return m_Pool.height; }
internal Vector3Int GetPoolDimensions() { return new Vector3Int(m_Pool.width, m_Pool.height, m_Pool.depth); }
internal void GetRuntimeResources(ref ProbeReferenceVolume.RuntimeResources rr)
{
rr.L0_L1rx = m_Pool.TexL0_L1rx as RenderTexture;
rr.L1_G_ry = m_Pool.TexL1_G_ry as RenderTexture;
rr.L1_B_rz = m_Pool.TexL1_B_rz as RenderTexture;
rr.L2_0 = m_Pool.TexL2_0 as RenderTexture;
rr.L2_1 = m_Pool.TexL2_1 as RenderTexture;
rr.L2_2 = m_Pool.TexL2_2 as RenderTexture;
rr.L2_3 = m_Pool.TexL2_3 as RenderTexture;
rr.ProbeOcclusion = m_Pool.TexProbeOcclusion as RenderTexture;
rr.Validity = m_Pool.TexValidity as RenderTexture;
rr.SkyOcclusionL0L1 = m_Pool.TexSkyOcclusion as RenderTexture;
rr.SkyShadingDirectionIndices = m_Pool.TexSkyShadingDirectionIndices as RenderTexture;
}
internal void Clear()
{
m_FreeList.Clear();
m_NextFreeChunk.x = m_NextFreeChunk.y = m_NextFreeChunk.z = 0;
}
internal static int GetChunkCount(int brickCount)
{
int chunkSize = kChunkSizeInBricks;
return (brickCount + chunkSize - 1) / chunkSize;
}
internal bool Allocate(int numberOfBrickChunks, List<BrickChunkAlloc> outAllocations, bool ignoreErrorLog)
{
while (m_FreeList.Count > 0 && numberOfBrickChunks > 0)
{
outAllocations.Add(m_FreeList.Pop());
numberOfBrickChunks--;
m_AvailableChunkCount--;
}
for (uint i = 0; i < numberOfBrickChunks; i++)
{
if (m_NextFreeChunk.z >= m_Pool.depth)
{
// During baking we know we can hit this when trying to do dilation of all cells at the same time.
// We don't want controlled error message spam during baking so we ignore it.
// In theory this should never happen with proper streaming/defrag but we keep the message just in case otherwise.
if (!ignoreErrorLog)
Debug.LogError("Cannot allocate more brick chunks, probe volume brick pool is full.");
Deallocate(outAllocations);
outAllocations.Clear();
return false; // failure case, pool is full
}
outAllocations.Add(m_NextFreeChunk);
m_AvailableChunkCount--;
m_NextFreeChunk.x += kChunkSizeInBricks * kBrickProbeCountPerDim;
if (m_NextFreeChunk.x >= m_Pool.width)
{
m_NextFreeChunk.x = 0;
m_NextFreeChunk.y += kBrickProbeCountPerDim;
if (m_NextFreeChunk.y >= m_Pool.height)
{
m_NextFreeChunk.y = 0;
m_NextFreeChunk.z += kBrickProbeCountPerDim;
}
}
}
return true;
}
internal void Deallocate(List<BrickChunkAlloc> allocations)
{
m_AvailableChunkCount += allocations.Count;
foreach (var brick in allocations)
m_FreeList.Push(brick);
}
internal void Update(DataLocation source, List<BrickChunkAlloc> srcLocations, List<BrickChunkAlloc> dstLocations, int destStartIndex, ProbeVolumeSHBands bands)
{
for (int i = 0; i < srcLocations.Count; i++)
{
BrickChunkAlloc src = srcLocations[i];
BrickChunkAlloc dst = dstLocations[destStartIndex + i];
for (int j = 0; j < kBrickProbeCountPerDim; j++)
{
int width = Mathf.Min(kChunkSizeInBricks * kBrickProbeCountPerDim, source.width - src.x);
Graphics.CopyTexture(source.TexL0_L1rx, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexL0_L1rx, dst.z + j, 0, dst.x, dst.y);
Graphics.CopyTexture(source.TexL1_G_ry, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexL1_G_ry, dst.z + j, 0, dst.x, dst.y);
Graphics.CopyTexture(source.TexL1_B_rz, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexL1_B_rz, dst.z + j, 0, dst.x, dst.y);
if (m_ContainsValidity)
Graphics.CopyTexture(source.TexValidity, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexValidity, dst.z + j, 0, dst.x, dst.y);
if (m_ContainsSkyOcclusion)
{
Graphics.CopyTexture(source.TexSkyOcclusion, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexSkyOcclusion, dst.z + j, 0, dst.x, dst.y);
if (m_ContainsSkyShadingDirection)
{
Graphics.CopyTexture(source.TexSkyShadingDirectionIndices, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexSkyShadingDirectionIndices, dst.z + j, 0, dst.x, dst.y);
}
}
if (bands == ProbeVolumeSHBands.SphericalHarmonicsL2)
{
Graphics.CopyTexture(source.TexL2_0, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexL2_0, dst.z + j, 0, dst.x, dst.y);
Graphics.CopyTexture(source.TexL2_1, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexL2_1, dst.z + j, 0, dst.x, dst.y);
Graphics.CopyTexture(source.TexL2_2, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexL2_2, dst.z + j, 0, dst.x, dst.y);
Graphics.CopyTexture(source.TexL2_3, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexL2_3, dst.z + j, 0, dst.x, dst.y);
}
if (m_ContainsProbeOcclusion)
{
Graphics.CopyTexture(source.TexProbeOcclusion, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexProbeOcclusion, dst.z + j, 0, dst.x, dst.y);
}
}
}
}
internal void Update(CommandBuffer cmd, CellStreamingScratchBuffer dataBuffer, CellStreamingScratchBufferLayout layout,
List<BrickChunkAlloc> dstLocations, bool updateSharedData, Texture validityTexture, ProbeVolumeSHBands bands,
bool skyOcclusion, Texture skyOcclusionTexture, bool skyShadingDirections, Texture skyShadingDirectionsTexture, bool probeOcclusion)
{
using (new ProfilingScope(cmd, CoreProfilingSamplers.APVDiskStreamingUpdatePool, m_Pool.TexL0_L1rx))
{
int chunkCount = dstLocations.Count;
cmd.SetComputeTextureParam(s_DataUploadCS, s_DataUploadKernel, _Out_L0_L1Rx, m_Pool.TexL0_L1rx);
cmd.SetComputeTextureParam(s_DataUploadCS, s_DataUploadKernel, _Out_L1G_L1Ry, m_Pool.TexL1_G_ry);
cmd.SetComputeTextureParam(s_DataUploadCS, s_DataUploadKernel, _Out_L1B_L1Rz, m_Pool.TexL1_B_rz);
if (updateSharedData)
{
cmd.EnableKeyword(s_DataUploadCS, s_DataUpload_Shared);
cmd.SetComputeTextureParam(s_DataUploadCS, s_DataUploadKernel, _Out_Shared, validityTexture);
if (skyOcclusion)
{
cmd.EnableKeyword(s_DataUploadCS, s_DataUpload_SkyOcclusion);
cmd.SetComputeTextureParam(s_DataUploadCS, s_DataUploadKernel, _Out_SkyOcclusionL0L1, skyOcclusionTexture);
if (skyShadingDirections)
{
cmd.SetComputeTextureParam(s_DataUploadCS, s_DataUploadKernel, _Out_SkyShadingDirectionIndices, skyShadingDirectionsTexture);
cmd.EnableKeyword(s_DataUploadCS, s_DataUpload_SkyShadingDirection);
}
else
cmd.DisableKeyword(s_DataUploadCS, s_DataUpload_SkyShadingDirection);
}
}
else
{
cmd.DisableKeyword(s_DataUploadCS, s_DataUpload_Shared);
cmd.DisableKeyword(s_DataUploadCS, s_DataUpload_SkyOcclusion);
cmd.DisableKeyword(s_DataUploadCS, s_DataUpload_SkyShadingDirection);
}
if (bands == ProbeVolumeSHBands.SphericalHarmonicsL2)
{
cmd.SetComputeTextureParam(s_DataUploadL2CS, s_DataUploadL2Kernel, _Out_L2_0, m_Pool.TexL2_0);
cmd.SetComputeTextureParam(s_DataUploadL2CS, s_DataUploadL2Kernel, _Out_L2_1, m_Pool.TexL2_1);
cmd.SetComputeTextureParam(s_DataUploadL2CS, s_DataUploadL2Kernel, _Out_L2_2, m_Pool.TexL2_2);
cmd.SetComputeTextureParam(s_DataUploadL2CS, s_DataUploadL2Kernel, _Out_L2_3, m_Pool.TexL2_3);
}
if (probeOcclusion)
{
cmd.EnableKeyword(s_DataUploadCS, s_DataUpload_ProbeOcclusion);
cmd.SetComputeTextureParam(s_DataUploadCS, s_DataUploadKernel, _Out_ProbeOcclusion, m_Pool.TexProbeOcclusion);
}
else
{
cmd.DisableKeyword(s_DataUploadCS, s_DataUpload_ProbeOcclusion);
}
const int numthreads = 64;
const int probePerThread = 4; // We can upload 4 probes per thread in the current shader.
int threadX = DivRoundUp(kChunkSizeInBricks * kBrickProbeCountTotal / probePerThread, numthreads);
ConstantBuffer.Push(cmd, layout, s_DataUploadCS, _ProbeVolumeScratchBufferLayout);
cmd.SetComputeBufferParam(s_DataUploadCS, s_DataUploadKernel, _ProbeVolumeScratchBuffer, dataBuffer.buffer);
cmd.DispatchCompute(s_DataUploadCS, s_DataUploadKernel, threadX, 1, chunkCount);
if (bands == ProbeVolumeSHBands.SphericalHarmonicsL2)
{
ConstantBuffer.Push(cmd, layout, s_DataUploadL2CS, _ProbeVolumeScratchBufferLayout);
cmd.SetComputeBufferParam(s_DataUploadL2CS, s_DataUploadL2Kernel, _ProbeVolumeScratchBuffer, dataBuffer.buffer);
cmd.DispatchCompute(s_DataUploadL2CS, s_DataUploadL2Kernel, threadX, 1, chunkCount);
}
}
}
internal void UpdateValidity(DataLocation source, List<BrickChunkAlloc> srcLocations, List<BrickChunkAlloc> dstLocations, int destStartIndex)
{
Debug.Assert(m_ContainsValidity);
for (int i = 0; i < srcLocations.Count; i++)
{
BrickChunkAlloc src = srcLocations[i];
BrickChunkAlloc dst = dstLocations[destStartIndex + i];
for (int j = 0; j < kBrickProbeCountPerDim; j++)
{
int width = Mathf.Min(kChunkSizeInBricks * kBrickProbeCountPerDim, source.width - src.x);
Graphics.CopyTexture(source.TexValidity, src.z + j, 0, src.x, src.y, width, kBrickProbeCountPerDim, m_Pool.TexValidity, dst.z + j, 0, dst.x, dst.y);
}
}
}
internal static Vector3Int ProbeCountToDataLocSize(int numProbes)
{
Debug.Assert(numProbes != 0);
Debug.Assert(numProbes % kBrickProbeCountTotal == 0);
int numBricks = numProbes / kBrickProbeCountTotal;
int poolWidth = kMaxPoolWidth / kBrickProbeCountPerDim;
int width, height, depth;
depth = (numBricks + poolWidth * poolWidth - 1) / (poolWidth * poolWidth);
if (depth > 1)
width = height = poolWidth;
else
{
height = (numBricks + poolWidth - 1) / poolWidth;
if (height > 1)
width = poolWidth;
else
width = numBricks;
}
width *= kBrickProbeCountPerDim;
height *= kBrickProbeCountPerDim;
depth *= kBrickProbeCountPerDim;
return new Vector3Int(width, height, depth);
}
static int EstimateMemoryCost(int width, int height, int depth, GraphicsFormat format)
{
int elementSize = format == GraphicsFormat.R16G16B16A16_SFloat ? 8 :
format == GraphicsFormat.R8G8B8A8_UNorm ? 4 : 1;
return (width * height * depth) * elementSize;
}
// Only computes the cost of textures allocated by the blending pool
internal static int EstimateMemoryCostForBlending(ProbeVolumeTextureMemoryBudget memoryBudget, bool compressed, ProbeVolumeSHBands bands)
{
if (memoryBudget == 0)
return 0;
DerivePoolSizeFromBudget(memoryBudget, out int width, out int height, out int depth);
Vector3Int locSize = ProbeCountToDataLocSize(width * height * depth);
width = locSize.x;
height = locSize.y;
depth = locSize.z;
int allocatedBytes = 0;
var L0Format = GraphicsFormat.R16G16B16A16_SFloat;
var L1L2Format = compressed ? GraphicsFormat.RGBA_BC7_UNorm : GraphicsFormat.R8G8B8A8_UNorm;
allocatedBytes += EstimateMemoryCost(width, height, depth, L0Format);
allocatedBytes += EstimateMemoryCost(width, height, depth, L1L2Format) * 2;
if (bands == ProbeVolumeSHBands.SphericalHarmonicsL2)
allocatedBytes += EstimateMemoryCost(width, height, depth, L1L2Format) * 3;
return allocatedBytes;
}
public static Texture CreateDataTexture(int width, int height, int depth, GraphicsFormat format, string name, bool allocateRendertexture, ref int allocatedBytes)
{
allocatedBytes += EstimateMemoryCost(width, height, depth, format);
Texture texture;
if (allocateRendertexture)
{
texture = new RenderTexture(new RenderTextureDescriptor()
{
width = width,
height = height,
volumeDepth = depth,
graphicsFormat = format,
mipCount = 1,
enableRandomWrite = SystemInfo.supportsComputeShaders,
dimension = TextureDimension.Tex3D,
msaaSamples = 1,
});
}
else
texture = new Texture3D(width, height, depth, format, TextureCreationFlags.None, 1);
texture.hideFlags = HideFlags.HideAndDontSave;
texture.name = name;
if (allocateRendertexture)
(texture as RenderTexture).Create();
return texture;
}
public static DataLocation CreateDataLocation(int numProbes, bool compressed, ProbeVolumeSHBands bands, string name, bool allocateRendertexture,
bool allocateValidityData, bool allocateRenderingLayers, bool allocateSkyOcclusionData, bool allocateSkyShadingDirectionData, bool allocateProbeOcclusionData, out int allocatedBytes)
{
Vector3Int locSize = ProbeCountToDataLocSize(numProbes);
int width = locSize.x;
int height = locSize.y;
int depth = locSize.z;
DataLocation loc;
var L0Format = GraphicsFormat.R16G16B16A16_SFloat;
var L1L2Format = compressed ? GraphicsFormat.RGBA_BC7_UNorm : GraphicsFormat.R8G8B8A8_UNorm;
var ValidityFormat = allocateRenderingLayers ?
// for 32 bits we use a float format but it's an uint
GraphicsFormat.R32_SFloat :
// NOTE: Platforms that do not support Sample nor LoadStore for R8_UNorm need to fallback to RGBA8_UNorm since that format should be supported for both (e.g. GLES3.x)
SystemInfo.IsFormatSupported(GraphicsFormat.R8_UNorm, GraphicsFormatUsage.Sample | GraphicsFormatUsage.LoadStore) ? GraphicsFormat.R8_UNorm : GraphicsFormat.R8G8B8A8_UNorm;
allocatedBytes = 0;
loc.TexL0_L1rx = CreateDataTexture(width, height, depth, L0Format, $"{name}_TexL0_L1rx", allocateRendertexture, ref allocatedBytes);
loc.TexL1_G_ry = CreateDataTexture(width, height, depth, L1L2Format, $"{name}_TexL1_G_ry", allocateRendertexture, ref allocatedBytes);
loc.TexL1_B_rz = CreateDataTexture(width, height, depth, L1L2Format, $"{name}_TexL1_B_rz", allocateRendertexture, ref allocatedBytes);
if (allocateValidityData)
loc.TexValidity = CreateDataTexture(width, height, depth, ValidityFormat, $"{name}_Validity", allocateRendertexture, ref allocatedBytes);
else
loc.TexValidity = null;
if (allocateSkyOcclusionData)
loc.TexSkyOcclusion = CreateDataTexture(width, height, depth, GraphicsFormat.R16G16B16A16_SFloat, $"{name}_SkyOcclusion", allocateRendertexture, ref allocatedBytes);
else
loc.TexSkyOcclusion = null;
if (allocateSkyShadingDirectionData)
loc.TexSkyShadingDirectionIndices = CreateDataTexture(width, height, depth, GraphicsFormat.R8_UNorm, $"{name}_SkyShadingDirectionIndices", allocateRendertexture, ref allocatedBytes);
else
loc.TexSkyShadingDirectionIndices = null;
if (allocateProbeOcclusionData)
loc.TexProbeOcclusion = CreateDataTexture(width, height, depth, GraphicsFormat.R8G8B8A8_UNorm, $"{name}_ProbeOcclusion", allocateRendertexture, ref allocatedBytes);
else
loc.TexProbeOcclusion = null;
if (bands == ProbeVolumeSHBands.SphericalHarmonicsL2)
{
loc.TexL2_0 = CreateDataTexture(width, height, depth, L1L2Format, $"{name}_TexL2_0", allocateRendertexture, ref allocatedBytes);
loc.TexL2_1 = CreateDataTexture(width, height, depth, L1L2Format, $"{name}_TexL2_1", allocateRendertexture, ref allocatedBytes);
loc.TexL2_2 = CreateDataTexture(width, height, depth, L1L2Format, $"{name}_TexL2_2", allocateRendertexture, ref allocatedBytes);
loc.TexL2_3 = CreateDataTexture(width, height, depth, L1L2Format, $"{name}_TexL2_3", allocateRendertexture, ref allocatedBytes);
}
else
{
loc.TexL2_0 = null;
loc.TexL2_1 = null;
loc.TexL2_2 = null;
loc.TexL2_3 = null;
}
loc.width = width;
loc.height = height;
loc.depth = depth;
return loc;
}
static void DerivePoolSizeFromBudget(ProbeVolumeTextureMemoryBudget memoryBudget, out int width, out int height, out int depth)
{
// TODO: This is fairly simplistic for now and relies on the enum to have the value set to the desired numbers,
// might change the heuristic later on.
width = (int)memoryBudget;
height = (int)memoryBudget;
depth = kBrickProbeCountPerDim;
}
internal void Cleanup()
{
m_Pool.Cleanup();
}
}
internal class ProbeBrickBlendingPool
{
static ComputeShader stateBlendShader;
static int scenarioBlendingKernel = -1;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
stateBlendShader = null;
scenarioBlendingKernel = -1;
}
#endif
static readonly int _PoolDim_LerpFactor = Shader.PropertyToID("_PoolDim_LerpFactor");
static readonly int _ChunkList = Shader.PropertyToID("_ChunkList");
static readonly int _State0_L0_L1Rx = Shader.PropertyToID("_State0_L0_L1Rx");
static readonly int _State0_L1G_L1Ry = Shader.PropertyToID("_State0_L1G_L1Ry");
static readonly int _State0_L1B_L1Rz = Shader.PropertyToID("_State0_L1B_L1Rz");
static readonly int _State0_L2_0 = Shader.PropertyToID("_State0_L2_0");
static readonly int _State0_L2_1 = Shader.PropertyToID("_State0_L2_1");
static readonly int _State0_L2_2 = Shader.PropertyToID("_State0_L2_2");
static readonly int _State0_L2_3 = Shader.PropertyToID("_State0_L2_3");
static readonly int _State0_ProbeOcclusion = Shader.PropertyToID("_State0_ProbeOcclusion");
static readonly int _State1_L0_L1Rx = Shader.PropertyToID("_State1_L0_L1Rx");
static readonly int _State1_L1G_L1Ry = Shader.PropertyToID("_State1_L1G_L1Ry");
static readonly int _State1_L1B_L1Rz = Shader.PropertyToID("_State1_L1B_L1Rz");
static readonly int _State1_L2_0 = Shader.PropertyToID("_State1_L2_0");
static readonly int _State1_L2_1 = Shader.PropertyToID("_State1_L2_1");
static readonly int _State1_L2_2 = Shader.PropertyToID("_State1_L2_2");
static readonly int _State1_L2_3 = Shader.PropertyToID("_State1_L2_3");
static readonly int _State1_ProbeOcclusion = Shader.PropertyToID("_State1_ProbeOcclusion");
internal static void Initialize()
{
if (SystemInfo.supportsComputeShaders)
{
stateBlendShader = GraphicsSettings.GetRenderPipelineSettings<ProbeVolumeRuntimeResources>()?.probeVolumeBlendStatesCS;
scenarioBlendingKernel = stateBlendShader ? stateBlendShader.FindKernel("BlendScenarios") : -1;
}
}
Vector4[] m_ChunkList;
int m_MappedChunks;
ProbeBrickPool m_State0, m_State1;
ProbeVolumeTextureMemoryBudget m_MemoryBudget;
ProbeVolumeSHBands m_ShBands;
bool m_ProbeOcclusion;
internal bool isAllocated => m_State0 != null;
internal int estimatedVMemCost
{
get
{
if (!ProbeReferenceVolume.instance.supportScenarioBlending)
return 0;
if (isAllocated)
return m_State0.estimatedVMemCost + m_State1.estimatedVMemCost;
return ProbeBrickPool.EstimateMemoryCostForBlending(m_MemoryBudget, false, m_ShBands) * 2;
}
}
internal int GetPoolWidth() { return m_State0.m_Pool.width; }
internal int GetPoolHeight() { return m_State0.m_Pool.height; }
internal int GetPoolDepth() { return m_State0.m_Pool.depth; }
internal ProbeBrickBlendingPool(ProbeVolumeBlendingTextureMemoryBudget memoryBudget, ProbeVolumeSHBands shBands, bool probeOcclusion)
{
// Casting to other memory budget struct works cause it's casted to int in the end anyway
m_MemoryBudget = (ProbeVolumeTextureMemoryBudget)memoryBudget;
m_ShBands = shBands;
m_ProbeOcclusion = probeOcclusion;
}
internal void AllocateResourcesIfNeeded()
{
if (isAllocated)
return;
m_State0 = new ProbeBrickPool(m_MemoryBudget, m_ShBands, allocateProbeOcclusionData: m_ProbeOcclusion);
m_State1 = new ProbeBrickPool(m_MemoryBudget, m_ShBands, allocateProbeOcclusionData: m_ProbeOcclusion);
int maxAvailablebrickCount = (GetPoolWidth() / ProbeBrickPool.kChunkProbeCountPerDim)
* (GetPoolHeight() / ProbeBrickPool.kBrickProbeCountPerDim)
* (GetPoolDepth() / ProbeBrickPool.kBrickProbeCountPerDim);
m_ChunkList = new Vector4[maxAvailablebrickCount];
m_MappedChunks = 0;
}
internal void Update(ProbeBrickPool.DataLocation source, List<ProbeBrickPool.BrickChunkAlloc> srcLocations, List<ProbeBrickPool.BrickChunkAlloc> dstLocations, int destStartIndex, ProbeVolumeSHBands bands, int state)
{
(state == 0 ? m_State0 : m_State1).Update(source, srcLocations, dstLocations, destStartIndex, bands);
}
internal void Update(CommandBuffer cmd, CellStreamingScratchBuffer dataBuffer, CellStreamingScratchBufferLayout layout,
List<ProbeBrickPool.BrickChunkAlloc> dstLocations, ProbeVolumeSHBands bands, int state, Texture validityTexture,
bool skyOcclusion, Texture skyOcclusionTexture, bool skyShadingDirections, Texture skyShadingDirectionsTexture, bool probeOcclusion)
{
bool updateShared = state == 0 ? true : false;
(state == 0 ? m_State0 : m_State1).Update(cmd, dataBuffer, layout, dstLocations,
updateShared, validityTexture, bands, updateShared && skyOcclusion, skyOcclusionTexture,
updateShared && skyShadingDirections, skyShadingDirectionsTexture, probeOcclusion);
}
internal void PerformBlending(CommandBuffer cmd, float factor, ProbeBrickPool dstPool)
{
if (m_MappedChunks == 0)
return;
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State0_L0_L1Rx, m_State0.m_Pool.TexL0_L1rx);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State0_L1G_L1Ry, m_State0.m_Pool.TexL1_G_ry);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State0_L1B_L1Rz, m_State0.m_Pool.TexL1_B_rz);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State1_L0_L1Rx, m_State1.m_Pool.TexL0_L1rx);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State1_L1G_L1Ry, m_State1.m_Pool.TexL1_G_ry);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State1_L1B_L1Rz, m_State1.m_Pool.TexL1_B_rz);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, ProbeBrickPool._Out_L0_L1Rx, dstPool.m_Pool.TexL0_L1rx);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, ProbeBrickPool._Out_L1G_L1Ry, dstPool.m_Pool.TexL1_G_ry);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, ProbeBrickPool._Out_L1B_L1Rz, dstPool.m_Pool.TexL1_B_rz);
if (m_ShBands == ProbeVolumeSHBands.SphericalHarmonicsL2)
{
stateBlendShader.EnableKeyword("PROBE_VOLUMES_L2");
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State0_L2_0, m_State0.m_Pool.TexL2_0);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State0_L2_1, m_State0.m_Pool.TexL2_1);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State0_L2_2, m_State0.m_Pool.TexL2_2);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State0_L2_3, m_State0.m_Pool.TexL2_3);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State1_L2_0, m_State1.m_Pool.TexL2_0);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State1_L2_1, m_State1.m_Pool.TexL2_1);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State1_L2_2, m_State1.m_Pool.TexL2_2);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State1_L2_3, m_State1.m_Pool.TexL2_3);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, ProbeBrickPool._Out_L2_0, dstPool.m_Pool.TexL2_0);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, ProbeBrickPool._Out_L2_1, dstPool.m_Pool.TexL2_1);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, ProbeBrickPool._Out_L2_2, dstPool.m_Pool.TexL2_2);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, ProbeBrickPool._Out_L2_3, dstPool.m_Pool.TexL2_3);
}
else
stateBlendShader.DisableKeyword("PROBE_VOLUMES_L2");
if (m_ProbeOcclusion)
{
stateBlendShader.EnableKeyword("USE_APV_PROBE_OCCLUSION");
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State0_ProbeOcclusion, m_State0.m_Pool.TexProbeOcclusion);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, _State1_ProbeOcclusion, m_State1.m_Pool.TexProbeOcclusion);
cmd.SetComputeTextureParam(stateBlendShader, scenarioBlendingKernel, ProbeBrickPool._Out_ProbeOcclusion, dstPool.m_Pool.TexProbeOcclusion);
}
else
stateBlendShader.DisableKeyword("USE_APV_PROBE_OCCLUSION");
var poolDim_LerpFactor = new Vector4(dstPool.GetPoolWidth(), dstPool.GetPoolHeight(), factor, 0.0f);
const int numthreads = 4;
int threadX = ProbeBrickPool.DivRoundUp(ProbeBrickPool.kChunkProbeCountPerDim, numthreads);
int threadY = ProbeBrickPool.DivRoundUp(ProbeBrickPool.kBrickProbeCountPerDim, numthreads);
int threadZ = ProbeBrickPool.DivRoundUp(ProbeBrickPool.kBrickProbeCountPerDim, numthreads);
cmd.SetComputeVectorArrayParam(stateBlendShader, _ChunkList, m_ChunkList);
cmd.SetComputeVectorParam(stateBlendShader, _PoolDim_LerpFactor, poolDim_LerpFactor);
cmd.DispatchCompute(stateBlendShader, scenarioBlendingKernel, threadX, threadY, threadZ * m_MappedChunks);
m_MappedChunks = 0;
}
internal void BlendChunks(Cell cell, ProbeBrickPool dstPool)
{
for (int c = 0; c < cell.blendingInfo.chunkList.Count; c++)
{
var chunk = cell.blendingInfo.chunkList[c];
int dst = cell.poolInfo.chunkList[c].flattenIndex(dstPool.GetPoolWidth(), dstPool.GetPoolHeight());
m_ChunkList[m_MappedChunks++] = new Vector4(chunk.x, chunk.y, chunk.z, dst);
}
}
internal void Clear()
=> m_State0?.Clear();
internal bool Allocate(int numberOfBrickChunks, List<ProbeBrickPool.BrickChunkAlloc> outAllocations)
{
AllocateResourcesIfNeeded();
if (numberOfBrickChunks > m_State0.GetRemainingChunkCount())
return false;
return m_State0.Allocate(numberOfBrickChunks, outAllocations, false);
}
internal void Deallocate(List<ProbeBrickPool.BrickChunkAlloc> allocations)
{
if (allocations.Count == 0)
return;
m_State0.Deallocate(allocations);
}
internal void EnsureTextureValidity()
{
if (isAllocated)
{
m_State0.EnsureTextureValidity();
m_State1.EnsureTextureValidity();
}
}
internal void Cleanup()
{
if (isAllocated)
{
m_State0.Cleanup();
m_State1.Cleanup();
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 079fb321dd4edfd42bee1376c8c48c05
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,209 @@
using System;
using CellIndexInfo = UnityEngine.Rendering.ProbeReferenceVolume.CellIndexInfo;
namespace UnityEngine.Rendering
{
internal class ProbeGlobalIndirection
{
const int kUintPerEntry = 3;
internal int estimatedVMemCost { get; private set; }
// IMPORTANT! IF THIS VALUE CHANGES DATA NEEDS TO BE REBAKED.
internal const int kEntryMaxSubdivLevel = 3;
internal struct IndexMetaData
{
static readonly uint[] s_PackedValues = new uint[kUintPerEntry];
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
Array.Clear(s_PackedValues, 0, s_PackedValues.Length);
}
#endif
internal Vector3Int minLocalIdx;
internal Vector3Int maxLocalIdxPlusOne;
internal int firstChunkIndex;
internal int minSubdiv;
internal void Pack(out uint[] vals)
{
vals = s_PackedValues;
for (int i = 0; i < kUintPerEntry; ++i)
{
vals[i] = 0;
}
// TODO: Note this packing is too generous, we can get rid of 1 uint
// minLocalIndex is in cell space so it has an upper bound
// first chunk index is also on 16bits max when using max memory budget
// see comment below about size of valid
//
// UINT 0:
// FirstChunkIndex 29 bit
// MinSubdiv 3 bit
// UINT 1:
// minLocalIdx.x 10 bit
// minLocalIdx.y 10 bit
// minLocalIdx.z 10 bit
// UINT 2:
// sizeOfValid.x 10 bit
// sizeOfValid.y 10 bit
// sizeOfValid.z 10 bit
// This is always less than CellSize(kEntryMaxSubdivLevel)+1 == 28. See GetEntrySubdivLevel()
var sizeOfValid = maxLocalIdxPlusOne - minLocalIdx;
vals[0] = (uint)firstChunkIndex & 0x1FFFFFFF;
vals[0] |= ((uint)minSubdiv & 0x7) << 29;
vals[1] = (uint)minLocalIdx.x & 0x3FF;
vals[1] |= ((uint)minLocalIdx.y & 0x3FF) << 10;
vals[1] |= ((uint)minLocalIdx.z & 0x3FF) << 20;
vals[2] = (uint)sizeOfValid.x & 0x3FF;
vals[2] |= ((uint)sizeOfValid.y & 0x3FF) << 10;
vals[2] |= ((uint)sizeOfValid.z & 0x3FF) << 20;
}
}
ComputeBuffer m_IndexOfIndicesBuffer;
uint[] m_IndexOfIndicesData;
int m_CellSizeInMinBricks;
Vector3Int m_EntriesCount;
Vector3Int m_EntryMin;
Vector3Int m_EntryMax;
internal void GetMinMaxEntry(out Vector3Int minEntry, out Vector3Int maxEntry)
{
minEntry = m_EntryMin;
maxEntry = m_EntryMax;
}
bool m_NeedUpdateComputeBuffer;
internal Vector3Int GetGlobalIndirectionDimension() => m_EntriesCount;
internal Vector3Int GetGlobalIndirectionMinEntry() => m_EntryMin;
int entrySizeInBricks => Mathf.Min((int)Mathf.Pow(ProbeBrickPool.kBrickCellCount, kEntryMaxSubdivLevel), m_CellSizeInMinBricks);
internal int entriesPerCellDimension => m_CellSizeInMinBricks / Mathf.Max(1, entrySizeInBricks);
int GetFlatIndex(Vector3Int normalizedPos)
{
return normalizedPos.z * (m_EntriesCount.x * m_EntriesCount.y) + normalizedPos.y * m_EntriesCount.x + normalizedPos.x;
}
internal ProbeGlobalIndirection(Vector3Int cellMin, Vector3Int cellMax, int cellSizeInMinBricks)
{
m_CellSizeInMinBricks = cellSizeInMinBricks;
Vector3Int cellCount = cellMax + Vector3Int.one - cellMin;
m_EntriesCount = cellCount * entriesPerCellDimension;
m_EntryMin = cellMin * entriesPerCellDimension;
m_EntryMax = (cellMax + Vector3Int.one) * entriesPerCellDimension - Vector3Int.one;
int flatEntryCount = m_EntriesCount.x * m_EntriesCount.y * m_EntriesCount.z;
int bufferSize = kUintPerEntry * flatEntryCount;
m_IndexOfIndicesBuffer = new ComputeBuffer(flatEntryCount, kUintPerEntry * sizeof(uint));
m_IndexOfIndicesData = new uint[bufferSize];
m_NeedUpdateComputeBuffer = false;
estimatedVMemCost = flatEntryCount * kUintPerEntry * sizeof(uint);
}
internal int GetFlatIdxForEntry(Vector3Int entryPosition)
{
Vector3Int normalizedPos = entryPosition - m_EntryMin;
Debug.Assert(normalizedPos.x >= 0 && normalizedPos.y >= 0 && normalizedPos.z >= 0);
return GetFlatIndex(normalizedPos);
}
internal int[] GetFlatIndicesForCell(Vector3Int cellPosition)
{
Vector3Int firstEntryPosition = cellPosition * entriesPerCellDimension;
int entriesPerCellDim = m_CellSizeInMinBricks / entrySizeInBricks;
int[] outListOfIndices = new int[entriesPerCellDimension * entriesPerCellDimension * entriesPerCellDimension];
int i = 0;
for (int x = 0; x < entriesPerCellDim; ++x)
{
for (int y = 0; y < entriesPerCellDim; ++y)
{
for (int z = 0; z < entriesPerCellDim; ++z)
{
outListOfIndices[i++] = GetFlatIdxForEntry(firstEntryPosition + new Vector3Int(x, y, z));
}
}
}
return outListOfIndices;
}
internal void UpdateCell(CellIndexInfo cellInfo)
{
for (int entry = 0; entry < cellInfo.flatIndicesInGlobalIndirection.Length; ++entry)
{
int entryIndex = cellInfo.flatIndicesInGlobalIndirection[entry];
ProbeBrickIndex.IndirectionEntryUpdateInfo entryUpdateInfo = cellInfo.updateInfo.entriesInfo[entry];
int minSubdivCellSize = ProbeReferenceVolume.CellSize(entryUpdateInfo.minSubdivInCell);
IndexMetaData metaData = new IndexMetaData();
metaData.minSubdiv = entryUpdateInfo.minSubdivInCell;
metaData.minLocalIdx = entryUpdateInfo.hasOnlyBiggerBricks ? Vector3Int.zero : entryUpdateInfo.minValidBrickIndexForCellAtMaxRes / minSubdivCellSize;
metaData.maxLocalIdxPlusOne = entryUpdateInfo.hasOnlyBiggerBricks ? Vector3Int.one : entryUpdateInfo.maxValidBrickIndexForCellAtMaxResPlusOne / minSubdivCellSize;
metaData.firstChunkIndex = entryUpdateInfo.firstChunkIndex;
metaData.Pack(out uint[] packedVals);
for (int i = 0; i < kUintPerEntry; ++i)
{
m_IndexOfIndicesData[entryIndex * kUintPerEntry + i] = packedVals[i];
}
}
m_NeedUpdateComputeBuffer = true;
}
internal void MarkEntriesAsUnloaded(int[] entriesFlatIndices)
{
for (int entry = 0; entry < entriesFlatIndices.Length; ++entry)
{
for (int i = 0; i < kUintPerEntry; ++i)
{
m_IndexOfIndicesData[entriesFlatIndices[entry] * kUintPerEntry + i] = 0xFFFFFFFF;
}
}
m_NeedUpdateComputeBuffer = true;
}
internal void PushComputeData()
{
m_IndexOfIndicesBuffer.SetData(m_IndexOfIndicesData);
m_NeedUpdateComputeBuffer = false;
}
internal void GetRuntimeResources(ref ProbeReferenceVolume.RuntimeResources rr)
{
// If we are pending an update of the actual compute buffer we do it here
if (m_NeedUpdateComputeBuffer)
{
PushComputeData();
}
rr.cellIndices = m_IndexOfIndicesBuffer;
}
internal void Cleanup()
{
CoreUtils.SafeRelease(m_IndexOfIndicesBuffer);
m_IndexOfIndicesBuffer = null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 58562d806ae1e3b4ba9cc4b895239782
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,149 @@
using System;
using UnityEngine.Rendering;
namespace UnityEngine.Rendering
{
public partial class ProbeReferenceVolume
{
internal static class ShaderIDs
{
// Adaptive Probe Volume
public static readonly int _APVResIndex = Shader.PropertyToID("_APVResIndex");
public static readonly int _APVResCellIndices = Shader.PropertyToID("_APVResCellIndices");
public static readonly int _APVResL0_L1Rx = Shader.PropertyToID("_APVResL0_L1Rx");
public static readonly int _APVResL1G_L1Ry = Shader.PropertyToID("_APVResL1G_L1Ry");
public static readonly int _APVResL1B_L1Rz = Shader.PropertyToID("_APVResL1B_L1Rz");
public static readonly int _APVResL2_0 = Shader.PropertyToID("_APVResL2_0");
public static readonly int _APVResL2_1 = Shader.PropertyToID("_APVResL2_1");
public static readonly int _APVResL2_2 = Shader.PropertyToID("_APVResL2_2");
public static readonly int _APVResL2_3 = Shader.PropertyToID("_APVResL2_3");
public static readonly int _APVProbeOcclusion = Shader.PropertyToID("_APVProbeOcclusion");
public static readonly int _APVResValidity = Shader.PropertyToID("_APVResValidity");
public static readonly int _SkyOcclusionTexL0L1 = Shader.PropertyToID("_SkyOcclusionTexL0L1");
public static readonly int _SkyShadingDirectionIndicesTex = Shader.PropertyToID("_SkyShadingDirectionIndicesTex");
public static readonly int _SkyPrecomputedDirections = Shader.PropertyToID("_SkyPrecomputedDirections");
public static readonly int _AntiLeakData = Shader.PropertyToID("_AntiLeakData");
}
ComputeBuffer m_EmptyIndexBuffer = null;
/// <summary>
/// Bind the global APV resources
/// </summary>
/// <param name="cmdBuffer">Command buffer</param>
/// <param name="isProbeVolumeEnabled">True if APV is enabled</param>
public void BindAPVRuntimeResources(CommandBuffer cmdBuffer, bool isProbeVolumeEnabled)
{
bool needToBindNeutral = true;
var refVolume = ProbeReferenceVolume.instance;
// Do this only if probe volume is enabled
if (isProbeVolumeEnabled && m_ProbeReferenceVolumeInit)
{
ProbeReferenceVolume.RuntimeResources rr = refVolume.GetRuntimeResources();
bool validResources = rr.index != null && rr.L0_L1rx != null && rr.L1_G_ry != null && rr.L1_B_rz != null;
validResources &= (refVolume.shBands == ProbeVolumeSHBands.SphericalHarmonicsL2 && rr.L2_0 != null) || refVolume.shBands == ProbeVolumeSHBands.SphericalHarmonicsL1;
if (validResources)
{
cmdBuffer.SetGlobalBuffer(ShaderIDs._APVResIndex, rr.index);
cmdBuffer.SetGlobalBuffer(ShaderIDs._APVResCellIndices, rr.cellIndices);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL0_L1Rx, rr.L0_L1rx);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL1G_L1Ry, rr.L1_G_ry);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL1B_L1Rz, rr.L1_B_rz);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResValidity, rr.Validity);
cmdBuffer.SetGlobalTexture(ShaderIDs._SkyOcclusionTexL0L1, rr.SkyOcclusionL0L1 ?? (RenderTargetIdentifier)CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalTexture(ShaderIDs._SkyShadingDirectionIndicesTex, rr.SkyShadingDirectionIndices ?? (RenderTargetIdentifier)CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalBuffer(ShaderIDs._SkyPrecomputedDirections, rr.SkyPrecomputedDirections);
cmdBuffer.SetGlobalBuffer(ShaderIDs._AntiLeakData, rr.QualityLeakReductionData);
if (refVolume.shBands == ProbeVolumeSHBands.SphericalHarmonicsL2)
{
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL2_0, rr.L2_0);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL2_1, rr.L2_1);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL2_2, rr.L2_2);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL2_3, rr.L2_3);
}
cmdBuffer.SetGlobalTexture(ShaderIDs._APVProbeOcclusion, rr.ProbeOcclusion ?? (RenderTargetIdentifier)CoreUtils.whiteVolumeTexture);
needToBindNeutral = false;
}
}
if (needToBindNeutral)
{
// Lazy init the empty buffer. We use sizeof(uint3) so that this buffer can be
// used with uint and uint3 bindings without triggering validation errors.
if (m_EmptyIndexBuffer == null)
m_EmptyIndexBuffer = new ComputeBuffer(1, sizeof(uint) * 3, ComputeBufferType.Structured);
cmdBuffer.SetGlobalBuffer(ShaderIDs._APVResIndex, m_EmptyIndexBuffer);
cmdBuffer.SetGlobalBuffer(ShaderIDs._APVResCellIndices, m_EmptyIndexBuffer);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL0_L1Rx, CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL1G_L1Ry, CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL1B_L1Rz, CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResValidity, CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalTexture(ShaderIDs._SkyOcclusionTexL0L1, CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalTexture(ShaderIDs._SkyShadingDirectionIndicesTex, CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalBuffer(ShaderIDs._SkyPrecomputedDirections, m_EmptyIndexBuffer);
cmdBuffer.SetGlobalBuffer(ShaderIDs._AntiLeakData, m_EmptyIndexBuffer);
if (refVolume.shBands == ProbeVolumeSHBands.SphericalHarmonicsL2)
{
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL2_0, CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL2_1, CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL2_2, CoreUtils.blackVolumeTexture);
cmdBuffer.SetGlobalTexture(ShaderIDs._APVResL2_3, CoreUtils.blackVolumeTexture);
}
cmdBuffer.SetGlobalTexture(ShaderIDs._APVProbeOcclusion, CoreUtils.whiteVolumeTexture);
}
}
/// <summary>
/// Update the constant buffer used by Probe Volumes in shaders.
/// </summary>
/// <param name="cmd">A command buffer used to perform the data update.</param>
/// <param name="probeVolumeOptions">probe volume options from the active volume stack</param>
/// <param name="taaFrameIndex">TAA frame index</param>
/// <param name="supportRenderingLayers">Are rendering layers supported</param>
/// <returns>True if successful</returns>
public bool UpdateShaderVariablesProbeVolumes(CommandBuffer cmd, ProbeVolumesOptions probeVolumeOptions, int taaFrameIndex, bool supportRenderingLayers = false)
{
bool enableProbeVolumes = DataHasBeenLoaded();
if (enableProbeVolumes)
{
ProbeVolumeShadingParameters parameters;
parameters.normalBias = probeVolumeOptions.normalBias.value;
parameters.viewBias = probeVolumeOptions.viewBias.value;
parameters.scaleBiasByMinDistanceBetweenProbes = probeVolumeOptions.scaleBiasWithMinProbeDistance.value;
parameters.samplingNoise = probeVolumeOptions.samplingNoise.value;
parameters.weight = probeVolumeOptions.intensityMultiplier.value;
parameters.leakReductionMode = probeVolumeOptions.leakReductionMode.value;
parameters.frameIndexForNoise = taaFrameIndex * (probeVolumeOptions.animateSamplingNoise.value ? 1 : 0);
parameters.reflNormalizationLowerClamp = 0.005f;
parameters.reflNormalizationUpperClamp = probeVolumeOptions.occlusionOnlyReflectionNormalization.value ? 1.0f : 7.0f;
parameters.skyOcclusionIntensity = skyOcclusion ? probeVolumeOptions.skyOcclusionIntensityMultiplier.value : 0.0f;
parameters.skyOcclusionShadingDirection = skyOcclusion && skyOcclusionShadingDirection;
parameters.regionCount = m_CurrentBakingSet != null ? m_CurrentBakingSet.bakedMaskCount : 0;
parameters.regionLayerMasks = (supportRenderingLayers && m_CurrentBakingSet != null) ? m_CurrentBakingSet.bakedLayerMasks : 0xFFFFFFFF;
parameters.worldOffset = probeVolumeOptions.worldOffset.value;
UpdateConstantBuffer(cmd, parameters);
}
return enableProbeVolumes;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c4a7a8f9379dbb4489b78bae7d001713
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,23 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef PROBEREFERENCEVOLUME_DEBUG_CS_HLSL
#define PROBEREFERENCEVOLUME_DEBUG_CS_HLSL
//
// UnityEngine.Rendering.DebugProbeShadingMode: static fields
//
#define DEBUGPROBESHADINGMODE_SH (0)
#define DEBUGPROBESHADINGMODE_SHL0 (1)
#define DEBUGPROBESHADINGMODE_SHL0L1 (2)
#define DEBUGPROBESHADINGMODE_VALIDITY (3)
#define DEBUGPROBESHADINGMODE_VALIDITY_OVER_DILATION_THRESHOLD (4)
#define DEBUGPROBESHADINGMODE_RENDERING_LAYER_MASKS (5)
#define DEBUGPROBESHADINGMODE_INVALIDATED_BY_ADJUSTMENT_VOLUMES (6)
#define DEBUGPROBESHADINGMODE_SIZE (7)
#define DEBUGPROBESHADINGMODE_SKY_OCCLUSION_SH (8)
#define DEBUGPROBESHADINGMODE_SKY_DIRECTION (9)
#define DEBUGPROBESHADINGMODE_PROBE_OCCLUSION (10)
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f6e06ceb4cc6a38458f4b614e8000dc8
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2f2e5e8e23a1880449ebe8c1baaa136f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,196 @@
using System;
using System.Collections.Generic;
using Unity.Collections;
#if UNITY_EDITOR
using UnityEditor;
using Unity.Scripting.LifecycleManagement;
#endif
namespace UnityEngine.Rendering
{
#if UNITY_EDITOR
/// <summary>
/// A manager to enqueue extra probe rendering outside of probe volumes.
/// </summary>
public partial class AdditionalGIBakeRequestsManager
{
// The baking ID for the extra requests
// TODO: Need to ensure this never conflicts with bake IDs from others interacting with the API.
// In our project, this is ProbeVolumes.
internal static readonly int s_BakingID = 912345678;
[AutoStaticsCleanup]
private static AdditionalGIBakeRequestsManager s_Instance = new AdditionalGIBakeRequestsManager();
/// <summary>
/// Get the manager that governs the additional light probe rendering requests.
/// </summary>
public static AdditionalGIBakeRequestsManager instance { get { return s_Instance; } }
const float kInvalidSH = 1f;
const float kInvalidValidity = 1f;
const float kValidSHThresh = 0.33f;
[AutoStaticsCleanup]
private static Dictionary<EntityId, SphericalHarmonicsL2> m_SHCoefficients = new Dictionary<EntityId, SphericalHarmonicsL2>();
[AutoStaticsCleanup]
private static Dictionary<EntityId, float> m_SHValidity = new Dictionary<EntityId, float>();
[AutoStaticsCleanup]
private static Dictionary<EntityId, Vector3> m_RequestPositions = new Dictionary<EntityId, Vector3>();
/// <summary>
/// Enqueue a request for probe rendering at the specified location.
/// </summary>
/// <param name ="capturePosition"> The position at which a probe is baked.</param>
/// <param name ="probeEntityId"> The entityId of the probe doing the request.</param>
public void EnqueueRequest(Vector3 capturePosition, EntityId probeEntityId)
{
m_SHCoefficients[probeEntityId] = new SphericalHarmonicsL2();
m_SHValidity[probeEntityId] = kInvalidSH;
m_RequestPositions[probeEntityId] = capturePosition;
}
/// <summary>
/// Dequeue a request for probe rendering.
/// </summary>
/// <param name ="probeInstanceID">The instance ID of the probe for which we want to dequeue a request. </param>
public void DequeueRequest(EntityId probeInstanceID)
{
if (m_SHCoefficients.ContainsKey(probeInstanceID))
{
m_SHCoefficients.Remove(probeInstanceID);
m_SHValidity.Remove(probeInstanceID);
m_RequestPositions.Remove(probeInstanceID);
}
}
/// <summary>
/// Retrieve the result of a capture request, it will return false if the request has not been fulfilled yet or the request ID is invalid.
/// </summary>
/// <param name ="probeInstanceID"> The instance ID of the probe doing the request.</param>
/// <param name ="sh"> The output SH coefficients that have been computed.</param>
/// <param name ="pos"> The position for which the computed SH coefficients are valid.</param>
/// <returns>Whether the request for light probe rendering has been fulfilled and sh is valid.</returns>
[Obsolete("Use RetrieveProbe instead. #from(6000.2)")]
public bool RetrieveProbeSH(int probeInstanceID, out SphericalHarmonicsL2 sh, out Vector3 pos)
{
if (m_SHCoefficients.ContainsKey(probeInstanceID))
{
sh = m_SHCoefficients[probeInstanceID];
pos = m_RequestPositions[probeInstanceID];
return m_SHValidity[probeInstanceID] < kValidSHThresh;
}
sh = new SphericalHarmonicsL2();
pos = Vector3.negativeInfinity;
return false;
}
/// <summary>
/// Retrieve the result of a capture request, it will return false if the request ID is invalid.
/// </summary>
/// <param name ="probeInstanceID"> The instance ID of the probe doing the request.</param>
/// <param name ="pos"> The position for which the computed SH coefficients are valid.</param>
/// <param name ="sh"> The output SH coefficients that have been computed.</param>
/// <param name ="validity"> The output validity that has been computed.</param>
/// <returns>True if the request ID is valid.</returns>
public bool RetrieveProbe(EntityId probeInstanceID, out Vector3 pos, out SphericalHarmonicsL2 sh, out float validity)
{
if (m_SHCoefficients.ContainsKey(probeInstanceID))
{
sh = m_SHCoefficients[probeInstanceID];
pos = m_RequestPositions[probeInstanceID];
validity = m_SHValidity[probeInstanceID];
return true;
}
sh = new SphericalHarmonicsL2();
pos = Vector3.negativeInfinity;
validity = float.NegativeInfinity;
return false;
}
static internal bool GetPositionForRequest(EntityId probeInstanceID, out Vector3 pos)
{
if (m_SHCoefficients.ContainsKey(probeInstanceID))
{
pos = m_RequestPositions[probeInstanceID];
return true;
}
pos = Vector3.negativeInfinity;
return false;
}
/// <summary>
/// Update the capture location for the probe request.
/// </summary>
/// <param name ="probeInstanceID"> The instance ID of the probe doing the request and that wants the capture position updated.</param>
/// <param name ="newPosition"> The position at which a probe is baked.</param>
public void UpdatePositionForRequest(EntityId probeInstanceID, Vector3 newPosition)
{
if (m_SHCoefficients.ContainsKey(probeInstanceID))
{
m_RequestPositions[probeInstanceID] = newPosition;
m_SHCoefficients[probeInstanceID] = new SphericalHarmonicsL2();
m_SHValidity[probeInstanceID] = kInvalidSH;
}
else
{
EnqueueRequest(newPosition, probeInstanceID);
}
}
static internal List<Vector3> GetProbeNormalizationRequests() => new List<Vector3>(m_RequestPositions.Values);
static internal void OnAdditionalProbesBakeCompleted(NativeArray<SphericalHarmonicsL2> sh, NativeArray<float> validity)
{
SetSHCoefficients(sh, validity);
ProbeReferenceVolume.instance.retrieveExtraDataAction?.Invoke(new ProbeReferenceVolume.ExtraDataActionInput());
}
static bool IsZero(in SphericalHarmonicsL2 s)
{
for (var r = 0; r < 3; ++r)
{
for (var c = 0; c < 9; ++c)
{
if (s[r, c] != 0f)
return false;
}
}
return true;
}
static internal void SetSHCoefficients(NativeArray<SphericalHarmonicsL2> sh, NativeArray<float> validity)
{
Debug.Assert(sh.Length == m_SHCoefficients.Count);
Debug.Assert(sh.Length == validity.Length);
List<EntityId> requestsInstanceIDs = new List<EntityId>(m_SHCoefficients.Keys);
for (int i = 0; i < sh.Length; ++i)
SetSHCoefficients(requestsInstanceIDs[i], sh[i], validity[i]);
}
static internal void SetSHCoefficients(EntityId instanceID, SphericalHarmonicsL2 sh, float validity)
{
if (validity < kValidSHThresh)
{
if (IsZero(in sh))
{
// Use max value as a sentinel to explicitly pass coefficients to light loop that cancel out reflection probe contribution
const float k = float.MaxValue;
sh.AddAmbientLight(new Color(k, k, k));
}
}
m_SHCoefficients[instanceID] = sh;
m_SHValidity[instanceID] = validity;
}
}
#endif
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 41e89eb9ee118734dab014dfd6bb55fc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,41 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef PROBEREFERENCEVOLUME_STREAMING_CS_HLSL
#define PROBEREFERENCEVOLUME_STREAMING_CS_HLSL
// Generated from UnityEngine.Rendering.ProbeReferenceVolume+CellStreamingScratchBufferLayout
// PackingRules = Exact
CBUFFER_START(CellStreamingScratchBufferLayout)
int _SharedDestChunksOffset;
int _L0L1rxOffset;
int _L1GryOffset;
int _L1BrzOffset;
int _ValidityOffset;
int _ProbeOcclusionOffset;
int _SkyOcclusionOffset;
int _SkyShadingDirectionOffset;
int _L2_0Offset;
int _L2_1Offset;
int _L2_2Offset;
int _L2_3Offset;
int _L0Size;
int _L0ProbeSize;
int _L1Size;
int _L1ProbeSize;
int _ValiditySize;
int _ValidityProbeSize;
int _ProbeOcclusionSize;
int _ProbeOcclusionProbeSize;
int _SkyOcclusionSize;
int _SkyOcclusionProbeSize;
int _SkyShadingDirectionSize;
int _SkyShadingDirectionProbeSize;
int _L2Size;
int _L2ProbeSize;
int _ProbeCountInChunkLine;
int _ProbeCountInChunkSlice;
CBUFFER_END
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2675e3c7f72788145b4a5bc872a75211
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 17f23bb13fc806a40b1c1ec8a9b6cb75
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5206b91ddf5158c47918dbb51d045103
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,61 @@
using System;
namespace UnityEngine.Rendering
{
public partial class ProbeVolume : MonoBehaviour
{
enum Version
{
Initial,
LocalMode,
InvertOverrideLevels,
Count
}
[SerializeField]
Version version = Version.Initial;
void Awake()
{
if (version == Version.Count)
return;
if (version == Version.LocalMode - 1)
{
#pragma warning disable 618 // Type or member is obsolete
mode = globalVolume ? Mode.Scene : Mode.Local;
#pragma warning restore 618
version++;
}
if (version == Version.InvertOverrideLevels - 1)
{
#if UNITY_EDITOR
ProbeVolumeBakingSet.SyncBakingSets();
var bakingSet = ProbeVolumeBakingSet.GetBakingSetForScene(gameObject.scene);
if (bakingSet != null)
{
int maxSubdiv = bakingSet != null ? bakingSet.simplificationLevels : 5;
int tmpLowest = lowestSubdivLevelOverride;
lowestSubdivLevelOverride = Mathf.Clamp(maxSubdiv - highestSubdivLevelOverride, 0, 5);
highestSubdivLevelOverride = Mathf.Clamp(maxSubdiv - tmpLowest, 0, 5);
}
#endif
version++;
}
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
}
/// <summary>
/// If is a global bolume
/// </summary>
[SerializeField, Obsolete("Use mode instead. #from(2023.1)")]
public bool globalVolume = false;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 66d9341ed4713be40a82b8eac8efe939
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,251 @@
using System;
using System.Collections.Generic;
using Unity.Scripting.LifecycleManagement;
using UnityEngine.SceneManagement;
namespace UnityEngine.Rendering
{
/// <summary>
/// A marker to determine what area of the scene is considered by the Probe Volumes system
/// </summary>
[CoreRPHelpURL("probevolumes-options-override-reference", "com.unity.render-pipelines.high-definition")]
[ExecuteAlways]
[AddComponentMenu("Rendering/Adaptive Probe Volume")]
public partial class ProbeVolume : MonoBehaviour
{
/// <summary>Indicates which renderers should be considerer for the Probe Volume bounds when baking</summary>
public enum Mode
{
/// <summary>Encapsulate all renderers in the baking set.</summary>
Global,
/// <summary>Encapsulate all renderers in the scene.</summary>
Scene,
/// <summary>Encapsulate all renderers in the bounding box.</summary>
Local
}
/// <summary>
/// If is a global bolume
/// </summary>
[Tooltip("When set to Global this Probe Volume considers all renderers with Contribute Global Illumination enabled. Local only considers renderers in the scene.\nThis list updates every time the Scene is saved or the lighting is baked.")]
public Mode mode = Mode.Local;
/// <summary>
/// The size
/// </summary>
public Vector3 size = new Vector3(10, 10, 10);
/// <summary>
/// Override the renderer filters.
/// </summary>
[HideInInspector, Min(0)]
public bool overrideRendererFilters = false;
/// <summary>
/// The minimum renderer bounding box volume size. This value is used to discard small renderers when the overrideMinRendererVolumeSize is enabled.
/// </summary>
[HideInInspector, Min(0)]
public float minRendererVolumeSize = 0.1f;
/// <summary>
/// The <see cref="LayerMask"/>
/// </summary>
public LayerMask objectLayerMask = -1;
/// <summary>
/// The lowest subdivision level override
/// </summary>
[HideInInspector]
public int lowestSubdivLevelOverride = 0;
/// <summary>
/// The highest subdivision level override
/// </summary>
[HideInInspector]
public int highestSubdivLevelOverride = ProbeBrickIndex.kMaxSubdivisionLevels;
/// <summary>
/// If the subdivision levels need to be overriden
/// </summary>
[HideInInspector]
public bool overridesSubdivLevels = false;
[SerializeField] internal bool mightNeedRebaking = false;
[SerializeField] internal Matrix4x4 cachedTransform;
[SerializeField] internal int cachedHashCode;
/// <summary>Whether spaces with no renderers need to be filled with bricks at highest subdivision level.</summary>
[HideInInspector]
[Tooltip("Whether Unity should fill empty space between renderers with bricks at the highest subdivision level.")]
public bool fillEmptySpaces = false;
#if UNITY_EDITOR
/// <summary>
/// Returns the extents of the volume.
/// </summary>
/// <returns>The extents of the ProbeVolume.</returns>
public Vector3 GetExtents()
{
return size;
}
public Matrix4x4 GetVolume()
{
return Matrix4x4.TRS(transform.position, transform.rotation, GetExtents());
}
internal Bounds ComputeBounds(GIContributors.ContributorFilter filter, Scene? scene = null)
{
Bounds bounds = new Bounds();
bool foundABound = false;
void ExpandBounds(Bounds bound)
{
if (!foundABound)
{
bounds = bound;
foundABound = true;
}
else
{
bounds.Encapsulate(bound);
}
}
var contributors = GIContributors.Find(filter, scene);
foreach (var renderer in contributors.renderers)
ExpandBounds(renderer.component.bounds);
#if ENABLE_TERRAIN_MODULE
foreach (var terrain in contributors.terrains)
ExpandBounds(terrain.boundsWithTrees);
#endif
return bounds;
}
internal void UpdateGlobalVolume(GIContributors.ContributorFilter filter)
{
float minBrickSize = ProbeReferenceVolume.instance.MinBrickSize();
var bounds = ComputeBounds(filter, gameObject.scene);
transform.position = bounds.center;
size = Vector3.Max(bounds.size + new Vector3(minBrickSize, minBrickSize, minBrickSize), Vector3.zero);
}
internal void OnLightingDataAssetCleared()
{
mightNeedRebaking = true;
}
internal void OnBakeCompleted()
{
// We cache the data of last bake completed.
cachedTransform = gameObject.transform.worldToLocalMatrix;
cachedHashCode = GetHashCode();
mightNeedRebaking = false;
}
public override int GetHashCode()
{
int hash = 17;
unchecked
{
hash = hash * 23 + size.GetHashCode();
hash = hash * 23 + gameObject.transform.worldToLocalMatrix.GetHashCode();
hash = hash * 23 + overridesSubdivLevels.GetHashCode();
hash = hash * 23 + highestSubdivLevelOverride.GetHashCode();
hash = hash * 23 + lowestSubdivLevelOverride.GetHashCode();
hash = hash * 23 + overrideRendererFilters.GetHashCode();
if (overrideRendererFilters)
{
hash = hash * 23 + minRendererVolumeSize.GetHashCode();
hash = hash * 23 + objectLayerMask.value.GetHashCode();
}
hash = hash * 23 + fillEmptySpaces.GetHashCode();
}
return hash;
}
internal void GetSubdivisionOverride(int maxSubdivisionLevel, out int minLevel, out int maxLevel)
{
if (overridesSubdivLevels)
{
maxLevel = Mathf.Min(highestSubdivLevelOverride, maxSubdivisionLevel);
minLevel = Mathf.Min(lowestSubdivLevelOverride, maxLevel);
}
else
{
maxLevel = maxSubdivisionLevel;
minLevel = 0;
}
}
[AutoStaticsCleanup]
internal static List<ProbeVolume> instances = new();
void OnEnable()
{
instances.Add(this);
}
void OnDisable()
{
instances.Remove(this);
}
internal ref struct CellCullingContext
{
public Camera ActiveCamera;
public Span<Plane> FrustumPlanes;
}
internal static void PrepareCellCulling(ref CellCullingContext ctx)
{
ctx.ActiveCamera = Camera.current;
#if UNITY_EDITOR
if (ctx.ActiveCamera == null)
ctx.ActiveCamera = UnityEditor.SceneView.lastActiveSceneView.camera;
#endif
Debug.Assert(ctx.FrustumPlanes.Length == 6);
GeometryUtility.CalculateFrustumPlanes(ctx.ActiveCamera, ctx.FrustumPlanes);
}
internal bool ShouldCullCell(in CellCullingContext ctx, Dictionary<string, ProbeVolumeBakingSetWeakReference> sceneToBakingSetMap, ProbeReferenceVolume probeRefVolume, Vector3 cellPosition)
{
var cellSizeInMeters = probeRefVolume.MaxBrickSize();
var probeOffset = probeRefVolume.ProbeOffset() + ProbeVolumeDebug.currentOffset;
var debugDisplay = probeRefVolume.probeVolumeDebug;
if (debugDisplay.realtimeSubdivision)
{
var bakingSet = ProbeVolumeBakingSet.GetBakingSetForScene(sceneToBakingSetMap, gameObject.scene.GetGUID());
if (bakingSet == null)
return true;
// Use the non-backed data to display real-time info
cellSizeInMeters = ProbeVolumeBakingSet.GetMinBrickSize(bakingSet.minDistanceBetweenProbes) * ProbeVolumeBakingSet.GetCellSizeInBricks(bakingSet.simplificationLevels);
probeOffset = bakingSet.probeOffset + ProbeVolumeDebug.currentOffset;
}
if (ctx.ActiveCamera == null)
return true;
var cameraTransform = ctx.ActiveCamera.transform;
Vector3 cellCenterWS = probeOffset + cellPosition * cellSizeInMeters + Vector3.one * (cellSizeInMeters / 2.0f);
// Round down to cell size distance
float roundedDownDist = Mathf.Floor(Vector3.Distance(cameraTransform.position, cellCenterWS) / cellSizeInMeters) * cellSizeInMeters;
if (roundedDownDist > probeRefVolume.probeVolumeDebug.subdivisionViewCullingDistance)
return true;
var volumeAABB = new Bounds(cellCenterWS, cellSizeInMeters * Vector3.one);
return !GeometryUtility.TestPlanesAABB(ctx.FrustumPlanes, volumeAABB);
}
#endif // UNITY_EDITOR
}
} // UnityEngine.Rendering.HDPipeline
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cded085d155cde949b60f67a11dbc3bd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 980a0f86d21d8c740af9cdf457a0d015, type: 2}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,997 @@
#ifndef __PROBEVOLUME_HLSL__
#define __PROBEVOLUME_HLSL__
#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
//#define USE_APV_TEXTURE_HALF
#endif // SHADER_API_MOBILE || SHADER_API_SWITCH || SHADER_API_SWITCH2
#include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ShaderVariablesProbeVolumes.cs.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SphericalHarmonics.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
// Unpack variables
#define _APVWorldOffset _Offset_LayerCount.xyz
#define _APVIndirectionEntryDim _MinLoadedCellInEntries_IndirectionEntryDim.w
#define _APVRcpIndirectionEntryDim _MaxLoadedCellInEntries_RcpIndirectionEntryDim.w
#define _APVMinBrickSize _PoolDim_MinBrickSize.w
#define _APVPoolDim _PoolDim_MinBrickSize.xyz
#define _APVRcpPoolDim _RcpPoolDim_XY.xyz
#define _APVRcpPoolDimXY _RcpPoolDim_XY.w
#define _APVMinEntryPosition _MinEntryPos_Noise.xyz
#define _APVSamplingNoise _MinEntryPos_Noise.w
#define _APVEntryCount _EntryCount_X_XY_LeakReduction.xy
#define _APVLeakReductionMode _EntryCount_X_XY_LeakReduction.z
#define _APVNormalBias _Biases_NormalizationClamp.x
#define _APVViewBias _Biases_NormalizationClamp.y
#define _APVMinLoadedCellInEntries _MinLoadedCellInEntries_IndirectionEntryDim.xyz
#define _APVMaxLoadedCellInEntries _MaxLoadedCellInEntries_RcpIndirectionEntryDim.xyz
#define _APVLayerCount (uint)(_Offset_LayerCount.w)
#define _APVMinReflProbeNormalizationFactor _Biases_NormalizationClamp.z
#define _APVMaxReflProbeNormalizationFactor _Biases_NormalizationClamp.w
#define _APVFrameIndex _FrameIndex_Weights.x
#define _APVWeight _FrameIndex_Weights.y
#define _APVSkyOcclusionWeight _FrameIndex_Weights.z
#define _APVSkyDirectionWeight _FrameIndex_Weights.w
#ifndef DECODE_SH
#include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/DecodeSH.hlsl"
#endif
#ifndef __AMBIENTPROBE_HLSL__
float3 EvaluateAmbientProbe(float3 normalWS)
{
return float3(0, 0, 0);
}
#endif
#ifndef UNITY_SHADER_VARIABLES_INCLUDED
SAMPLER(s_linear_clamp_sampler);
SAMPLER(s_point_clamp_sampler);
#endif
#ifdef USE_APV_TEXTURE_HALF
#define TEXTURE3D_APV TEXTURE3D_HALF
#else
#define TEXTURE3D_APV TEXTURE3D_FLOAT
#endif
struct APVResources
{
StructuredBuffer<int> index;
StructuredBuffer<float3> SkyPrecomputedDirections;
TEXTURE3D_APV(L0_L1Rx);
TEXTURE3D_APV(L1G_L1Ry);
TEXTURE3D_APV(L1B_L1Rz);
TEXTURE3D_APV(L2_0);
TEXTURE3D_APV(L2_1);
TEXTURE3D_APV(L2_2);
TEXTURE3D_APV(L2_3);
TEXTURE3D_FLOAT(Validity); // Validity stores indices and requires full float precision to be decoded properly.
TEXTURE3D_APV(ProbeOcclusion);
TEXTURE3D_APV(SkyOcclusionL0L1);
TEXTURE3D_FLOAT(SkyShadingDirectionIndices);
};
struct APVResourcesRW
{
RWTexture3D<half4> L0_L1Rx;
RWTexture3D<unorm float4> L1G_L1Ry;
RWTexture3D<unorm float4> L1B_L1Rz;
RWTexture3D<unorm float4> L2_0;
RWTexture3D<unorm float4> L2_1;
RWTexture3D<unorm float4> L2_2;
RWTexture3D<unorm float4> L2_3;
RWTexture3D<unorm float4> ProbeOcclusion;
};
#ifndef USE_APV_PROBE_OCCLUSION
// If we are rendering a probe lit renderer, and we have APV enabled, and we are using subtractive or shadowmask mode, we sample occlusion from APV.
#if !defined(LIGHTMAP_ON) && (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)) && (defined(LIGHTMAP_SHADOW_MIXING) || defined(SHADOWS_SHADOWMASK))
#define USE_APV_PROBE_OCCLUSION 1
#endif
#endif
#define LOAD_APV_RES_L1(res, target) \
res.L0_L1Rx = CALL_MERGE_NAME(target, _L0_L1Rx); \
res.L1G_L1Ry = CALL_MERGE_NAME(target, _L1G_L1Ry); \
res.L1B_L1Rz = CALL_MERGE_NAME(target, _L1B_L1Rz);
#define LOAD_APV_RES_L2(res, target) \
res.L2_0 = CALL_MERGE_NAME(target, _L2_0); \
res.L2_1 = CALL_MERGE_NAME(target, _L2_1); \
res.L2_2 = CALL_MERGE_NAME(target, _L2_2); \
res.L2_3 = CALL_MERGE_NAME(target, _L2_3);
#define LOAD_APV_RES_OCCLUSION(res, target) \
res.ProbeOcclusion = CALL_MERGE_NAME(target, _ProbeOcclusion);
#ifndef PROBE_VOLUMES_L2
#ifndef USE_APV_PROBE_OCCLUSION
# define LOAD_APV_RES(res, target) LOAD_APV_RES_L1(res, target)
#else
# define LOAD_APV_RES(res, target) LOAD_APV_RES_L1(res, target) \
LOAD_APV_RES_OCCLUSION(res, target)
#endif
#else
#ifndef USE_APV_PROBE_OCCLUSION
# define LOAD_APV_RES(res, target) \
LOAD_APV_RES_L1(res, target) \
LOAD_APV_RES_L2(res, target)
#else
# define LOAD_APV_RES(res, target) \
LOAD_APV_RES_L1(res, target) \
LOAD_APV_RES_L2(res, target) \
LOAD_APV_RES_OCCLUSION(res, target)
#endif
#endif
struct APVSample
{
half3 L0;
half3 L1_R;
half3 L1_G;
half3 L1_B;
#ifdef PROBE_VOLUMES_L2
half4 L2_R;
half4 L2_G;
half4 L2_B;
half3 L2_C;
#endif // PROBE_VOLUMES_L2
float4 skyOcclusionL0L1;
float3 skyShadingDirection;
#ifdef USE_APV_PROBE_OCCLUSION
float4 probeOcclusion;
#endif
#define APV_SAMPLE_STATUS_INVALID -1
#define APV_SAMPLE_STATUS_ENCODED 0
#define APV_SAMPLE_STATUS_DECODED 1
int status;
// Note: at the moment this is called at the moment the struct is built, but it is kept as a separate step
// as ideally should be called as far as possible from sample to allow for latency hiding.
void Decode()
{
if (status == APV_SAMPLE_STATUS_ENCODED)
{
L1_R = DecodeSH(L0.r, L1_R);
L1_G = DecodeSH(L0.g, L1_G);
L1_B = DecodeSH(L0.b, L1_B);
#ifdef PROBE_VOLUMES_L2
DecodeSH_L2(L0, L2_R, L2_G, L2_B, L2_C);
#endif // PROBE_VOLUMES_L2
status = APV_SAMPLE_STATUS_DECODED;
}
}
void Encode()
{
if (status == APV_SAMPLE_STATUS_DECODED)
{
L1_R = EncodeSH(L0.r, L1_R);
L1_G = EncodeSH(L0.g, L1_G);
L1_B = EncodeSH(L0.b, L1_B);
#ifdef PROBE_VOLUMES_L2
EncodeSH_L2(L0, L2_R, L2_G, L2_B, L2_C);
#endif // PROBE_VOLUMES_L2
status = APV_SAMPLE_STATUS_ENCODED;
}
}
};
// Resources required for APV
StructuredBuffer<int> _APVResIndex;
StructuredBuffer<uint3> _APVResCellIndices;
StructuredBuffer<float3> _SkyPrecomputedDirections;
StructuredBuffer<uint> _AntiLeakData;
TEXTURE3D_APV(_APVResL0_L1Rx);
TEXTURE3D_APV(_APVResL1G_L1Ry);
TEXTURE3D_APV(_APVResL1B_L1Rz);
TEXTURE3D_APV(_APVResL2_0);
TEXTURE3D_APV(_APVResL2_1);
TEXTURE3D_APV(_APVResL2_2);
TEXTURE3D_APV(_APVResL2_3);
TEXTURE3D_APV(_APVProbeOcclusion);
TEXTURE3D_APV(_APVResValidity);
TEXTURE3D_APV(_SkyOcclusionTexL0L1);
TEXTURE3D(_SkyShadingDirectionIndicesTex);
// -------------------------------------------------------------
// Various weighting functions for occlusion or helper functions.
// -------------------------------------------------------------
float3 AddNoiseToSamplingPosition(float3 posWS, float2 positionSS, float3 direction)
{
#ifdef UNITY_SPACE_TRANSFORMS_INCLUDED
float3 right = mul((float3x3)GetViewToWorldMatrix(), float3(1.0, 0.0, 0.0));
float3 top = mul((float3x3)GetViewToWorldMatrix(), float3(0.0, 1.0, 0.0));
float noise01 = InterleavedGradientNoise(positionSS, _APVFrameIndex);
float noise02 = frac(noise01 * 100.0);
float noise03 = frac(noise01 * 1000.0);
direction += top * (noise02 - 0.5) + right * (noise03 - 0.5);
return _APVSamplingNoise > 0 ? posWS + noise01 * _APVSamplingNoise * direction : posWS;
#else
return posWS;
#endif
}
uint3 GetSampleOffset(uint i)
{
return uint3(i, i >> 1, i >> 2) & 1;
}
// The validity mask is sampled once and contains a binary info on whether a probe neighbour (relevant for trilinear) is to be used
// or not. The entry in the mask uses the same mapping that GetSampleOffset above uses.
half GetValidityWeight(uint offset, uint validityMask)
{
uint mask = 1U << offset;
return (validityMask & mask) > 0 ? 1 : 0;
}
float ProbeDistance(uint subdiv)
{
return pow(3, subdiv) * _APVMinBrickSize / 3.0f;
}
half ProbeDistanceHalf(uint subdiv)
{
return pow(half(3), half(subdiv)) * half(_APVMinBrickSize) / 3.0;
}
float3 GetSnappedProbePosition(float3 posWS, uint subdiv)
{
float3 distBetweenProbes = ProbeDistance(subdiv);
float3 dividedPos = posWS / distBetweenProbes;
return (dividedPos - frac(dividedPos)) * distBetweenProbes;
}
// -------------------------------------------------------------
// Indexing functions
// -------------------------------------------------------------
bool LoadCellIndexMetaData(uint cellFlatIdx, out uint chunkIndex, out int stepSize, out int3 minRelativeIdx, out uint3 sizeOfValid)
{
uint3 metaData = _APVResCellIndices[cellFlatIdx];
// See ProbeIndexOfIndices.cs for packing
chunkIndex = metaData.x & 0x1FFFFFFF;
stepSize = round(pow(3, (metaData.x >> 29) & 0x7));
minRelativeIdx.x = metaData.y & 0x3FF;
minRelativeIdx.y = (metaData.y >> 10) & 0x3FF;
minRelativeIdx.z = (metaData.y >> 20) & 0x3FF;
sizeOfValid.x = metaData.z & 0x3FF;
sizeOfValid.y = (metaData.z >> 10) & 0x3FF;
sizeOfValid.z = (metaData.z >> 20) & 0x3FF;
return metaData.x != 0xFFFFFFFF;
}
uint GetIndexData(APVResources apvRes, float3 posWS)
{
float3 entryPos = floor(posWS * _APVRcpIndirectionEntryDim);
float3 topLeftEntryWS = entryPos * _APVIndirectionEntryDim;
bool isALoadedCell = all(entryPos >= _APVMinLoadedCellInEntries) && all(entryPos <= _APVMaxLoadedCellInEntries);
// Make sure we start from 0
uint3 entryPosInt = (uint3)(entryPos - _APVMinEntryPosition);
uint flatIdx = dot(entryPosInt, uint3(1, _APVEntryCount.x, _APVEntryCount.y));
// Dynamic branch must be enforced to avoid out-of-bounds memory access in LoadCellIndexMetaData
uint result = 0xffffffff;
UNITY_BRANCH if (isALoadedCell)
{
int stepSize;
int3 minRelativeIdx;
uint3 sizeOfValid;
uint chunkIdx;
if (LoadCellIndexMetaData(flatIdx, chunkIdx, stepSize, minRelativeIdx, sizeOfValid))
{
float3 residualPosWS = posWS - topLeftEntryWS;
uint3 localBrickIndex = floor(residualPosWS / (_APVMinBrickSize * stepSize));
localBrickIndex = min(localBrickIndex, (uint3)(3 * 3 * 3 - 1)); // due to floating point issue, we may query an invalid brick
localBrickIndex -= minRelativeIdx; // Relative to valid region
UNITY_BRANCH
if (all(localBrickIndex < sizeOfValid))
{
uint flattenedLocationInCell = dot(localBrickIndex, uint3(sizeOfValid.y, 1, sizeOfValid.x * sizeOfValid.y));
uint locationInPhysicalBuffer = chunkIdx * (uint)PROBE_INDEX_CHUNK_SIZE + flattenedLocationInCell;
result = apvRes.index[locationInPhysicalBuffer];
}
}
}
return result;
}
// -------------------------------------------------------------
// Loading functions
// -------------------------------------------------------------
APVResources FillAPVResources()
{
APVResources apvRes;
apvRes.index = _APVResIndex;
apvRes.L0_L1Rx = _APVResL0_L1Rx;
apvRes.L1G_L1Ry = _APVResL1G_L1Ry;
apvRes.L1B_L1Rz = _APVResL1B_L1Rz;
apvRes.L2_0 = _APVResL2_0;
apvRes.L2_1 = _APVResL2_1;
apvRes.L2_2 = _APVResL2_2;
apvRes.L2_3 = _APVResL2_3;
apvRes.Validity = _APVResValidity;
apvRes.SkyOcclusionL0L1 = _SkyOcclusionTexL0L1;
apvRes.SkyShadingDirectionIndices = _SkyShadingDirectionIndicesTex;
apvRes.SkyPrecomputedDirections = _SkyPrecomputedDirections;
apvRes.ProbeOcclusion = _APVProbeOcclusion;
return apvRes;
}
bool TryToGetPoolUVWAndSubdiv(APVResources apvRes, float3 posWSForSample, out float3 uvw, out uint subdiv)
{
// resolve the index
uint packed_pool_idx = GetIndexData(apvRes, posWSForSample.xyz);
// unpack pool idx
// size is encoded in the upper 4 bits
subdiv = (packed_pool_idx >> 28) & 15;
float flattened_pool_idx = packed_pool_idx & ((1 << 28) - 1);
float3 pool_idx;
pool_idx.z = floor(flattened_pool_idx * _APVRcpPoolDimXY);
flattened_pool_idx -= (pool_idx.z * (_APVPoolDim.x * _APVPoolDim.y));
pool_idx.y = floor(flattened_pool_idx * _APVRcpPoolDim.x);
pool_idx.x = floor(flattened_pool_idx - (pool_idx.y * _APVPoolDim.x));
// calculate uv offset and scale
float brickSizeWS = pow(3.0, subdiv) * _APVMinBrickSize;
float3 offset = frac(posWSForSample.xyz / brickSizeWS); // [0;1] in brick space
//offset = clamp( offset, 0.25, 0.75 ); // [0.25;0.75] in brick space (is this actually necessary?)
uvw = (pool_idx + 0.5 + (3.0 * offset)) * _APVRcpPoolDim; // add offset with brick footprint converted to text footprint in pool texel space
// no valid brick loaded for this index, fallback to ambient probe
// Note: we could instead early return when we know we'll have invalid UVs, but some bade code gen on Vulkan generates shader warnings if we do.
return packed_pool_idx != 0xffffffffu;
}
bool TryToGetPoolUVWAndSubdiv(APVResources apvRes, float3 posWS, float3 normalWS, float3 viewDirWS, out float3 uvw, out uint subdiv, out float3 biasedPosWS)
{
biasedPosWS = (posWS + normalWS * _APVNormalBias) + viewDirWS * _APVViewBias;
return TryToGetPoolUVWAndSubdiv(apvRes, biasedPosWS, uvw, subdiv);
}
bool TryToGetPoolUVW(APVResources apvRes, float3 posWS, float3 normalWS, float3 viewDir, out float3 uvw)
{
uint unusedSubdiv;
float3 unusedPos;
return TryToGetPoolUVWAndSubdiv(apvRes, posWS, normalWS, viewDir, uvw, unusedSubdiv, unusedPos);
}
APVSample SampleAPV(APVResources apvRes, float3 uvw)
{
APVSample apvSample;
half4 L0_L1Rx = half4(SAMPLE_TEXTURE3D_LOD(apvRes.L0_L1Rx, s_linear_clamp_sampler, uvw, 0).rgba);
half4 L1G_L1Ry = half4(SAMPLE_TEXTURE3D_LOD(apvRes.L1G_L1Ry, s_linear_clamp_sampler, uvw, 0).rgba);
half4 L1B_L1Rz = half4(SAMPLE_TEXTURE3D_LOD(apvRes.L1B_L1Rz, s_linear_clamp_sampler, uvw, 0).rgba);
apvSample.L0 = L0_L1Rx.xyz;
apvSample.L1_R = half3(L0_L1Rx.w, L1G_L1Ry.w, L1B_L1Rz.w);
apvSample.L1_G = L1G_L1Ry.xyz;
apvSample.L1_B = L1B_L1Rz.xyz;
#ifdef PROBE_VOLUMES_L2
apvSample.L2_R = half4(SAMPLE_TEXTURE3D_LOD(apvRes.L2_0, s_linear_clamp_sampler, uvw, 0).rgba);
apvSample.L2_G = half4(SAMPLE_TEXTURE3D_LOD(apvRes.L2_1, s_linear_clamp_sampler, uvw, 0).rgba);
apvSample.L2_B = half4(SAMPLE_TEXTURE3D_LOD(apvRes.L2_2, s_linear_clamp_sampler, uvw, 0).rgba);
apvSample.L2_C = half3(SAMPLE_TEXTURE3D_LOD(apvRes.L2_3, s_linear_clamp_sampler, uvw, 0).rgb);
#endif // PROBE_VOLUMES_L2
if (_APVSkyOcclusionWeight > 0)
apvSample.skyOcclusionL0L1 = SAMPLE_TEXTURE3D_LOD(apvRes.SkyOcclusionL0L1, s_linear_clamp_sampler, uvw, 0).rgba;
else
apvSample.skyOcclusionL0L1 = float4(0, 0, 0, 0);
if (_APVSkyDirectionWeight > 0)
{
// No interpolation for sky shading indices
int3 texCoord = uvw * _APVPoolDim - 0.5f;
uint index = LOAD_TEXTURE3D(apvRes.SkyShadingDirectionIndices, texCoord).x * 255.0;
if (index == 255)
apvSample.skyShadingDirection = float3(0, 0, 0);
else
apvSample.skyShadingDirection = apvRes.SkyPrecomputedDirections[index].rgb;
}
else
apvSample.skyShadingDirection = float3(0, 0, 0);
#ifdef USE_APV_PROBE_OCCLUSION
apvSample.probeOcclusion = SAMPLE_TEXTURE3D_LOD(apvRes.ProbeOcclusion, s_linear_clamp_sampler, uvw, 0).rgba;
#endif
apvSample.status = APV_SAMPLE_STATUS_ENCODED;
return apvSample;
}
APVSample LoadAndDecodeAPV(APVResources apvRes, int3 loc)
{
APVSample apvSample;
half4 L0_L1Rx = half4(LOAD_TEXTURE3D(apvRes.L0_L1Rx, loc).rgba);
half4 L1G_L1Ry = half4(LOAD_TEXTURE3D(apvRes.L1G_L1Ry, loc).rgba);
half4 L1B_L1Rz = half4(LOAD_TEXTURE3D(apvRes.L1B_L1Rz, loc).rgba);
apvSample.L0 = L0_L1Rx.xyz;
apvSample.L1_R = half3(L0_L1Rx.w, L1G_L1Ry.w, L1B_L1Rz.w);
apvSample.L1_G = L1G_L1Ry.xyz;
apvSample.L1_B = L1B_L1Rz.xyz;
#ifdef PROBE_VOLUMES_L2
apvSample.L2_R = half4(LOAD_TEXTURE3D(apvRes.L2_0, loc).rgba);
apvSample.L2_G = half4(LOAD_TEXTURE3D(apvRes.L2_1, loc).rgba);
apvSample.L2_B = half4(LOAD_TEXTURE3D(apvRes.L2_2, loc).rgba);
apvSample.L2_C = half3(LOAD_TEXTURE3D(apvRes.L2_3, loc).rgb);
#endif // PROBE_VOLUMES_L2
#ifdef USE_APV_PROBE_OCCLUSION
apvSample.probeOcclusion = LOAD_TEXTURE3D(apvRes.ProbeOcclusion, loc).rgba;
#endif
apvSample.status = APV_SAMPLE_STATUS_ENCODED;
apvSample.Decode();
return apvSample;
}
void WeightSample(inout APVSample apvSample, half weight)
{
apvSample.L0 *= weight;
apvSample.L1_R *= weight;
apvSample.L1_G *= weight;
apvSample.L1_B *= weight;
#ifdef PROBE_VOLUMES_L2
apvSample.L2_R *= weight;
apvSample.L2_G *= weight;
apvSample.L2_B *= weight;
apvSample.L2_C *= weight;
#endif // PROBE_VOLUMES_L2
#ifdef USE_APV_PROBE_OCCLUSION
apvSample.probeOcclusion *= weight;
#endif
apvSample.skyOcclusionL0L1 *= weight;
}
void AccumulateSamples(inout APVSample dst, APVSample other, half weight)
{
WeightSample(other, weight);
dst.L0 += other.L0;
dst.L1_R += other.L1_R;
dst.L1_G += other.L1_G;
dst.L1_B += other.L1_B;
#ifdef PROBE_VOLUMES_L2
dst.L2_R += other.L2_R;
dst.L2_G += other.L2_G;
dst.L2_B += other.L2_B;
dst.L2_C += other.L2_C;
#endif // PROBE_VOLUMES_L2
#ifdef USE_APV_PROBE_OCCLUSION
dst.probeOcclusion += other.probeOcclusion;
#endif
dst.skyOcclusionL0L1 += other.skyOcclusionL0L1;
}
uint LoadValidityMask(APVResources apvRes, uint renderingLayer, int3 coord)
{
float rawValidity = LOAD_TEXTURE3D(apvRes.Validity, coord).x;
uint validityMask;
if (_APVLayerCount == 1)
{
validityMask = rawValidity * 255.0;
}
else
{
// If the object is on none of the masks, enable all layers to still sample validity correctly
uint globalLayer = _ProbeVolumeLayerMask[0] | _ProbeVolumeLayerMask[1] | _ProbeVolumeLayerMask[2] | _ProbeVolumeLayerMask[3];
if ((renderingLayer & globalLayer) == 0) renderingLayer = 0xFFFFFFFF;
validityMask = 0;
if ((renderingLayer & _ProbeVolumeLayerMask[0]) != 0)
validityMask = asuint(rawValidity);
if ((renderingLayer & _ProbeVolumeLayerMask[1]) != 0)
validityMask |= asuint(rawValidity) >> 8;
if ((renderingLayer & _ProbeVolumeLayerMask[2]) != 0)
validityMask |= asuint(rawValidity) >> 16;
if ((renderingLayer & _ProbeVolumeLayerMask[3]) != 0)
validityMask |= asuint(rawValidity) >> 24;
validityMask = validityMask & 0xFF;
}
return validityMask;
}
float UnpackSamplingWeight(uint mask, float3 texFrac)
{
int3 dir = 0;
dir.x = (int)(mask >> 1) & 3;
dir.y = (int)(mask >> 4) & 3;
dir.z = (int)(mask >> 7) & 3;
float3 weights;
weights.x = saturate(mask & 1) + (dir.x - 1) * texFrac.x;
weights.y = saturate(mask & 8) + (dir.y - 1) * texFrac.y;
weights.z = saturate(mask & 64) + (dir.z - 1) * texFrac.z;
return weights.x * weights.y * weights.z;
}
void UnpackSamplingOffset(uint mask, float3 texFrac, out float3 uvwOffset)
{
uvwOffset.x = saturate(mask & 4) + (saturate(mask & 2) * texFrac.x - texFrac.x);
uvwOffset.y = saturate(mask & 32) + (saturate(mask & 16) * texFrac.y - texFrac.y);
uvwOffset.z = saturate(mask & 256) + (saturate(mask & 128) * texFrac.z - texFrac.z);
}
APVSample QualityLeakReduction(APVResources apvRes, uint renderingLayer, inout float3 uvw)
{
float3 texCoord = uvw * _APVPoolDim - .5f;
float3 texFrac = frac(texCoord);
half3 offset;
uint validityMask = LoadValidityMask(apvRes, renderingLayer, texCoord);
uint antileak = _AntiLeakData[validityMask];
UnpackSamplingOffset(antileak >> 0, texFrac, offset);
APVSample apvSample = SampleAPV(apvRes, uvw + offset * _APVRcpPoolDim);
// Optional additional samples for quality leak reduction
if (validityMask != 0xFF)
{
float3 weights;
weights.x = UnpackSamplingWeight(antileak >> 0, texFrac);
weights.y = UnpackSamplingWeight(antileak >> 9, texFrac);
weights.z = UnpackSamplingWeight(antileak >> 18, texFrac);
weights *= rcp(max(0.0001, weights.x+weights.y+weights.z));
WeightSample(apvSample, weights.x);
UNITY_BRANCH if (weights.y != 0)
{
UnpackSamplingOffset(antileak >> 9, texFrac, offset);
APVSample partialSample = SampleAPV(apvRes, uvw + offset * _APVRcpPoolDim);
AccumulateSamples(apvSample, partialSample, weights.y);
}
UNITY_BRANCH if (weights.z != 0)
{
UnpackSamplingOffset(antileak >> 18, texFrac, offset);
APVSample partialSample = SampleAPV(apvRes, uvw + offset * _APVRcpPoolDim);
AccumulateSamples(apvSample, partialSample, weights.z);
}
}
return apvSample;
}
void WarpUVWLeakReduction(APVResources apvRes, uint renderingLayer, inout float3 uvw)
{
float3 texCoord = uvw * _APVPoolDim - 0.5f;
half3 texFrac = half3(frac(texCoord));
uint validityMask = LoadValidityMask(apvRes, renderingLayer, texCoord);
if (validityMask != 0xFF)
{
half weights[8];
half totalW = 0.0;
half3 offset = 0;
uint i;
UNITY_UNROLL
for (i = 0; i < 8; ++i)
{
uint3 probeOffset = GetSampleOffset(i);
half validityWeight =
((probeOffset.x == 1) ? texFrac.x : 1.0f - texFrac.x) *
((probeOffset.y == 1) ? texFrac.y : 1.0f - texFrac.y) *
((probeOffset.z == 1) ? texFrac.z : 1.0f - texFrac.z);
validityWeight *= GetValidityWeight(i, validityMask);
half weight = saturate(validityWeight);
weights[i] = weight;
totalW += weight;
}
offset = -texFrac;
half rcpTotalW = rcp(max(0.0001, totalW));
UNITY_UNROLL
for (i = 0; i < 8; ++i)
{
uint3 probeOffset = GetSampleOffset(i);
offset += (half3)probeOffset * (weights[i] * rcpTotalW);
}
uvw += (float3)offset * _APVRcpPoolDim;
}
}
APVSample SampleAPV(APVResources apvRes, float3 posWS, float3 biasNormalWS, uint renderingLayer, float3 viewDir)
{
APVSample outSample;
posWS -= _APVWorldOffset;
uint subdiv;
float3 pool_uvw;
float3 biasedPosWS;
if (TryToGetPoolUVWAndSubdiv(apvRes, posWS, biasNormalWS, viewDir, pool_uvw, subdiv, biasedPosWS))
{
UNITY_BRANCH if (_APVLeakReductionMode == APVLEAKREDUCTIONMODE_QUALITY)
{
outSample = QualityLeakReduction(apvRes, renderingLayer, pool_uvw);
}
else
{
if (_APVLeakReductionMode == APVLEAKREDUCTIONMODE_PERFORMANCE)
WarpUVWLeakReduction(apvRes, renderingLayer, pool_uvw);
outSample = SampleAPV(apvRes, pool_uvw);
}
}
else
{
ZERO_INITIALIZE(APVSample, outSample);
#ifdef USE_APV_PROBE_OCCLUSION
// The "neutral" value for probe occlusion is 1.0. We write it here to prevent objects that are outside
// the bounds of the probe volume from being entirely shadowed.
outSample.probeOcclusion = 1.0f;
#endif
outSample.status = APV_SAMPLE_STATUS_INVALID;
}
return outSample;
}
APVSample SampleAPV(float3 posWS, float3 biasNormalWS, uint renderingLayer, float3 viewDir)
{
APVResources apvRes = FillAPVResources();
return SampleAPV(apvRes, posWS, biasNormalWS, renderingLayer, viewDir);
}
// -------------------------------------------------------------
// Dynamic Sky Handling
// -------------------------------------------------------------
// Expects Layout DC, x, y, z
// See on baking side in DynamicGISkyOcclusion.hlsl
float EvalSHSkyOcclusion(float3 dir, APVSample apvSample)
{
// L0 L1
float4 temp = float4(kSHBasis0, kSHBasis1 * dir.x, kSHBasis1 * dir.y, kSHBasis1 * dir.z);
return _APVSkyOcclusionWeight * dot(temp, apvSample.skyOcclusionL0L1);
}
float3 EvaluateOccludedSky(APVSample apvSample, float3 N)
{
float occValue = EvalSHSkyOcclusion(N, apvSample);
float3 shadingNormal = N;
if (_APVSkyDirectionWeight > 0)
{
shadingNormal = apvSample.skyShadingDirection;
float normSquared = dot(shadingNormal, shadingNormal);
if (normSquared < 0.2f)
shadingNormal = N;
else
{
shadingNormal = shadingNormal * rsqrt(normSquared);
}
}
return occValue * EvaluateAmbientProbe(shadingNormal);
}
// -------------------------------------------------------------
// Internal Evaluation functions (avoid usage in caller code outside this file)
// -------------------------------------------------------------
float3 EvaluateAPVL0(APVSample apvSample)
{
return apvSample.L0;
}
void EvaluateAPVL1(APVSample apvSample, float3 N, out float3 diffuseLighting)
{
diffuseLighting = SHEvalLinearL1(N, apvSample.L1_R, apvSample.L1_G, apvSample.L1_B);
}
#ifdef PROBE_VOLUMES_L2
void EvaluateAPVL1L2(APVSample apvSample, float3 N, out float3 diffuseLighting)
{
EvaluateAPVL1(apvSample, N, diffuseLighting);
diffuseLighting += SHEvalLinearL2(N, apvSample.L2_R, apvSample.L2_G, apvSample.L2_B, float4(apvSample.L2_C, 0.0f));
}
#endif
// -------------------------------------------------------------
// "Public" Evaluation functions, the one that callers outside this file should use
// -------------------------------------------------------------
void EvaluateAdaptiveProbeVolume(APVSample apvSample, float3 normalWS, out float3 bakeDiffuseLighting)
{
bakeDiffuseLighting = float3(0.0f, 0.0f, 0.0f);
if (apvSample.status != APV_SAMPLE_STATUS_INVALID)
{
apvSample.Decode();
#if defined(PROBE_VOLUMES_L1)
EvaluateAPVL1(apvSample, normalWS, bakeDiffuseLighting);
#elif defined(PROBE_VOLUMES_L2)
EvaluateAPVL1L2(apvSample, normalWS, bakeDiffuseLighting);
#endif
bakeDiffuseLighting += apvSample.L0;
if (_APVSkyOcclusionWeight > 0)
bakeDiffuseLighting += EvaluateOccludedSky(apvSample, normalWS);
//if (_APVWeight < 1.f)
{
bakeDiffuseLighting = bakeDiffuseLighting * _APVWeight;
}
}
else
{
// no valid brick, fallback to ambient probe
bakeDiffuseLighting = EvaluateAmbientProbe(normalWS);
}
}
void EvaluateAdaptiveProbeVolume(APVSample apvSample, float3 normalWS, float3 backNormalWS, out float3 bakeDiffuseLighting, out float3 backBakeDiffuseLighting)
{
if (apvSample.status != APV_SAMPLE_STATUS_INVALID)
{
apvSample.Decode();
#ifdef PROBE_VOLUMES_L1
EvaluateAPVL1(apvSample, normalWS, bakeDiffuseLighting);
EvaluateAPVL1(apvSample, backNormalWS, backBakeDiffuseLighting);
#elif defined(PROBE_VOLUMES_L2)
EvaluateAPVL1L2(apvSample, normalWS, bakeDiffuseLighting);
EvaluateAPVL1L2(apvSample, backNormalWS, backBakeDiffuseLighting);
#endif
bakeDiffuseLighting += apvSample.L0;
backBakeDiffuseLighting += apvSample.L0;
if (_APVSkyOcclusionWeight > 0)
{
bakeDiffuseLighting += EvaluateOccludedSky(apvSample, normalWS);
backBakeDiffuseLighting += EvaluateOccludedSky(apvSample, backNormalWS);
}
//if (_APVWeight < 1.f)
{
bakeDiffuseLighting = bakeDiffuseLighting * _APVWeight;
backBakeDiffuseLighting = backBakeDiffuseLighting * _APVWeight;
}
}
else
{
// no valid brick, fallback to ambient probe
bakeDiffuseLighting = EvaluateAmbientProbe(normalWS);
backBakeDiffuseLighting = EvaluateAmbientProbe(backNormalWS);
}
}
void EvaluateAdaptiveProbeVolume(in float3 posWS, in float3 normalWS, in float3 backNormalWS, in float3 reflDir, in float3 viewDir,
in float2 positionSS, in uint renderingLayer, out float3 bakeDiffuseLighting, out float3 backBakeDiffuseLighting, out float3 lightingInReflDir)
{
APVResources apvRes = FillAPVResources();
posWS = AddNoiseToSamplingPosition(posWS, positionSS, viewDir);
APVSample apvSample = SampleAPV(posWS, normalWS, renderingLayer, viewDir);
if (apvSample.status != APV_SAMPLE_STATUS_INVALID)
{
apvSample.Decode();
#ifdef PROBE_VOLUMES_L1
EvaluateAPVL1(apvSample, normalWS, bakeDiffuseLighting);
EvaluateAPVL1(apvSample, backNormalWS, backBakeDiffuseLighting);
EvaluateAPVL1(apvSample, reflDir, lightingInReflDir);
#elif defined(PROBE_VOLUMES_L2)
EvaluateAPVL1L2(apvSample, normalWS, bakeDiffuseLighting);
EvaluateAPVL1L2(apvSample, backNormalWS, backBakeDiffuseLighting);
EvaluateAPVL1L2(apvSample, reflDir, lightingInReflDir);
#endif
bakeDiffuseLighting += apvSample.L0;
backBakeDiffuseLighting += apvSample.L0;
lightingInReflDir += apvSample.L0;
if (_APVSkyOcclusionWeight > 0)
{
bakeDiffuseLighting += EvaluateOccludedSky(apvSample, normalWS);
backBakeDiffuseLighting += EvaluateOccludedSky(apvSample, backNormalWS);
lightingInReflDir += EvaluateOccludedSky(apvSample, reflDir);
}
//if (_APVWeight < 1.f)
{
bakeDiffuseLighting = bakeDiffuseLighting * _APVWeight;
backBakeDiffuseLighting = backBakeDiffuseLighting * _APVWeight;
}
}
else
{
bakeDiffuseLighting = EvaluateAmbientProbe(normalWS);
backBakeDiffuseLighting = EvaluateAmbientProbe(backNormalWS);
lightingInReflDir = -1;
}
}
void EvaluateAdaptiveProbeVolume(in float3 posWS, in float3 normalWS, in float3 backNormalWS, in float3 viewDir,
in float2 positionSS, in uint renderingLayer, out float3 bakeDiffuseLighting, out float3 backBakeDiffuseLighting, out float4 probeOcclusion)
{
bakeDiffuseLighting = float3(0.0, 0.0, 0.0);
backBakeDiffuseLighting = float3(0.0, 0.0, 0.0);
posWS = AddNoiseToSamplingPosition(posWS, positionSS, viewDir);
APVSample apvSample = SampleAPV(posWS, normalWS, renderingLayer, viewDir);
#ifdef USE_APV_PROBE_OCCLUSION
probeOcclusion = apvSample.probeOcclusion;
#else
probeOcclusion = 1;
#endif
EvaluateAdaptiveProbeVolume(apvSample, normalWS, backNormalWS, bakeDiffuseLighting, backBakeDiffuseLighting);
}
void EvaluateAdaptiveProbeVolume(in float3 posWS, in float3 normalWS, in float3 backNormalWS, in float3 viewDir,
in float2 positionSS, in uint renderingLayer, out float3 bakeDiffuseLighting, out float3 backBakeDiffuseLighting)
{
float4 unusedProbeOcclusion = 0;
EvaluateAdaptiveProbeVolume(posWS, normalWS, backNormalWS, viewDir, positionSS, renderingLayer, bakeDiffuseLighting, backBakeDiffuseLighting, unusedProbeOcclusion);
}
void EvaluateAdaptiveProbeVolume(in float3 posWS, in float3 normalWS, in float3 viewDir, in float2 positionSS, in uint renderingLayer,
out float3 bakeDiffuseLighting, out float4 probeOcclusion)
{
bakeDiffuseLighting = float3(0.0, 0.0, 0.0);
posWS = AddNoiseToSamplingPosition(posWS, positionSS, viewDir);
APVSample apvSample = SampleAPV(posWS, normalWS, renderingLayer, viewDir);
#ifdef USE_APV_PROBE_OCCLUSION
probeOcclusion = apvSample.probeOcclusion;
#else
probeOcclusion = 1;
#endif
EvaluateAdaptiveProbeVolume(apvSample, normalWS, bakeDiffuseLighting);
}
void EvaluateAdaptiveProbeVolume(in float3 posWS, in float3 normalWS, in float3 viewDir, in uint renderingLayer,
out float3 bakeDiffuseLighting, out float4 probeOcclusion)
{
bakeDiffuseLighting = float3(0.0, 0.0, 0.0);
APVSample apvSample = SampleAPV(posWS, normalWS, renderingLayer, viewDir);
#ifdef USE_APV_PROBE_OCCLUSION
probeOcclusion = apvSample.probeOcclusion;
#else
probeOcclusion = 1;
#endif
EvaluateAdaptiveProbeVolume(apvSample, normalWS, bakeDiffuseLighting);
}
void EvaluateAdaptiveProbeVolume(in float3 posWS, in float3 normalWS, in float3 viewDir, in float2 positionSS, in uint renderingLayer,
out float3 bakeDiffuseLighting)
{
float4 unusedProbeOcclusion = 0;
EvaluateAdaptiveProbeVolume(posWS, normalWS, viewDir, positionSS, renderingLayer, bakeDiffuseLighting, unusedProbeOcclusion);
}
void EvaluateAdaptiveProbeVolume(in float3 posWS, in float2 positionSS, out float3 bakeDiffuseLighting)
{
APVResources apvRes = FillAPVResources();
posWS = AddNoiseToSamplingPosition(posWS, positionSS, 1);
posWS -= _APVWorldOffset;
float3 ambientProbe = EvaluateAmbientProbe(0);
float3 uvw;
if (TryToGetPoolUVW(apvRes, posWS, 0, 0, uvw))
{
bakeDiffuseLighting = SAMPLE_TEXTURE3D_LOD(apvRes.L0_L1Rx, s_linear_clamp_sampler, uvw, 0).rgb;
if (_APVSkyOcclusionWeight > 0)
{
float skyOcclusionL0 = kSHBasis0 * SAMPLE_TEXTURE3D_LOD(apvRes.SkyOcclusionL0L1, s_linear_clamp_sampler, uvw, 0).x;
bakeDiffuseLighting += ambientProbe * skyOcclusionL0;
}
}
else
{
bakeDiffuseLighting = ambientProbe;
}
}
// public APIs for backward compatibility
// to be removed after Unity 6
void EvaluateAdaptiveProbeVolume(in float3 posWS, in float3 normalWS, in float3 backNormalWS, in float3 reflDir, in float3 viewDir, in float2 positionSS, out float3 bakeDiffuseLighting, out float3 backBakeDiffuseLighting, out float3 lightingInReflDir)
{ EvaluateAdaptiveProbeVolume(posWS, normalWS, backNormalWS, reflDir, viewDir, positionSS, 0xFFFFFFFF, bakeDiffuseLighting, backBakeDiffuseLighting, lightingInReflDir); }
void EvaluateAdaptiveProbeVolume(in float3 posWS, in float3 normalWS, in float3 backNormalWS, in float3 viewDir, in float2 positionSS, out float3 bakeDiffuseLighting, out float3 backBakeDiffuseLighting)
{ EvaluateAdaptiveProbeVolume(posWS, normalWS, backNormalWS, viewDir, positionSS, 0xFFFFFFFF, bakeDiffuseLighting, backBakeDiffuseLighting); }
void EvaluateAdaptiveProbeVolume(in float3 posWS, in float3 normalWS, in float3 viewDir, in float2 positionSS, out float3 bakeDiffuseLighting)
{ EvaluateAdaptiveProbeVolume(posWS, normalWS, viewDir, positionSS, 0xFFFFFFFF, bakeDiffuseLighting); }
// -------------------------------------------------------------
// Reflection Probe Normalization functions
// -------------------------------------------------------------
// Same idea as in Rendering of COD:IW [Drobot 2017]
float EvaluateReflectionProbeSH(float3 sampleDir, float4 reflProbeSHL0L1, float4 reflProbeSHL2_1, float reflProbeSHL2_2)
{
float outFactor = 0;
float L0 = reflProbeSHL0L1.x;
float L1 = dot(reflProbeSHL0L1.yzw, sampleDir);
outFactor = L0 + L1;
#ifdef PROBE_VOLUMES_L2
// IMPORTANT: The encoding is unravelled C# side before being sent
float4 vB = sampleDir.xyzz * sampleDir.yzzx;
// First 4 coeff.
float L2 = dot(reflProbeSHL2_1, vB);
float vC = sampleDir.x * sampleDir.x - sampleDir.y * sampleDir.y;
L2 += reflProbeSHL2_2 * vC;
outFactor += L2;
#endif // PROBE_VOLUMES_L2
return outFactor;
}
float GetReflectionProbeNormalizationFactor(float3 lightingInReflDir, float3 sampleDir, float4 reflProbeSHL0L1, float4 reflProbeSHL2_1, float reflProbeSHL2_2)
{
float refProbeNormalization = EvaluateReflectionProbeSH(sampleDir, reflProbeSHL0L1, reflProbeSHL2_1, reflProbeSHL2_2);
float localNormalization = Luminance(real3(lightingInReflDir));
return lerp(1.f, clamp(SafeDiv(localNormalization, refProbeNormalization), _APVMinReflProbeNormalizationFactor, _APVMaxReflProbeNormalizationFactor), _APVWeight);
}
#endif // __PROBEVOLUME_HLSL__
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 688129ab15b222340a2c7fa427269889
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
namespace UnityEngine.Rendering
{
// Only kept for backward compatibility purpose.
[PreferBinarySerialization]
internal class ObsoleteProbeVolumeAsset : ScriptableObject
{
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c1043e08cdc375146bdb853794c4c0fd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,102 @@
namespace UnityEngine.Rendering
{
[System.Serializable]
internal struct ProbeDilationSettings
{
public bool enableDilation;
public float dilationDistance;
public float dilationValidityThreshold;
public int dilationIterations;
public bool squaredDistWeighting;
internal void SetDefaults()
{
enableDilation = false;
dilationDistance = 1;
dilationValidityThreshold = 0.25f;
dilationIterations = 1;
squaredDistWeighting = true;
}
internal void UpgradeFromTo(ProbeVolumeBakingProcessSettings.SettingsVersion from, ProbeVolumeBakingProcessSettings.SettingsVersion to) { }
}
[System.Serializable]
internal struct VirtualOffsetSettings
{
// Duplicated Physics.DefaultRaycastLayers because that dependency is removed from render-pipelines.core. Kept in sync with a unit test.
internal const int kPhysicsDefaultRaycastLayers = ~(1 << 2);
public bool useVirtualOffset;
[Range(0f, 0.95f)] public float validityThreshold;
[Range(0f, 1f)] public float outOfGeoOffset;
[Range(0f, 2f)] public float searchMultiplier;
[Range(-0.05f, 0f)] public float rayOriginBias;
public LayerMask collisionMask;
internal void SetDefaults()
{
useVirtualOffset = true;
validityThreshold = 0.25f;
outOfGeoOffset = 0.01f;
searchMultiplier = 0.2f;
UpgradeFromTo(ProbeVolumeBakingProcessSettings.SettingsVersion.Initial, ProbeVolumeBakingProcessSettings.SettingsVersion.ThreadedVirtualOffset);
}
internal void UpgradeFromTo(ProbeVolumeBakingProcessSettings.SettingsVersion from, ProbeVolumeBakingProcessSettings.SettingsVersion to)
{
if (from < ProbeVolumeBakingProcessSettings.SettingsVersion.ThreadedVirtualOffset && to >= ProbeVolumeBakingProcessSettings.SettingsVersion.ThreadedVirtualOffset)
{
rayOriginBias = -0.001f;
collisionMask = kPhysicsDefaultRaycastLayers;
}
}
}
// TODO: Use this structure in the actual authoring component rather than just a mean to group output parameters.
[System.Serializable]
internal struct ProbeVolumeBakingProcessSettings
{
internal static ProbeVolumeBakingProcessSettings Default { get { var s = new ProbeVolumeBakingProcessSettings(); s.SetDefaults(); return s; } }
internal enum SettingsVersion
{
Initial,
ThreadedVirtualOffset,
Max,
Current = Max - 1
}
internal ProbeVolumeBakingProcessSettings(ProbeDilationSettings dilationSettings, VirtualOffsetSettings virtualOffsetSettings)
{
m_Version = SettingsVersion.Current;
this.dilationSettings = dilationSettings;
this.virtualOffsetSettings = virtualOffsetSettings;
}
internal void SetDefaults()
{
m_Version = SettingsVersion.Current;
dilationSettings.SetDefaults();
virtualOffsetSettings.SetDefaults();
}
internal void Upgrade()
{
if (m_Version != SettingsVersion.Current)
{
// Debug.Log($"Upgrading probe volume baking process settings from '{m_Version}' to '{SettingsVersion.Current}'.");
dilationSettings.UpgradeFromTo(m_Version, SettingsVersion.Current);
virtualOffsetSettings.UpgradeFromTo(m_Version, SettingsVersion.Current);
m_Version = SettingsVersion.Current;
}
}
[SerializeField] SettingsVersion m_Version;
public ProbeDilationSettings dilationSettings;
public VirtualOffsetSettings virtualOffsetSettings;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2ca179cc72ecf4f4fa7d4ed3bb83ffd2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,655 @@
#if UNITY_EDITOR
using System;
using System.IO;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine.SceneManagement;
using Unity.Mathematics;
using Unity.Scripting.LifecycleManagement;
namespace UnityEngine.Rendering
{
// Everything here is only needed in editor for baking or managing baking sets.
public partial class ProbeVolumeBakingSet
{
[Serializable]
internal class SceneBakeData
{
public bool hasProbeVolume = false;
public bool bakeScene = true;
public Bounds bounds = new();
}
internal partial class SceneToBakingSet
{
[AutoStaticsCleanup]
static Dictionary<string, ProbeVolumeBakingSetWeakReference> sceneToBakingSet = null;
internal static Dictionary<string, ProbeVolumeBakingSetWeakReference> Instance
{
get
{
if (sceneToBakingSet == null)
sceneToBakingSet = ProbeVolumeBakingSet.SyncBakingSets();
return sceneToBakingSet;
}
}
// Undo/redo restores a set's serialized scene list without going through Add/Remove/SetScene.
internal static void Resync(ProbeVolumeBakingSet set)
{
if (sceneToBakingSet == null)
return;
var entityId = set.GetEntityId();
var staleGUIDs = new List<string>();
foreach (var kvp in sceneToBakingSet)
{
if (kvp.Value.m_EntityId == entityId && !set.m_SceneGUIDs.Contains(kvp.Key))
staleGUIDs.Add(kvp.Key);
}
foreach (var guid in staleGUIDs)
sceneToBakingSet.Remove(guid);
var reference = new ProbeVolumeBakingSetWeakReference(set);
foreach (var guid in set.m_SceneGUIDs)
{
// Don't steal scenes whose current owner is loaded and still lists them (e.g. a duplicated set asset).
if (sceneToBakingSet.TryGetValue(guid, out var existing) && existing.m_EntityId != entityId)
{
var owner = existing.IsLoaded() ? existing.Get() : null;
if (owner == null || owner.m_SceneGUIDs.Contains(guid))
continue;
}
sceneToBakingSet[guid] = reference;
}
}
}
[SerializeField]
SerializedDictionary<string, SceneBakeData> m_SceneBakeData = new();
/// <summary>
/// Tries to add a scene to the baking set.
/// </summary>
/// <param name ="guid">The GUID of the scene to add.</param>
/// <returns>Whether the scene was successfull added to the baking set.</returns>
public bool TryAddScene(string guid)
{
var sceneSet = GetBakingSetForScene(guid);
if (sceneSet != null)
return false;
AddScene(guid);
return true;
}
internal void AddScene(string guid, SceneBakeData bakeData = null)
{
m_SceneGUIDs.Add(guid);
m_SceneBakeData.Add(guid, bakeData != null ? bakeData : new SceneBakeData());
SceneToBakingSet.Instance[guid] = new ProbeVolumeBakingSetWeakReference(this);
EditorUtility.SetDirty(this);
}
/// <summary>
/// Removes a scene from the baking set.
/// </summary>
/// <param name ="guid">The GUID of the scene to remove.</param>
public void RemoveScene(string guid)
{
m_SceneGUIDs.Remove(guid);
m_SceneBakeData.Remove(guid);
if (SceneToBakingSet.Instance.TryGetValue(guid, out var mapped) && mapped.m_EntityId == this.GetEntityId())
SceneToBakingSet.Instance.Remove(guid);
EditorUtility.SetDirty(this);
}
internal void SetScene(string guid, int index, SceneBakeData bakeData = null)
{
var previousSceneGUID = m_SceneGUIDs[index];
m_SceneGUIDs[index] = guid;
if (SceneToBakingSet.Instance.TryGetValue(previousSceneGUID, out var mapped) && mapped.m_EntityId == this.GetEntityId())
SceneToBakingSet.Instance.Remove(previousSceneGUID);
SceneToBakingSet.Instance[guid] = new ProbeVolumeBakingSetWeakReference(this);
m_SceneBakeData.Add(guid, bakeData != null ? bakeData : new SceneBakeData());
EditorUtility.SetDirty(this);
}
internal void MoveSceneToBakingSet(string guid, int index)
{
var oldBakingSet = GetBakingSetForScene(guid);
var oldBakeData = oldBakingSet.GetSceneBakeData(guid);
if (oldBakingSet.singleSceneMode)
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(oldBakingSet));
else
oldBakingSet.RemoveScene(guid);
if (index == -1)
AddScene(guid, oldBakeData);
else
SetScene(guid, index, oldBakeData);
}
/// <summary>
/// Changes the baking status of a scene. Objects in scenes disabled for baking will still contribute to
/// lighting for other scenes.
/// </summary>
/// <param name ="guid">The GUID of the scene to remove.</param>
/// <param name ="enableForBaking">Wheter or not this scene should be included when baking lighting.</param>
public void SetSceneBaking(string guid, bool enableForBaking)
{
if (m_SceneBakeData.TryGetValue(guid, out var sceneData))
sceneData.bakeScene = enableForBaking;
EditorUtility.SetDirty(this);
}
/// <summary>
/// Changes the baking status of all scenes. Objects in scenes disabled for baking will still contribute to
/// lighting for other scenes.
/// </summary>
/// <param name="enableForBaking">Wheter or not scenes should be included when baking lighting.</param>
public void SetAllSceneBaking(bool enableForBaking)
{
foreach (var kvp in m_SceneBakeData)
kvp.Value.bakeScene = enableForBaking;
EditorUtility.SetDirty(this);
}
/// <summary>
/// Tries to add a lighting scenario to the baking set.
/// </summary>
/// <param name ="name">The name of the scenario to add.</param>
/// <returns>Whether the scenario was successfully created.</returns>
public bool TryAddScenario(string name)
{
if (m_LightingScenarios.Contains(name))
return false;
m_LightingScenarios.Add(name);
EditorUtility.SetDirty(this);
return true;
}
internal string CreateScenario(string name)
{
int index = 1;
string renamed = name;
while (!TryAddScenario(renamed))
renamed = $"{name} ({index++})";
return renamed;
}
/// <summary>
/// Tries to remove a given scenario from the baking set. This will delete associated baked data.
/// </summary>
/// <param name="name">The name of the scenario to remove</param>
/// <returns>Whether the scenario was successfully deleted.</returns>
public bool RemoveScenario(string name)
{
if (scenarios.TryGetValue(name, out var scenarioData))
{
AssetDatabase.DeleteAsset(scenarioData.cellDataAsset.GetAssetPath());
AssetDatabase.DeleteAsset(scenarioData.cellOptionalDataAsset.GetAssetPath());
AssetDatabase.DeleteAsset(scenarioData.cellProbeOcclusionDataAsset.GetAssetPath());
EditorUtility.SetDirty(this);
}
foreach (var cellData in cellDataMap.Values)
{
if (cellData.scenarios.TryGetValue(name, out var cellScenarioData))
{
cellData.CleanupPerScenarioData(cellScenarioData);
cellData.scenarios.Remove(name);
}
}
scenarios.Remove(name);
EditorUtility.SetDirty(this);
return m_LightingScenarios.Remove(name);
}
internal ProbeVolumeBakingSet Clone()
{
var newSet = CreateInstance<ProbeVolumeBakingSet>();
// We don't want to clone everything in the set
// Especially don't copy reference to baked data !
newSet.probeOffset = probeOffset;
newSet.simplificationLevels = simplificationLevels;
newSet.minDistanceBetweenProbes = minDistanceBetweenProbes;
newSet.renderersLayerMask = renderersLayerMask;
newSet.minRendererVolumeSize = minRendererVolumeSize;
newSet.skyOcclusion = skyOcclusion;
newSet.skyOcclusionBakingSamples = skyOcclusionBakingSamples;
newSet.skyOcclusionBakingBounces = skyOcclusionBakingBounces;
newSet.skyOcclusionAverageAlbedo = skyOcclusionAverageAlbedo;
newSet.skyOcclusionBackFaceCulling = skyOcclusionBackFaceCulling;
newSet.skyOcclusionShadingDirection = skyOcclusionShadingDirection;
newSet.useRenderingLayers = useRenderingLayers;
newSet.renderingLayerMasks = renderingLayerMasks != null ? (ProbeLayerMask[])renderingLayerMasks.Clone() : null;
newSet.useRenderingLayers = useRenderingLayers;
newSet.useRenderingLayers = useRenderingLayers;
newSet.useRenderingLayers = useRenderingLayers;
newSet.useRenderingLayers = useRenderingLayers;
return newSet;
}
/// <summary>
/// Determines if the Probe Reference Volume Profile is equivalent to another one.
/// </summary>
/// <param name ="otherProfile">The profile to compare with.</param>
/// <returns>Whether the Probe Reference Volume Profile is equivalent to another one.</returns>
public bool IsEquivalent(ProbeVolumeBakingSet otherProfile)
{
return minDistanceBetweenProbes == otherProfile.minDistanceBetweenProbes &&
cellSizeInMeters == otherProfile.cellSizeInMeters &&
simplificationLevels == otherProfile.simplificationLevels &&
renderersLayerMask == otherProfile.renderersLayerMask;
}
internal void Clear()
{
try
{
AssetDatabase.StartAssetEditing();
if (cellBricksDataAsset != null)
{
DeleteAsset(cellBricksDataAsset.GetAssetPath());
DeleteAsset(cellSharedDataAsset.GetAssetPath());
DeleteAsset(cellSupportDataAsset.GetAssetPath());
cellBricksDataAsset = null;
cellSharedDataAsset = null;
cellSupportDataAsset = null;
}
foreach (var scenarioData in scenarios.Values)
{
if (scenarioData.IsValid())
{
DeleteAsset(scenarioData.cellDataAsset.GetAssetPath());
DeleteAsset(scenarioData.cellOptionalDataAsset.GetAssetPath());
DeleteAsset(scenarioData.cellProbeOcclusionDataAsset.GetAssetPath());
}
}
}
finally
{
AssetDatabase.StopAssetEditing();
AssetDatabase.Refresh();
EditorUtility.SetDirty(this);
}
cellDescs.Clear();
scenarios.Clear();
// All cells should have been released through unloading the scenes first.
Debug.Assert(cellDataMap.Count == 0);
perSceneCellLists.Clear();
foreach (var sceneGUID in sceneGUIDs)
perSceneCellLists.Add(sceneGUID, new List<int>());
}
/// <summary>
/// Renames a given scenario.
/// </summary>
/// <param name="scenario">The original scenario name.</param>
/// <param name="newName">The requested new scenario name.</param>
/// <returns>The new scenario name. The is different than the requested name in case a scenario with the same name already exists.</returns>
public string RenameScenario(string scenario, string newName)
{
if (!m_LightingScenarios.Contains(scenario))
return newName;
m_LightingScenarios.Remove(scenario);
newName = CreateScenario(newName);
// If the scenario was not baked at least once, this does not exist.
if (scenarios.TryGetValue(scenario, out var data))
{
scenarios.Remove(scenario);
scenarios.Add(newName, data);
foreach (var cellData in cellDataMap.Values)
{
if (cellData.scenarios.TryGetValue(scenario, out var cellScenarioData))
{
cellData.scenarios.Add(newName, cellScenarioData);
cellData.scenarios.Remove(scenario);
}
}
GetCellDataFileNames(name, newName, out string cellDataFileName, out string cellOptionalDataFileName, out string cellProbeOcclusionDataFileName);
data.cellDataAsset.RenameAsset(cellDataFileName);
data.cellOptionalDataAsset.RenameAsset(cellOptionalDataFileName);
data.cellProbeOcclusionDataAsset.RenameAsset(cellProbeOcclusionDataFileName);
}
return newName;
}
internal static Dictionary<string, ProbeVolumeBakingSetWeakReference> SyncBakingSets()
{
Dictionary<string, ProbeVolumeBakingSetWeakReference> sceneToBakingSet = new Dictionary<string, ProbeVolumeBakingSetWeakReference>();
var setGUIDs = AssetDatabase.FindAssets("t:" + nameof(ProbeVolumeBakingSet));
foreach (var setGUID in setGUIDs)
{
string bakingSetPath = AssetDatabase.GUIDToAssetPath(setGUID);
bool alreadyLoaded = AssetDatabase.IsMainAssetAtPathLoaded(bakingSetPath);
var set = AssetDatabase.LoadAssetAtPath<ProbeVolumeBakingSet>(bakingSetPath);
if (set != null)
{
// We need to call Migrate here because of Version.RemoveProbeVolumeSceneData step.
// This step needs the obsolete ProbeVolumeSceneData to be initialized first which can happen out of order. Here we now it's ok.
set.Migrate();
var reference = new ProbeVolumeBakingSetWeakReference(set);
foreach (var guid in set.sceneGUIDs)
sceneToBakingSet[guid] = reference;
// If the asset wasn't already in-memory, and we just loaded it into memory, free it, so we don't waste memory.
if (!alreadyLoaded)
reference.Unload();
}
}
return sceneToBakingSet;
}
internal static ProbeVolumeBakingSet GetBakingSetForScene(Dictionary<string, ProbeVolumeBakingSetWeakReference> mapping, string sceneGUID) { return mapping.GetValueOrDefault(sceneGUID, null)?.Get(); }
internal static ProbeVolumeBakingSet GetBakingSetForScene(string sceneGUID) { return SceneToBakingSet.Instance.GetValueOrDefault(sceneGUID, null)?.Get(); }
internal static ProbeVolumeBakingSet GetBakingSetForScene(Scene scene) => GetBakingSetForScene(scene.GetGUID());
internal void SetDefaults()
{
settings.SetDefaults();
m_LightingScenarios = new List<string> { ProbeReferenceVolume.defaultLightingScenario };
// We have to initialize that to not trigger a warning on new baking sets
chunkSizeInBricks = ProbeBrickPool.GetChunkSizeInBrickCount();
}
string GetOrCreateFileName(ProbeVolumeStreamableAsset asset, string filePath)
{
string res = string.Empty;
if (asset != null && asset.IsValid())
res = asset.GetAssetPath();
if (string.IsNullOrEmpty(res))
res = filePath;
return res;
}
internal void EnsureScenarioAssetNameConsistencyForUndo()
{
foreach (var scenario in scenarios)
{
var scenarioName = scenario.Key;
var scenarioData = scenario.Value;
GetCellDataFileNames(name, scenarioName, out string cellDataFileName, out string cellOptionalDataFileName, out string cellProbeOcclusionDataFileName);
if (!scenarioData.cellDataAsset.GetAssetPath().Contains(cellDataFileName))
{
scenarioData.cellDataAsset.RenameAsset(cellDataFileName);
scenarioData.cellOptionalDataAsset.RenameAsset(cellOptionalDataFileName);
scenarioData.cellProbeOcclusionDataAsset.RenameAsset(cellProbeOcclusionDataFileName);
}
}
}
internal void GetCellDataFileNames(string basePath, string scenario, out string cellDataFileName, out string cellOptionalDataFileName, out string cellProbeOcclusionDataFileName)
{
cellDataFileName = $"{basePath}-{scenario}.CellData.bytes";
cellOptionalDataFileName = $"{basePath}-{scenario}.CellOptionalData.bytes";
cellProbeOcclusionDataFileName = $"{basePath}-{scenario}.CellProbeOcclusionData.bytes";
}
internal void GetBlobFileNames(string scenario, out string cellDataFilename, out string cellBricksDataFilename, out string cellOptionalDataFilename, out string cellProbeOcclusionDataFilename, out string cellSharedDataFilename, out string cellSupportDataFilename)
{
string baseDir = Path.GetDirectoryName(AssetDatabase.GetAssetPath(this));
string basePath = Path.Combine(baseDir, name);
GetCellDataFileNames(basePath, scenario, out string dataFile, out string optionalDataFile, out string probeOcclusionDataFile);
cellDataFilename = GetOrCreateFileName(scenarios[scenario].cellDataAsset, dataFile);
cellOptionalDataFilename = GetOrCreateFileName(scenarios[scenario].cellOptionalDataAsset, optionalDataFile);
cellProbeOcclusionDataFilename = GetOrCreateFileName(scenarios[scenario].cellProbeOcclusionDataAsset, probeOcclusionDataFile);
cellBricksDataFilename = GetOrCreateFileName(cellBricksDataAsset, basePath + ".CellBricksData.bytes");
cellSharedDataFilename = GetOrCreateFileName(cellSharedDataAsset, basePath + ".CellSharedData.bytes");
cellSupportDataFilename = GetOrCreateFileName(cellSupportDataAsset, basePath + ".CellSupportData.bytes");
}
// Returns the file size in bytes
long GetFileSize(string path) => File.Exists(path) ? new FileInfo(path).Length : 0;
internal long GetDiskSizeOfSharedData()
{
if (cellSharedDataAsset == null || !cellSharedDataAsset.IsValid())
return 0;
return GetFileSize(cellBricksDataAsset.GetAssetPath()) + GetFileSize(cellSharedDataAsset.GetAssetPath()) + GetFileSize(cellSupportDataAsset.GetAssetPath());
}
internal long GetDiskSizeOfScenarioData(string scenario)
{
if (scenario == null || !scenarios.TryGetValue(scenario, out var data) || !data.IsValid())
return 0;
return GetFileSize(data.cellDataAsset.GetAssetPath()) + GetFileSize(data.cellOptionalDataAsset.GetAssetPath()) + GetFileSize(data.cellProbeOcclusionDataAsset.GetAssetPath());
}
internal void SanitizeScenes()
{
// Remove entries in the list pointing to deleted scenes
for (int i = m_SceneGUIDs.Count - 1; i >= 0; i--)
{
string path = UnityEditor.AssetDatabase.GUIDToAssetPath(m_SceneGUIDs[i]);
if (UnityEditor.AssetDatabase.LoadAssetAtPath<UnityEditor.SceneAsset>(path) == null)
RemoveScene(m_SceneGUIDs[i]);
}
}
void DeleteAsset(string assetPath)
{
if (string.IsNullOrEmpty(assetPath))
return;
AssetDatabase.DeleteAsset(assetPath);
}
internal bool HasBeenBaked()
{
return cellSharedDataAsset.IsValid();
}
internal static string GetDirectory(string scenePath, string sceneName)
{
string sceneDir = Path.GetDirectoryName(scenePath);
string assetPath = Path.Combine(sceneDir, sceneName);
if (!AssetDatabase.IsValidFolder(assetPath))
AssetDatabase.CreateFolder(sceneDir, sceneName);
return assetPath;
}
internal static void OnSceneSaving(Scene scene, string path = null)
{
// If we are called from the scene callback, we want to update all global volumes that are potentially affected
bool onSceneSave = path != null;
string sceneGUID = ProbeReferenceVolume.GetSceneGUID(scene);
var bakingSet = GetBakingSetForScene(sceneGUID);
if (bakingSet != null)
{
bakingSet.UpdateSceneBounds(scene, sceneGUID, onSceneSave);
bakingSet.EnsurePerSceneData(scene, sceneGUID);
}
}
static internal int MaxSubdivLevelInProbeVolume(Vector3 volumeSize, int maxSubdiv)
{
float maxSizedDim = Mathf.Max(volumeSize.x, Mathf.Max(volumeSize.y, volumeSize.z));
float maxSideInBricks = maxSizedDim / ProbeReferenceVolume.instance.MinDistanceBetweenProbes();
int subdiv = Mathf.FloorToInt(Mathf.Log(maxSideInBricks, 3)) - 1;
return Mathf.Max(subdiv, maxSubdiv);
}
static void InflateBound(ref Bounds bounds, ProbeVolume pv)
{
Bounds originalBounds = bounds;
// Round the probe volume bounds to cell size
float cellSize = ProbeReferenceVolume.instance.MaxBrickSize();
Vector3 cellOffset = ProbeReferenceVolume.instance.ProbeOffset();
// Expand the probe volume bounds to snap on the cell size grid
bounds.Encapsulate((Vector3)math.floor((bounds.min - cellOffset) / cellSize) * cellSize + cellOffset);
bounds.Encapsulate((Vector3)math.ceil((bounds.max - cellOffset) / cellSize) * cellSize + cellOffset);
// calculate how much padding we need to remove according to the brick generation in ProbePlacement.cs:
var cellSizeVector = new Vector3(cellSize, cellSize, cellSize);
var minPadding = (bounds.min - originalBounds.min);
var maxPadding = (bounds.max - originalBounds.max);
minPadding = cellSizeVector - new Vector3(Mathf.Abs(minPadding.x), Mathf.Abs(minPadding.y), Mathf.Abs(minPadding.z));
maxPadding = cellSizeVector - new Vector3(Mathf.Abs(maxPadding.x), Mathf.Abs(maxPadding.y), Mathf.Abs(maxPadding.z));
// Find the size of the brick we can put for every axis given the padding size
int maxSubdiv = ProbeReferenceVolume.instance.GetMaxSubdivision() - 1;
if (pv.overridesSubdivLevels) maxSubdiv = Mathf.Min(pv.highestSubdivLevelOverride, maxSubdiv);
float rightPaddingSubdivLevel = ProbeReferenceVolume.instance.BrickSize(MaxSubdivLevelInProbeVolume(new Vector3(maxPadding.x, originalBounds.size.y, originalBounds.size.z), maxSubdiv));
float leftPaddingSubdivLevel = ProbeReferenceVolume.instance.BrickSize(MaxSubdivLevelInProbeVolume(new Vector3(minPadding.x, originalBounds.size.y, originalBounds.size.z), maxSubdiv));
float topPaddingSubdivLevel = ProbeReferenceVolume.instance.BrickSize(MaxSubdivLevelInProbeVolume(new Vector3(originalBounds.size.x, maxPadding.y, originalBounds.size.z), maxSubdiv));
float bottomPaddingSubdivLevel = ProbeReferenceVolume.instance.BrickSize(MaxSubdivLevelInProbeVolume(new Vector3(originalBounds.size.x, minPadding.y, originalBounds.size.z), maxSubdiv));
float forwardPaddingSubdivLevel = ProbeReferenceVolume.instance.BrickSize(MaxSubdivLevelInProbeVolume(new Vector3(originalBounds.size.x, originalBounds.size.y, maxPadding.z), maxSubdiv));
float backPaddingSubdivLevel = ProbeReferenceVolume.instance.BrickSize(MaxSubdivLevelInProbeVolume(new Vector3(originalBounds.size.x, originalBounds.size.y, minPadding.z), maxSubdiv));
// Remove the extra padding caused by cell rounding
bounds.min = bounds.min + new Vector3(
leftPaddingSubdivLevel * Mathf.Floor(Mathf.Abs(bounds.min.x - originalBounds.min.x) / (float)leftPaddingSubdivLevel),
bottomPaddingSubdivLevel * Mathf.Floor(Mathf.Abs(bounds.min.y - originalBounds.min.y) / (float)bottomPaddingSubdivLevel),
backPaddingSubdivLevel * Mathf.Floor(Mathf.Abs(bounds.min.z - originalBounds.min.z) / (float)backPaddingSubdivLevel)
);
bounds.max = bounds.max - new Vector3(
rightPaddingSubdivLevel * Mathf.Floor(Mathf.Abs(bounds.max.x - originalBounds.max.x) / (float)rightPaddingSubdivLevel),
topPaddingSubdivLevel * Mathf.Floor(Mathf.Abs(bounds.max.y - originalBounds.max.y) / (float)topPaddingSubdivLevel),
forwardPaddingSubdivLevel * Mathf.Floor(Mathf.Abs(bounds.max.z - originalBounds.max.z) / (float)forwardPaddingSubdivLevel)
);
}
internal void UpdateSceneBounds(Scene scene, string sceneGUID, bool onSceneSave)
{
var volumes = FindObjectsByType<ProbeVolume>();
float prevBrickSize = ProbeReferenceVolume.instance.MinBrickSize();
int prevMaxSubdiv = ProbeReferenceVolume.instance.GetMaxSubdivision();
Vector3 prevOffset = ProbeReferenceVolume.instance.ProbeOffset();
if (onSceneSave) // Use baked values
ProbeReferenceVolume.instance.SetSubdivisionDimensions(minBrickSize, maxSubdivision, bakedProbeOffset);
else // Use displayed values
ProbeReferenceVolume.instance.SetSubdivisionDimensions(GetMinBrickSize(minDistanceBetweenProbes), GetMaxSubdivision(simplificationLevels), probeOffset);
bool boundFound = false;
Bounds newBound = new Bounds();
foreach (var volume in volumes)
{
bool forceUpdate = onSceneSave && volume.mode == ProbeVolume.Mode.Global;
if (!forceUpdate && volume.gameObject.scene != scene)
continue;
if (volume.mode != ProbeVolume.Mode.Local)
volume.UpdateGlobalVolume(volume.mode == ProbeVolume.Mode.Global ? GIContributors.ContributorFilter.All : GIContributors.ContributorFilter.Scene);
var obb = new ProbeReferenceVolume.Volume(volume.GetVolume(), 0, 0);
Bounds localBounds = obb.CalculateAABB();
InflateBound(ref localBounds, volume);
if (!boundFound)
{
newBound = localBounds;
boundFound = true;
}
else
{
newBound.Encapsulate(localBounds);
}
}
bool bakeDataExist = m_SceneBakeData.TryGetValue(sceneGUID, out var bakeData);
Debug.Assert(bakeDataExist, "Scene should have been added to the baking set with default bake data instance.");
bakeData.hasProbeVolume = boundFound;
if (boundFound)
bakeData.bounds = newBound;
ProbeReferenceVolume.instance.SetSubdivisionDimensions(prevBrickSize, prevMaxSubdiv, prevOffset);
EditorUtility.SetDirty(this);
}
// It is important this is called after UpdateSceneBounds is called otherwise SceneHasProbeVolumes might be out of date
internal void EnsurePerSceneData(Scene scene, string sceneGUID)
{
bool bakeDataExist = m_SceneBakeData.TryGetValue(sceneGUID, out var bakeData);
Debug.Assert(bakeDataExist, "Scene should have been added to the baking set with default bake data instance.");
if (bakeData.hasProbeVolume)
{
if (!ProbeReferenceVolume.instance.TryGetPerSceneData(sceneGUID, out var data))
{
GameObject go = new GameObject("ProbeVolumePerSceneData");
go.hideFlags |= HideFlags.HideInHierarchy;
var perSceneData = go.AddComponent<ProbeVolumePerSceneData>();
SceneManager.MoveGameObjectToScene(go, scene);
}
}
}
internal SceneBakeData GetSceneBakeData(string sceneGUID, bool addIfMissing = true)
{
if (!m_SceneBakeData.TryGetValue(sceneGUID, out var bakeData) && addIfMissing)
{
if (m_SceneGUIDs.Contains(sceneGUID))
m_SceneBakeData[sceneGUID] = bakeData = new SceneBakeData();
}
return bakeData;
}
internal static bool SceneHasProbeVolumes(string sceneGUID)
{
var bakingSet = GetBakingSetForScene(sceneGUID);
return bakingSet?.GetSceneBakeData(sceneGUID)?.hasProbeVolume ?? false;
}
internal bool DialogNoProbeVolumeInSetShown()
{
return dialogNoProbeVolumeInSetShown;
}
internal void SetDialogNoProbeVolumeInSetShown(bool value)
{
dialogNoProbeVolumeInSetShown = value;
}
}
}
#endif
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c74704f1b85e9e94fbc165484fbf7985
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4881f9a2c4d568047b316028d20a8dca
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,75 @@
namespace UnityEngine.Rendering
{
// Q: What is this?
// A: A utility class for storing a reference to a ProbeVolumeBakingSet, without forcing the object to be loaded in-memory.
// Q: Why do we need this?
// A: APV uses a lot of global state, and we aren't always good with cleaning it up. Unity's serialization layer will automatically
// load referenced assets into memory, recursively. Some of the assets referenced by ProbeVolumeBakingSet can get very large, on
// the order of several gigabytes. A lingering global reference to a ProbeVolumeBakingSet can keep these assets in memory indefinitely,
// preventing them from being garbage collected. By using a weak reference, we prevent this - ProbeVolumeBakingSet can be freely
// garbage collected. Whenever we actually need to access it, we load it on-demand, if it isn't already in memory.
internal class ProbeVolumeBakingSetWeakReference
{
public EntityId m_EntityId;
public ProbeVolumeBakingSetWeakReference(ProbeVolumeBakingSet bakingSet)
{
Set(bakingSet);
}
public ProbeVolumeBakingSetWeakReference()
{
m_EntityId = EntityId.None;
}
// Change which baking set the references points to.
public void Set(ProbeVolumeBakingSet bakingSet)
{
if (bakingSet == null)
m_EntityId = EntityId.None;
else
m_EntityId = bakingSet.GetEntityId();
}
// Get the referenced baking set, loading it into memory if necessary.
public ProbeVolumeBakingSet Get()
{
return Resources.EntityIdToObject(m_EntityId) as ProbeVolumeBakingSet;
}
// Is the referenced baking set in memory?
public bool IsLoaded()
{
return Resources.EntityIdIsValid(m_EntityId);
}
// Force the referenced baking set to be unloaded from memory.
// Calling Get() after Unload() will re-load the baking set into memory.
public void Unload()
{
if (!IsLoaded())
return;
var bakingSet = Get();
// These assets would get garbage collected, but we clean them up immediately to free memory earlier.
// Only do this in editor, where the assets are never needed, so we don't unload assets that may still be in use.
#if UNITY_EDITOR
Resources.UnloadAsset(bakingSet.cellBricksDataAsset?.asset);
Resources.UnloadAsset(bakingSet.cellSharedDataAsset?.asset);
Resources.UnloadAsset(bakingSet.cellSupportDataAsset?.asset);
foreach (var scenario in bakingSet.scenarios)
{
Resources.UnloadAsset(scenario.Value.cellDataAsset?.asset);
Resources.UnloadAsset(scenario.Value.cellOptionalDataAsset?.asset);
Resources.UnloadAsset(scenario.Value.cellProbeOcclusionDataAsset?.asset);
}
#endif
// Unload the baking set itself.
Resources.UnloadAsset(bakingSet);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ec6eec0d49474f845b4288cb1dc2525a
@@ -0,0 +1,82 @@
//#pragma enable_d3d11_debug_symbols
#pragma kernel BlendScenarios
#pragma multi_compile _ PROBE_VOLUMES_L2
#pragma multi_compile _ USE_APV_PROBE_OCCLUSION
#include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBlendStates.hlsl"
Texture3D<float4> _State0_L0_L1Rx;
Texture3D<float4> _State0_L1G_L1Ry;
Texture3D<float4> _State0_L1B_L1Rz;
Texture3D<float4> _State1_L0_L1Rx;
Texture3D<float4> _State1_L1G_L1Ry;
Texture3D<float4> _State1_L1B_L1Rz;
RWTexture3D<half4> _Out_L0_L1Rx;
RWTexture3D<unorm float4> _Out_L1G_L1Ry;
RWTexture3D<unorm float4> _Out_L1B_L1Rz;
#ifdef PROBE_VOLUMES_L2
Texture3D<float4> _State0_L2_0;
Texture3D<float4> _State0_L2_1;
Texture3D<float4> _State0_L2_2;
Texture3D<float4> _State0_L2_3;
Texture3D<float4> _State1_L2_0;
Texture3D<float4> _State1_L2_1;
Texture3D<float4> _State1_L2_2;
Texture3D<float4> _State1_L2_3;
RWTexture3D<unorm float4> _Out_L2_0;
RWTexture3D<unorm float4> _Out_L2_1;
RWTexture3D<unorm float4> _Out_L2_2;
RWTexture3D<unorm float4> _Out_L2_3;
#endif
#ifdef USE_APV_PROBE_OCCLUSION
Texture3D<float4> _State0_ProbeOcclusion;
Texture3D<float4> _State1_ProbeOcclusion;
RWTexture3D<unorm float4> _Out_ProbeOcclusion;
#endif
float4 _ChunkList[1000];
float4 _PoolDim_LerpFactor;
#define _DstPoolDim _PoolDim_LerpFactor.xy
#define _LerpFactor _PoolDim_LerpFactor.z
uint3 IndexToChunk(uint index, float2 poolSize)
{
uint coordZ = index / (poolSize.x*poolSize.y);
uint offsetXY = index - coordZ * (poolSize.x*poolSize.y);
return uint3(offsetXY % poolSize.x, offsetXY / poolSize.x, coordZ);
}
[numthreads(4, 4, 4)]
void BlendScenarios(uint3 probe : SV_DispatchThreadID, uint3 brick : SV_GroupID)
{
uint chunkIndex = brick.z;
probe.z -= 4 * chunkIndex;
// Load
APVResources resources0, resources1;
LOAD_APV_RES(resources0, _State0);
LOAD_APV_RES(resources1, _State1);
uint3 srcChunk = _ChunkList[chunkIndex].xyz;
APVSample state0 = LoadAndDecodeAPV(resources0, probe + srcChunk);
APVSample state1 = LoadAndDecodeAPV(resources1, probe + srcChunk);
// Blend
state0 = BlendAPVSamples(state0, state1, half(_LerpFactor));
// Store
APVResourcesRW output;
LOAD_APV_RES(output, _Out);
uint3 dstChunk = IndexToChunk(_ChunkList[chunkIndex].w, _DstPoolDim);
EncodeAndStoreAPV(output, state0, probe + dstChunk);
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a3f7b8c99de28a94684cb1daebeccf5d
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,50 @@
#ifndef BLEND_STATES
#define BLEND_STATES
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl"
APVSample BlendAPVSamples(APVSample state0, APVSample state1, half factor)
{
APVSample result;
result.L0 = lerp(state0.L0, state1.L0, factor);
result.L1_R = lerp(state0.L1_R, state1.L1_R, factor);
result.L1_G = lerp(state0.L1_G, state1.L1_G, factor);
result.L1_B = lerp(state0.L1_B, state1.L1_B, factor);
#ifdef PROBE_VOLUMES_L2
result.L2_R = lerp(state0.L2_R, state1.L2_R, factor);
result.L2_G = lerp(state0.L2_G, state1.L2_G, factor);
result.L2_B = lerp(state0.L2_B, state1.L2_B, factor);
result.L2_C = lerp(state0.L2_C, state1.L2_C, factor);
#endif
#ifdef USE_APV_PROBE_OCCLUSION
result.probeOcclusion = lerp(state0.probeOcclusion, state1.probeOcclusion, factor);
#endif
result.status = APV_SAMPLE_STATUS_DECODED;
return result;
}
void EncodeAndStoreAPV(APVResourcesRW apvRes, APVSample apvSample, int3 loc)
{
apvSample.Encode();
float4 L0_L1Rx = float4(apvSample.L0, apvSample.L1_R.x);
float4 L1G_L1Ry = float4(apvSample.L1_G, apvSample.L1_R.y);
float4 L1B_L1Rz = float4(apvSample.L1_B, apvSample.L1_R.z);
apvRes.L0_L1Rx [loc].rgba = L0_L1Rx;
apvRes.L1G_L1Ry[loc].rgba = L1G_L1Ry;
apvRes.L1B_L1Rz[loc].rgba = L1B_L1Rz;
#ifdef PROBE_VOLUMES_L2
apvRes.L2_0[loc].rgba = apvSample.L2_R;
apvRes.L2_1[loc].rgba = apvSample.L2_G;
apvRes.L2_2[loc].rgba = apvSample.L2_B;
apvRes.L2_3[loc].rgba = float4(apvSample.L2_C, 0.0f);
#endif
#ifdef USE_APV_PROBE_OCCLUSION
apvRes.ProbeOcclusion[loc].rgba = apvSample.probeOcclusion;
#endif
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: e478f7f7b57c7ab46a2933b408f63161
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,312 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.Mathematics;
using RuntimeResources = UnityEngine.Rendering.ProbeReferenceVolume.RuntimeResources;
namespace UnityEngine.Rendering
{
static class ProbeVolumeConstantRuntimeResources
{
static ComputeBuffer m_SkySamplingDirectionsBuffer = null;
static ComputeBuffer m_AntiLeakDataBuffer = null;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
CoreUtils.SafeRelease(m_SkySamplingDirectionsBuffer);
m_SkySamplingDirectionsBuffer = null;
CoreUtils.SafeRelease(m_AntiLeakDataBuffer);
m_AntiLeakDataBuffer = null;
Array.Clear(k_SkyDirections, 0, k_SkyDirections.Length);
}
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void GetRuntimeResources(ref RuntimeResources rr)
{
rr.SkyPrecomputedDirections = m_SkySamplingDirectionsBuffer;
rr.QualityLeakReductionData = m_AntiLeakDataBuffer;
}
internal static void Initialize()
{
if (m_SkySamplingDirectionsBuffer == null)
{
k_SkyDirections = GenerateSkyDirections();
m_SkySamplingDirectionsBuffer = new ComputeBuffer(k_SkyDirections.Length, 3 * sizeof(float));
m_SkySamplingDirectionsBuffer.SetData(k_SkyDirections);
}
if (m_AntiLeakDataBuffer == null)
{
m_AntiLeakDataBuffer = new ComputeBuffer(k_AntiLeakData.Length, sizeof(uint));
m_AntiLeakDataBuffer.SetData(k_AntiLeakData);
}
}
public static Vector3[] GetSkySamplingDirections()
{
return k_SkyDirections;
}
internal static void Cleanup()
{
CoreUtils.SafeRelease(m_SkySamplingDirectionsBuffer);
m_SkySamplingDirectionsBuffer = null;
CoreUtils.SafeRelease(m_AntiLeakDataBuffer);
m_AntiLeakDataBuffer = null;
}
#region Sky Directions Buffer generator
const int NB_SKY_PRECOMPUTED_DIRECTIONS = 255;
static Vector3[] k_SkyDirections = new Vector3[NB_SKY_PRECOMPUTED_DIRECTIONS];
static Vector3[] GenerateSkyDirections()
{
var skyDirections = new Vector3[NB_SKY_PRECOMPUTED_DIRECTIONS];
float sqrtNBpoints = Mathf.Sqrt((float)(NB_SKY_PRECOMPUTED_DIRECTIONS));
float phi = 0.0f;
float phiMax = 0.0f;
float thetaMax = 0.0f;
// Spiral based sampling on sphere
// See http://web.archive.org/web/20120331125729/http://www.math.niu.edu/~rusin/known-math/97/spherefaq
// http://www.math.vanderbilt.edu/saffeb/texts/161.pdf
for (int i=0; i < NB_SKY_PRECOMPUTED_DIRECTIONS; i++)
{
// theta from 0 to PI
// phi from 0 to 2PI
float h = -1.0f + (2.0f * i) / (NB_SKY_PRECOMPUTED_DIRECTIONS - 1.0f);
float theta = Mathf.Acos(h);
if (i == NB_SKY_PRECOMPUTED_DIRECTIONS - 1 || i==0)
phi = 0.0f;
else
phi = phi + 3.6f / sqrtNBpoints * 1.0f / (Mathf.Sqrt(1.0f-h*h));
Vector3 pointOnSphere = new Vector3(Mathf.Sin(theta) * Mathf.Cos(phi), Mathf.Sin(theta) * Mathf.Sin(phi), Mathf.Cos(theta));
pointOnSphere.Normalize();
skyDirections[i] = pointOnSphere;
phiMax = Mathf.Max(phiMax, phi);
thetaMax = Mathf.Max(thetaMax, theta);
}
return skyDirections;
}
#endregion
#region AntiLeak Buffer generator
#if UNITY_EDITOR
static uint3 GetSampleOffset(uint i)
{
return new uint3(i, i >> 1, i >> 2) & 1;
}
static int GetProbeIndex(int x, int y, int z)
{
return x + y * 2 + z * 4;
}
static uint BuildFace(int axis, int idx)
{
uint mask = 0;
int[] coords = new int[3];
coords[axis] = idx;
for (int i = 0; i < 2; i++)
{
coords[(axis + 1) % 3] = i;
for (int j = 0; j < 2; j++)
{
coords[(axis + 2) % 3] = j;
mask = mask | (uint)(1 << GetProbeIndex(coords[0], coords[1], coords[2]));
}
}
return mask;
}
static bool TryGetEdge(uint validityMask, uint samplingMask, out uint edge, out uint3 offset)
{
for (int i = 0; i < 8; i++)
{
if ((validityMask & (1 << i)) == 0)
continue;
uint3 p = GetSampleOffset((uint)i);
if (p.x == 0)
{
edge = (1u << i) | (1u << GetProbeIndex(1, (int)p.y, (int)p.z));
if ((validityMask & edge) == edge && (samplingMask & edge) == 0)
{
offset = 2 * p;
offset.x = 1;
return true;
}
}
if (p.y == 0)
{
edge = (1u << i) | (1u << GetProbeIndex((int)p.x, 1, (int)p.z));
if ((validityMask & edge) == edge && (samplingMask & edge) == 0)
{
offset = 2 * p;
offset.y = 1;
return true;
}
}
if (p.z == 0)
{
edge = (1u << i) | (1u << GetProbeIndex((int)p.x, (int)p.y, 1));
if ((validityMask & edge) == edge && (samplingMask & edge) == 0)
{
offset = 2 * p;
offset.z = 1;
return true;
}
}
}
edge = 0;
offset = 0;
return false;
}
static List<uint3> ComputeMask(uint validityMask)
{
List<uint3> samples = new();
// Cube sample
if (validityMask == 0 || validityMask == 255)
{
samples.Add(1);
return samples;
}
// track which probes are sampled
uint samplingMask = 0;
// Find face sample
for (int i = 0; i < 6; i++)
{
int axis = i / 2;
uint face = BuildFace(axis, i % 2);
if ((validityMask & face) == face) // all face is valid, sample it
{
uint3 offset = 0;
offset[axis] = (i % 2) == 0 ? 0u : 2u;
offset[(axis + 1) % 3] = 1;
offset[(axis + 2) % 3] = 1;
samples.Add(offset);
samplingMask = face;
break;
}
}
// Find edge samples
while (true)
{
if (!TryGetEdge(validityMask, samplingMask, out uint edge, out uint3 offset))
break;
samples.Add(offset);
samplingMask |= edge;
}
// Find single probe samples
for (int i = 0; i < 8; i++)
{
if (((1 << i) & (validityMask & ~samplingMask)) == 0)
continue;
samples.Add(2 * GetSampleOffset((uint)i));
samplingMask |= (uint)(1 << i);
}
return samples;
}
static uint PackSamplingDir(uint val)
{
// On a single axis there is up to 2 probes. A face or edge sample needs to sample in between the probes
// We encode 0 as sample first probe, 1 as sample between probe, 2 as sample second probe (2 bits)
// For faster decoding, we use a third bit that reduces ALU in shader
return /* 2 bits */ (val << 1) | /* 1 bit */ ((~val & 2) >> 1);
}
static uint InvalidSampleMask()
{
// This is a special code that results in no sampling in shader without any additional ALU
return 2 | (2 << 3) | (2 << 6);
}
static uint ComputeAntiLeakData(uint validityMask)
{
// This may generate more than 3 samples, but we limit to 3
var samples = ComputeMask(validityMask);
uint mask = 0;
for (int i = 0; i < 3; i++)
{
uint sampleMask;
if (i < samples.Count)
sampleMask = PackSamplingDir(samples[i].x) | (PackSamplingDir(samples[i].y) << 3) | (PackSamplingDir(samples[i].z) << 6);
else
sampleMask = InvalidSampleMask();
// 32bits - 9bits per samples (up to 3 samples)
// Each sample encodes sampling on each axis (3axis * 3bits)
// See PackSamplingDir for axis encoding
mask |= sampleMask << (9 * i);
}
return mask;
}
//[UnityEditor.MenuItem("Edit/Rendering/Global Illumination/Generate AntiLeak Buffer")]
static uint[] BuildAntiLeakDataArray()
{
uint[] antileak = new uint[256];
for (uint validityMask = 0; validityMask < 256; validityMask++)
antileak[validityMask] = ComputeAntiLeakData(validityMask);
string str = "static readonly uint[] k_AntiLeakData = new uint[256] {\n";
for (int i = 0; i < 16; i++)
{
str += " ";
for (int j = 0; j < 16; j++)
{
str += antileak[i * 16 + j] + (j == 15 ? ",\n" : ", ");
}
}
str += " };";
Debug.Log(str);
return antileak;
}
#endif
// This is autogenerated using the MenuItem above -- do not edit by hand
static readonly uint[] k_AntiLeakData = new uint[256] {
38347995, 38347849, 38347852, 38347851, 38347873, 38347865, 38322764, 38322763, 38347876, 38324297, 38347868, 38324299, 38347875, 38324313, 38322780, 38347867,
38348041, 38347977, 38408780, 38408779, 38408801, 38408793, 69517900, 69517899, 38408804, 38324425, 38408796, 69519435, 38408803, 69519449, 69517916, 38408795,
38348044, 38410313, 38347980, 38410315, 38410337, 38410329, 38322892, 70304331, 38410340, 70305865, 38410332, 70305867, 38410339, 70305881, 70304348, 38410331,
38348043, 38410441, 38408908, 38347979, 38322955, 38409817, 69518028, 38322891, 38324491, 70305993, 38409820, 38324427, 38409827, 26351193, 25564764, 38323915,
38348065, 38421065, 38421068, 38421067, 38348001, 38421081, 38312161, 38388299, 38421092, 75810889, 38421084, 75810891, 38421091, 75810905, 38388316, 38421083,
38348057, 38421193, 38312217, 38416971, 38408929, 38347993, 69507297, 38312153, 38324505, 75811017, 38416988, 26358347, 38416995, 38324441, 69583452, 38320345,
38421260, 75896905, 38421196, 75896907, 38410465, 75896921, 38388428, 70369867, 75896932, 70305865, 75896924, 70305867, 75896931, 70305881, 70369884, 75896923,
38421259, 75897033, 38417100, 38421195, 38409953, 38410457, 69583564, 38377689, 75811083, 70305993, 75896412, 75811019, 75896419, 70306009, 70107740, 70301913,
38348068, 38422601, 38422604, 38422603, 38422625, 38422617, 76595788, 76595787, 38348004, 38310628, 38422620, 38389835, 38422627, 38389849, 76595804, 38422619,
38422793, 38422729, 76681804, 76681803, 76681825, 76681817, 69517900, 69517899, 38408932, 38389961, 76681820, 69584971, 76681827, 69584985, 69517916, 76681819,
38348060, 38310684, 38422732, 38418507, 38322972, 38418521, 76595916, 25573451, 38410468, 70292196, 38347996, 38310620, 38418531, 70371417, 38322908, 38318812,
38422795, 38418633, 76681932, 38422731, 76595979, 76682841, 69518028, 76595915, 38409956, 70371529, 38408924, 38376156, 76682851, 70109273, 69518044, 69513948,
38348067, 38310691, 38312227, 38422091, 38422753, 38422105, 76585185, 76661323, 38421220, 75797220, 38422108, 75876427, 38348003, 38310627, 38312163, 38311651,
38422809, 38422217, 76585241, 76689995, 76681953, 38422745, 69507297, 76585177, 38417124, 75876553, 76690012, 73779275, 38408931, 38389977, 69507299, 76593369,
38421276, 75797276, 38422220, 75905099, 38418657, 75905113, 76661452, 74564171, 75897060, 70292196, 38421212, 75797212, 38410467, 70292195, 38388444, 75805404,
38348059, 38310683, 38312219, 38422219, 38322971, 38418649, 25467163, 76650713, 38324507, 26252059, 38417116, 75862748, 38409955, 70371545, 69583580, 38347995,
};
#endregion
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 048170d3a5da040f2b4a67567f20e84d
@@ -0,0 +1,501 @@
using System.Collections.Generic;
using Unity.Profiling;
using Unity.Profiling.LowLevel;
using UnityEngine.SceneManagement;
#if UNITY_EDITOR
using UnityEditor;
using ProbeVolumeWithBoundsList = System.Collections.Generic.List<(UnityEngine.Rendering.ProbeVolume component, UnityEngine.Rendering.ProbeReferenceVolume.Volume volume, UnityEngine.Bounds bounds)>;
#endif
namespace UnityEngine.Rendering
{
struct GIContributors
{
#if UNITY_EDITOR
/// <summary>
/// Collects all GI-contributing renderers and terrains from the scene (or selection).
/// For terrains, also resolves tree prototype meshes and computes per-instance bounds.
/// Cost scales with total scene renderer and terrain count.
/// </summary>
static readonly ProfilerMarker k_FindGIContributors =
new ProfilerMarker(ProfilerCategory.Render, "GIContributors.Find", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Iterates all scene renderers returned by <c>FindObjectsByType</c>, filtering to
/// those that are active, LOD0, have a <c>MeshFilter</c>, and contribute GI.
/// </summary>
static readonly ProfilerMarker k_FindRenderers =
new ProfilerMarker(ProfilerCategory.Render, "Find Renderers", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Iterates all scene terrains returned by <c>FindObjectsByType</c>, filtering to
/// those that are active and have valid terrain data, and resolves their tree prototypes.
/// </summary>
static readonly ProfilerMarker k_FindTerrains =
new ProfilerMarker(ProfilerCategory.Render, "Find Terrains", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Filters the full GI contributor lists to those overlapping a given baking cell and
/// at least one probe volume, applying both spatial bounds and per-probe-volume size and
/// layer mask rules.
/// </summary>
static readonly ProfilerMarker k_FilterGIContributors =
new ProfilerMarker(ProfilerCategory.Render, "Filter GIContributors", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Tests each renderer's bounds against the cell AABB and all probe volumes, keeping
/// only those that pass the OBB-AABB intersection and the minimum bounding-volume-size
/// filter.
/// </summary>
static readonly ProfilerMarker k_FilterRenderers =
new ProfilerMarker(ProfilerCategory.Render, "Filter Renderers", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Tests each terrain's bounds against the cell AABB and probe volumes, then culls
/// individual tree instances for each prototype. Cost scales with terrain tree instance count
/// when trees are present.
/// </summary>
static readonly ProfilerMarker k_FilterTerrains =
new ProfilerMarker(ProfilerCategory.Render, "Filter Terrains", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Filters the full GI contributor lists by layer mask only, without spatial bounds
/// checks. Used when per-cell spatial culling is not required.
/// </summary>
static readonly ProfilerMarker k_FilterGIContributorsLayerMask =
new ProfilerMarker(ProfilerCategory.Render, "Filter GIContributors LayerMask", MarkerFlags.VerbosityAdvanced);
static GIContributors Create()
{
GIContributors contributors;
contributors.renderers = new();
#if ENABLE_TERRAIN_MODULE
contributors.terrains = new();
#endif
return contributors;
}
#if ENABLE_TERRAIN_MODULE
public struct TerrainContributor
{
public struct TreePrototype
{
public MeshRenderer component;
public Matrix4x4 transform;
public Bounds prefabBounds;
public List<(Matrix4x4 transform, Bounds boundsWS)> instances;
}
public Terrain component;
public Bounds boundsWithTrees;
public Bounds boundsTerrainOnly;
public TreePrototype[] treePrototypes;
}
public List<TerrainContributor> terrains;
#endif
public List<(Renderer component, Bounds bounds)> renderers;
public int Count =>
#if ENABLE_TERRAIN_MODULE
renderers.Count + terrains.Count;
#else
renderers.Count;
#endif
internal enum ContributorFilter { All, Scene, Selection };
internal static bool ContributesGI(GameObject go) =>
(GameObjectUtility.GetStaticEditorFlags(go) & StaticEditorFlags.ContributeGI) != 0;
// Scratch buffer reused across calls to avoid per-call allocation. Every code path fully
// writes all 8 elements before reading, so no per-Play-Mode reset is needed (a readonly
// array of unmanaged elements is exempt from the statics-cleanup analyzer).
static readonly Vector3[] m_Vertices = new Vector3[8];
static Bounds TransformBounds(Bounds bounds, Matrix4x4 transform)
{
Vector3 boundsMin = bounds.min, boundsMax = bounds.max;
m_Vertices[0] = new Vector3(boundsMin.x, boundsMin.y, boundsMin.z);
m_Vertices[1] = new Vector3(boundsMax.x, boundsMin.y, boundsMin.z);
m_Vertices[2] = new Vector3(boundsMax.x, boundsMax.y, boundsMin.z);
m_Vertices[3] = new Vector3(boundsMin.x, boundsMax.y, boundsMin.z);
m_Vertices[4] = new Vector3(boundsMin.x, boundsMin.y, boundsMax.z);
m_Vertices[5] = new Vector3(boundsMax.x, boundsMin.y, boundsMax.z);
m_Vertices[6] = new Vector3(boundsMax.x, boundsMax.y, boundsMax.z);
m_Vertices[7] = new Vector3(boundsMin.x, boundsMax.y, boundsMax.z);
Vector3 min = transform.MultiplyPoint(m_Vertices[0]);
Vector3 max = min;
for (int i = 1; i < 8; i++)
{
var point = transform.MultiplyPoint(m_Vertices[i]);
min = Vector3.Min(min, point);
max = Vector3.Max(max, point);
}
Bounds result = default;
result.SetMinMax(min, max);
return result;
}
#if ENABLE_TERRAIN_MODULE
static internal Matrix4x4 GetTreeInstanceTransform(Terrain terrain, TreeInstance tree)
{
var position = terrain.GetPosition() + Vector3.Scale(tree.position, terrain.terrainData.size);
var rotation = Quaternion.Euler(0, tree.rotation * Mathf.Rad2Deg, 0);
var scale = new Vector3(tree.widthScale, tree.heightScale, tree.widthScale);
return Matrix4x4.TRS(position, rotation, scale);
}
#endif
public static GIContributors Find(ContributorFilter filter, Scene? scene = null)
{
if (filter == ContributorFilter.Scene && scene == null)
return default;
using var _ = k_FindGIContributors.Auto();
var contributors = GIContributors.Create();
void PushRenderer(Renderer renderer)
{
if (!ContributesGI(renderer.gameObject) || !renderer.gameObject.TryGetComponent<MeshFilter>(out var _) || !renderer.gameObject.activeInHierarchy || !renderer.enabled || !renderer.isLOD0)
return;
var bounds = renderer.bounds;
bounds.size += Vector3.one * 0.01f;
contributors.renderers.Add((renderer, bounds));
}
#if ENABLE_TERRAIN_MODULE
void PushTerrain(Terrain terrain)
{
if (!ContributesGI(terrain.gameObject) || !terrain.gameObject.activeInHierarchy || !terrain.enabled || terrain.terrainData == null)
return;
var terrainData = terrain.terrainData;
var terrainBounds = terrainData.bounds;
terrainBounds.center += terrain.GetPosition();
terrainBounds.size += Vector3.one * 0.01f;
var prototypes = terrainData.treePrototypes;
var treePrototypes = new TerrainContributor.TreePrototype[prototypes.Length];
for (int i = 0; i < prototypes.Length; i++)
{
MeshRenderer renderer = null;
var prefab = prototypes[i].prefab;
if (prefab == null)
continue;
if (prefab.TryGetComponent<LODGroup>(out var lodGroup))
{
var groups = lodGroup.GetLODs();
if (groups.Length != 0 && groups[0].renderers.Length != 0)
renderer = groups[0].renderers[0] as MeshRenderer;
}
if (renderer == null)
renderer = prefab.GetComponent<MeshRenderer>();
if (renderer != null && renderer.enabled && ContributesGI(renderer.gameObject))
{
var tr = prefab.transform;
// For some reason, tree instances are not affected by rotation and position of prefab root
// But they are affected by scale, and by any other transform in the hierarchy
var transform = Matrix4x4.TRS(tr.position, tr.rotation, Vector3.one).inverse * renderer.localToWorldMatrix;
// Compute prefab bounds. This will be used to compute highest tree to expand terrain bounds
// and to approximate the bounds of tree instances for culling during voxelization.
var prefabBounds = TransformBounds(renderer.localBounds, transform);
treePrototypes[i] = new TerrainContributor.TreePrototype()
{
component = renderer,
transform = transform,
prefabBounds = prefabBounds,
instances = new List<(Matrix4x4 transform, Bounds boundsWS)>(),
};
}
}
Vector3 totalMax = terrainBounds.max;
foreach (var tree in terrainData.treeInstances)
{
var prototype = treePrototypes[tree.prototypeIndex];
if (prototype.component == null)
continue;
// Approximate instance bounds since rotation can only be on y axis
var transform = GetTreeInstanceTransform(terrain, tree);
var boundsCenter = transform.MultiplyPoint(prototype.prefabBounds.center);
var boundsSize = prototype.prefabBounds.size;
float maxTreeWidth = Mathf.Max(boundsSize.x, boundsSize.z) * tree.widthScale * Mathf.Sqrt(2.0f);
boundsSize = new Vector3(maxTreeWidth, boundsSize.y * tree.heightScale, maxTreeWidth);
prototype.instances.Add((transform, new Bounds(boundsCenter, boundsSize)));
totalMax.y = Mathf.Max(boundsCenter.y + boundsSize.y * 0.5f, totalMax.y);
}
var totalBounds = new Bounds();
totalBounds.SetMinMax(terrainBounds.min, totalMax);
contributors.terrains.Add(new TerrainContributor()
{
component = terrain,
boundsWithTrees = totalBounds,
boundsTerrainOnly = terrainBounds,
treePrototypes = treePrototypes,
});
}
#endif
if (filter == ContributorFilter.Selection)
{
var transforms = Selection.transforms;
foreach (var transform in transforms)
{
var childrens = transform.gameObject.GetComponentsInChildren<Transform>();
foreach (var children in childrens)
{
if (children.gameObject.TryGetComponent(out Renderer renderer))
PushRenderer(renderer);
#if ENABLE_TERRAIN_MODULE
else if (children.gameObject.TryGetComponent(out Terrain terrain))
PushTerrain(terrain);
#endif
}
}
}
else
{
#pragma warning disable CS0618 // Type or member is obsolete
var renderers = Object.FindObjectsByType<Renderer>(FindObjectsSortMode.InstanceID);
#pragma warning restore CS0618 // Type or member is obsolete
using (k_FindRenderers.Auto())
{
foreach (var renderer in renderers)
{
if (filter != ContributorFilter.Scene || renderer.gameObject.scene == scene)
PushRenderer(renderer);
}
}
#if ENABLE_TERRAIN_MODULE
#pragma warning disable CS0618 // Type or member is obsolete
var terrains = Object.FindObjectsByType<Terrain>(FindObjectsSortMode.InstanceID);
#pragma warning restore CS0618 // Type or member is obsolete
using (k_FindTerrains.Auto())
{
foreach (var terrain in terrains)
{
if (filter != ContributorFilter.Scene || terrain.gameObject.scene == scene)
PushTerrain(terrain);
}
}
#endif
}
return contributors;
}
static bool DiscardedByProbeVolume(ProbeVolume pv, ProbeVolumeBakingSet bakingSet, float boundsVolume, int layerMask)
{
if (bakingSet == null)
return false;
float minRendererBoundingBoxSize = bakingSet.minRendererVolumeSize;
var renderersLayerMask = bakingSet.renderersLayerMask;
if (pv.overrideRendererFilters)
{
minRendererBoundingBoxSize = pv.minRendererVolumeSize;
renderersLayerMask = pv.objectLayerMask;
}
// Skip renderers that have a smaller volume than the min volume size from the profile or probe volume component
// And renderers whose layer mask is excluded
return (boundsVolume < minRendererBoundingBoxSize) || (layerMask & renderersLayerMask) == 0;
}
public GIContributors Filter(ProbeVolumeBakingSet bakingSet, Bounds cellBounds, ProbeVolumeWithBoundsList probeVolumes)
{
k_FilterGIContributors.Begin();
var contributors = GIContributors.Create();
k_FilterRenderers.Begin();
foreach (var renderer in renderers)
{
if (!cellBounds.Intersects(renderer.bounds))
continue;
var volumeSize = renderer.bounds.size;
float rendererBoundsVolume = volumeSize.x * volumeSize.y * volumeSize.z;
int rendererLayerMask = 1 << renderer.component.gameObject.layer;
foreach (var probeVolume in probeVolumes)
{
if (DiscardedByProbeVolume(probeVolume.component, bakingSet, rendererBoundsVolume, rendererLayerMask) ||
!ProbeVolumePositioning.OBBAABBIntersect(probeVolume.volume, renderer.bounds, probeVolume.bounds))
continue;
contributors.renderers.Add(renderer);
break;
}
}
k_FilterRenderers.End();
#if ENABLE_TERRAIN_MODULE
k_FilterTerrains.Begin();
foreach (var terrain in terrains)
{
if (!cellBounds.Intersects(terrain.boundsWithTrees))
continue;
var volumeSize = terrain.boundsWithTrees.size;
float terrainBoundsVolume = volumeSize.x * volumeSize.y * volumeSize.z;
int terrainLayerMask = 1 << terrain.component.gameObject.layer;
// Find if terrain with trees hits at least one PV
bool contributes = false;
foreach (var probeVolume in probeVolumes)
{
if (DiscardedByProbeVolume(probeVolume.component, bakingSet, terrainBoundsVolume, terrainLayerMask) ||
!ProbeVolumePositioning.OBBAABBIntersect(probeVolume.volume, terrain.boundsWithTrees, probeVolume.bounds))
continue;
contributes = true;
break;
}
if (!contributes)
continue;
// Cull trees - iterates over all instances for each pv, may be very slow
var probeVolumesForProto = new List<Bounds>();
Vector3 totalMax = terrain.boundsTerrainOnly.max;
var treePrototypes = new TerrainContributor.TreePrototype[terrain.treePrototypes.Length];
for (int i = 0; i < treePrototypes.Length; i++)
{
var srcProto = terrain.treePrototypes[i];
// This prototype may have been previously filtered out
if (srcProto.component == null)
continue;
// Find which pv may intersect instances of this proto
probeVolumesForProto.Clear();
int prototypeLayerMask = 1 << srcProto.component.gameObject.layer;
foreach (var probeVolume in probeVolumes)
{
// Ignore bounds volume check for trees, assume they are always big enough
// Otherwise we have to do the complex math stuff to compute the actual tree bounds
if (!DiscardedByProbeVolume(probeVolume.component, bakingSet, float.MaxValue, prototypeLayerMask))
probeVolumesForProto.Add(probeVolume.bounds);
}
if (probeVolumesForProto.Count == 0)
continue;
treePrototypes[i] = new TerrainContributor.TreePrototype()
{
component = srcProto.component,
transform = srcProto.transform,
prefabBounds = srcProto.prefabBounds,
instances = new List<(Matrix4x4 transform, Bounds boundsWS)>(),
};
// Cull tree instances
for (int j = 0; j < srcProto.instances.Count; j++)
{
var treeBounds = srcProto.instances[j].boundsWS;
if (!treeBounds.Intersects(cellBounds))
continue;
foreach (var pvAABB in probeVolumesForProto)
{
if (treeBounds.Intersects(pvAABB))
{
treePrototypes[i].instances.Add(srcProto.instances[j]);
totalMax.y = Mathf.Max(treeBounds.max.y, totalMax.y);
break;
}
}
}
}
// Recompute terrain bounds by excluding trees that were filtered out
var totalBounds = new Bounds();
totalBounds.SetMinMax(terrain.boundsTerrainOnly.min, totalMax);
var terrainContrib = new TerrainContributor()
{
component = terrain.component,
boundsWithTrees = totalBounds,
boundsTerrainOnly = terrain.boundsTerrainOnly,
treePrototypes = treePrototypes,
};
contributors.terrains.Add(terrainContrib);
}
k_FilterTerrains.End();
#endif
k_FilterGIContributors.End();
return contributors;
}
public GIContributors FilterLayerMaskOnly(LayerMask layerMask)
{
k_FilterGIContributorsLayerMask.Begin();
var contributors = GIContributors.Create();
foreach (var renderer in renderers)
{
int rendererLayerMask = 1 << renderer.component.gameObject.layer;
if ((rendererLayerMask & layerMask) != 0)
contributors.renderers.Add(renderer);
}
#if ENABLE_TERRAIN_MODULE
foreach (var terrain in terrains)
{
int terrainLayerMask = 1 << terrain.component.gameObject.layer;
if ((terrainLayerMask & layerMask) != 0)
{
// Filter out trees
var filteredPrototypes = new List<TerrainContributor.TreePrototype>();
foreach (var treeProto in terrain.treePrototypes)
{
// check if the mesh renderer exists
if (treeProto.component != null)
{
int treeProtoLayerMask = 1 << treeProto.component.gameObject.layer;
if ((treeProtoLayerMask & layerMask) != 0)
filteredPrototypes.Add(treeProto);
}
}
var terrainContrib = new TerrainContributor()
{
component = terrain.component,
boundsWithTrees = terrain.boundsWithTrees,
boundsTerrainOnly = terrain.boundsTerrainOnly,
treePrototypes = filteredPrototypes.ToArray(),
};
contributors.terrains.Add(terrainContrib);
}
}
#endif
k_FilterGIContributorsLayerMask.End();
return contributors;
}
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d6b61523d2d66384485b5ef359496dd9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,101 @@
using System;
namespace UnityEngine.Rendering
{
[Serializable]
[SupportedOnRenderPipeline()]
[Categorization.CategoryInfo(Name = "R: Adaptive Probe Volumes", Order = 1000), HideInInspector]
class ProbeVolumeRuntimeResources : IRenderPipelineResources
{
[SerializeField, HideInInspector]
int m_Version = 1;
public int version { get => m_Version; }
[Header("Runtime")]
[ResourcePath("Runtime/Lighting/ProbeVolume/ProbeVolumeBlendStates.compute")]
public ComputeShader probeVolumeBlendStatesCS;
[ResourcePath("Runtime/Lighting/ProbeVolume/ProbeVolumeUploadData.compute")]
public ComputeShader probeVolumeUploadDataCS;
[ResourcePath("Runtime/Lighting/ProbeVolume/ProbeVolumeUploadDataL2.compute")]
public ComputeShader probeVolumeUploadDataL2CS;
}
[Serializable]
[SupportedOnRenderPipeline()]
[Categorization.CategoryInfo(Name = "R: Adaptive Probe Volumes", Order = 1000), HideInInspector]
class ProbeVolumeDebugResources : IRenderPipelineResources
{
[SerializeField, HideInInspector]
int m_Version = 1;
public int version { get => m_Version; }
[Header("Debug")]
[ResourcePath("Runtime/Debug/ProbeVolumeDebug.shader")]
public Shader probeVolumeDebugShader;
[ResourcePath("Runtime/Debug/ProbeVolumeFragmentationDebug.shader")]
public Shader probeVolumeFragmentationDebugShader;
[ResourcePath("Runtime/Debug/ProbeVolumeSamplingDebug.shader")]
public Shader probeVolumeSamplingDebugShader;
[ResourcePath("Runtime/Debug/ProbeVolumeOffsetDebug.shader")]
public Shader probeVolumeOffsetDebugShader;
[ResourcePath("Runtime/Debug/ProbeSamplingDebugMesh.fbx")]
public Mesh probeSamplingDebugMesh;
[ResourcePath("Runtime/Debug/ProbeVolumeNumbersDisplayTex.png")]
public Texture2D numbersDisplayTex;
}
[Serializable]
[SupportedOnRenderPipeline()]
[Categorization.CategoryInfo(Name = "R: Adaptive Probe Volumes", Order = 1000), HideInInspector]
class ProbeVolumeBakingResources : IRenderPipelineResources
{
[SerializeField, HideInInspector]
int m_Version = 1;
public int version { get => m_Version; }
[Header("Baking")]
[ResourcePath("Editor/Lighting/ProbeVolume/ProbeVolumeCellDilation.compute")]
public ComputeShader dilationShader;
[ResourcePath("Editor/Lighting/ProbeVolume/ProbeVolumeSubdivide.compute")]
public ComputeShader subdivideSceneCS;
[ResourcePath("Editor/Lighting/ProbeVolume/VoxelizeScene.shader")]
public Shader voxelizeSceneShader;
[ResourcePath("Editor/Lighting/ProbeVolume/VirtualOffset/TraceVirtualOffset.urtshader")]
public ComputeShader traceVirtualOffsetCS;
[ResourcePath("Editor/Lighting/ProbeVolume/VirtualOffset/TraceVirtualOffset.urtshader")]
public RayTracingShader traceVirtualOffsetRT;
[ResourcePath("Editor/Lighting/ProbeVolume/DynamicGI/DynamicGISkyOcclusion.urtshader")]
public ComputeShader skyOcclusionCS;
[ResourcePath("Editor/Lighting/ProbeVolume/DynamicGI/DynamicGISkyOcclusion.urtshader")]
public RayTracingShader skyOcclusionRT;
[ResourcePath("Editor/Lighting/ProbeVolume/RenderingLayerMask/TraceRenderingLayerMask.urtshader")]
public ComputeShader renderingLayerCS;
[ResourcePath("Editor/Lighting/ProbeVolume/RenderingLayerMask/TraceRenderingLayerMask.urtshader")]
public RayTracingShader renderingLayerRT;
}
[Serializable]
[SupportedOnRenderPipeline()]
[Categorization.CategoryInfo(Name = "Lighting", Order = 20)]
class ProbeVolumeGlobalSettings : IRenderPipelineGraphicsSettings
{
[SerializeField, HideInInspector]
int m_Version = 1;
[SerializeField, Tooltip("Enabling this will make APV baked data assets compatible with Addressables and Asset Bundles. This will also make Disk Streaming unavailable. After changing this setting, a clean rebuild may be required for data assets to be included in Adressables and Asset Bundles.")]
bool m_ProbeVolumeDisableStreamingAssets;
public int version { get => m_Version; }
public bool probeVolumeDisableStreamingAssets
{
get => m_ProbeVolumeDisableStreamingAssets;
set => this.SetValueAndNotify(ref m_ProbeVolumeDisableStreamingAssets, value, nameof(m_ProbeVolumeDisableStreamingAssets));
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6f793e729125fbd4c8fd3f5f79653b47
@@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using UnityEngine.Serialization;
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
#endif
namespace UnityEngine.Rendering
{
/// <summary>
/// A component that stores baked probe volume state and data references. Normally hidden in the hierarchy.
/// </summary>
[ExecuteAlways]
[AddComponentMenu("")] // Hide.
public class ProbeVolumePerSceneData : MonoBehaviour
{
/// <summary>The baking set this scene is part of.</summary>
public ProbeVolumeBakingSet bakingSet => serializedBakingSet;
// Warning: this is the baking set this scene was part of during last bake
// It shouldn't be used while baking as the scene may have been moved since then
[SerializeField, FormerlySerializedAs("bakingSet")] internal ProbeVolumeBakingSet serializedBakingSet;
[SerializeField] internal string sceneGUID = "";
// All code bellow is only kept in order to be able to cleanup obsolete data.
[Serializable]
internal struct ObsoletePerScenarioData
{
public int sceneHash;
public TextAsset cellDataAsset; // Contains L0 L1 SH data
public TextAsset cellOptionalDataAsset; // Contains L2 SH data
}
[Serializable]
struct ObsoleteSerializablePerScenarioDataItem
{
#pragma warning disable 649 // is never assigned to, and will always have its default value
public string scenario;
public ObsoletePerScenarioData data;
#pragma warning restore 649
}
[FormerlySerializedAs("asset")]
[SerializeField] internal ObsoleteProbeVolumeAsset obsoleteAsset;
[FormerlySerializedAs("cellSharedDataAsset")]
[SerializeField] internal TextAsset obsoleteCellSharedDataAsset; // Contains bricks and validity data
[FormerlySerializedAs("cellSupportDataAsset")]
[SerializeField] internal TextAsset obsoleteCellSupportDataAsset; // Contains debug data
[FormerlySerializedAs("serializedScenarios")]
[SerializeField] List<ObsoleteSerializablePerScenarioDataItem> obsoleteSerializedScenarios = new();
#if UNITY_EDITOR
void DeleteAsset(Object asset)
{
if (asset != null && AssetDatabase.TryGetGUIDAndLocalFileIdentifier(asset, out string guid, out long instanceID))
{
var assetPath = AssetDatabase.GUIDToAssetPath(guid);
AssetDatabase.DeleteAsset(assetPath);
}
}
#endif
internal void Clear()
{
QueueSceneRemoval();
serializedBakingSet = null;
#if UNITY_EDITOR
EditorUtility.SetDirty(this);
#endif
}
internal void QueueSceneLoading()
{
if (serializedBakingSet == null)
return;
#if UNITY_EDITOR
// Check if we are trying to load APV data for a scene which has not enabled APV (or it was removed)
var bakedData = serializedBakingSet.GetSceneBakeData(sceneGUID, addIfMissing: false);
if (bakedData != null && bakedData.hasProbeVolume == false)
return;
#endif
var refVol = ProbeReferenceVolume.instance;
refVol.AddPendingSceneLoading(sceneGUID, serializedBakingSet);
}
internal void QueueSceneRemoval()
{
if (serializedBakingSet != null)
ProbeReferenceVolume.instance.AddPendingSceneRemoval(sceneGUID);
}
void OnEnable()
{
#if UNITY_EDITOR
// In the editor, always refresh the GUID as it may become out of date is scene is duplicated or other weird things
// This field is serialized, so it will be available in standalones, where it can't change anymore.
// Only change the GUID if the new one is valid.
var newGUID = gameObject.scene.GetGUID();
if (newGUID != sceneGUID && new GUID(newGUID) != default)
{
sceneGUID = newGUID;
EditorUtility.SetDirty(this);
}
#endif
ProbeReferenceVolume.instance.RegisterPerSceneData(this);
}
void OnDisable()
{
QueueSceneRemoval();
ProbeReferenceVolume.instance.UnregisterPerSceneData(this);
}
private void OnValidate()
{
#if UNITY_EDITOR
// Cleanup old obsolete data.
if (obsoleteAsset != null)
{
DeleteAsset(obsoleteAsset);
DeleteAsset(obsoleteCellSharedDataAsset);
DeleteAsset(obsoleteCellSupportDataAsset);
foreach(var scenario in obsoleteSerializedScenarios)
{
DeleteAsset(scenario.data.cellDataAsset);
DeleteAsset(scenario.data.cellOptionalDataAsset);
}
obsoleteAsset = null;
obsoleteCellSharedDataAsset = null;
obsoleteCellSupportDataAsset = null;
obsoleteSerializedScenarios = null;
EditorUtility.SetDirty(this);
}
#endif
}
internal void Initialize()
{
ProbeReferenceVolume.instance.RegisterBakingSet(this);
QueueSceneRemoval();
QueueSceneLoading();
}
internal bool ResolveCellData()
{
if (serializedBakingSet != null)
return serializedBakingSet.ResolveCellData(serializedBakingSet.GetSceneCellIndexList(sceneGUID));
return false;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a83d2f7ae04ab6f4f99b0d85377be998
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,135 @@
namespace UnityEngine.Rendering
{
internal static class ProbeVolumePositioning
{
// Scratch buffers reused across calls to avoid per-call allocation.
// Every code path fully writes all elements before reading — no reset needed on domain reload.
static readonly Vector3[] m_Axes = new Vector3[6];
static readonly Vector3[] m_AABBCorners = new Vector3[8];
public static bool OBBIntersect(in ProbeReferenceVolume.Volume a, in ProbeReferenceVolume.Volume b)
{
// First we test if the bounding spheres intersects, in which case we case do the more complex OBB test
a.CalculateCenterAndSize(out var aCenter, out var aSize);
b.CalculateCenterAndSize(out var bCenter, out var bSize);
var aRadius = aSize.sqrMagnitude / 2.0f;
var bRadius = bSize.sqrMagnitude / 2.0f;
if (Vector3.SqrMagnitude(aCenter - bCenter) > aRadius + bRadius)
return false;
m_Axes[0] = a.X.normalized;
m_Axes[1] = a.Y.normalized;
m_Axes[2] = a.Z.normalized;
m_Axes[3] = b.X.normalized;
m_Axes[4] = b.Y.normalized;
m_Axes[5] = b.Z.normalized;
for (int i = 0; i < 6; i++)
{
Vector2 aProj = ProjectOBB(in a, m_Axes[i]);
Vector2 bProj = ProjectOBB(in b, m_Axes[i]);
if (aProj.y < bProj.x || bProj.y < aProj.x)
{
return false;
}
}
return true;
}
public static bool OBBContains(in ProbeReferenceVolume.Volume obb, Vector3 point)
{
float lenX2 = obb.X.sqrMagnitude;
float lenY2 = obb.Y.sqrMagnitude;
float lenZ2 = obb.Z.sqrMagnitude;
// Project in OBB space
point -= obb.corner;
point = new Vector3(Vector3.Dot(point, obb.X), Vector3.Dot(point, obb.Y), Vector3.Dot(point, obb.Z));
return (0.0f < point.x && point.x < lenX2) && (0.0f < point.y && point.y < lenY2) && (0.0f < point.z && point.z < lenZ2);
}
// Test between a OBB and an AABB. The AABB of the OBB is requested to avoid recalculating it
public static bool OBBAABBIntersect(in ProbeReferenceVolume.Volume a, in Bounds b, in Bounds aAABB)
{
// First perform fast AABB test
if (!aAABB.Intersects(b))
return false;
// Perform complex OBB test
Vector3 boundsMin = b.min, boundsMax = b.max;
m_AABBCorners[0] = new Vector3(boundsMin.x, boundsMin.y, boundsMin.z);
m_AABBCorners[1] = new Vector3(boundsMax.x, boundsMin.y, boundsMin.z);
m_AABBCorners[2] = new Vector3(boundsMax.x, boundsMax.y, boundsMin.z);
m_AABBCorners[3] = new Vector3(boundsMin.x, boundsMax.y, boundsMin.z);
m_AABBCorners[4] = new Vector3(boundsMin.x, boundsMin.y, boundsMax.z);
m_AABBCorners[5] = new Vector3(boundsMax.x, boundsMin.y, boundsMax.z);
m_AABBCorners[6] = new Vector3(boundsMax.x, boundsMax.y, boundsMax.z);
m_AABBCorners[7] = new Vector3(boundsMin.x, boundsMax.y, boundsMax.z);
m_Axes[0] = a.X.normalized;
m_Axes[1] = a.Y.normalized;
m_Axes[2] = a.Z.normalized;
for (int i = 0; i < 3; i++)
{
Vector2 aProj = ProjectOBB(in a, m_Axes[i]);
Vector2 bProj = ProjectAABB(m_AABBCorners, m_Axes[i]);
if (aProj.y < bProj.x || bProj.y < aProj.x)
{
return false;
}
}
return true;
}
static Vector2 ProjectOBB(in ProbeReferenceVolume.Volume a, Vector3 axis)
{
float min = Vector3.Dot(axis, a.corner);
float max = min;
for (int x = 0; x < 2; x++)
{
for (int y = 0; y < 2; y++)
{
for (int z = 0; z < 2; z++)
{
Vector3 vert = a.corner + a.X * x + a.Y * y + a.Z * z;
float proj = Vector3.Dot(axis, vert);
if (proj < min)
{
min = proj;
}
else if (proj > max)
{
max = proj;
}
}
}
}
return new Vector2(min, max);
}
static Vector2 ProjectAABB(in Vector3[] corners, Vector3 axis)
{
float min = Vector3.Dot(axis, corners[0]);
float max = min;
for (int i = 1; i < 8; i++)
{
float proj = Vector3.Dot(axis, corners[i]);
if (proj < min) min = proj;
else if (proj > max) max = proj;
}
return new Vector2(min, max);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a55ec696682683040ab8b67b9175f1a0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,44 @@
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine.Serialization;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Rendering
{
// Add Profile and baking settings.
/// <summary> A class containing info about the bounds defined by the probe volumes in various scenes. </summary>
[System.Serializable]
[Obsolete("This class is no longer necessary for APV implementation. #from(2023.3)")]
public class ProbeVolumeSceneData
{
internal Object parentAsset = null;
[SerializeField, FormerlySerializedAs("sceneBounds"), Obsolete("This data is now serialized directly in the baking set asset. #from(2023.3)")]
internal SerializedDictionary<string, Bounds> obsoleteSceneBounds;
[SerializeField, FormerlySerializedAs("hasProbeVolumes"), Obsolete("This data is now serialized directly in the baking set asset. #from(2023.3)")]
internal SerializedDictionary<string, bool> obsoleteHasProbeVolumes;
/// <summary>
/// Constructor for ProbeVolumeSceneData.
/// </summary>
/// <param name="parentAsset">The asset holding this ProbeVolumeSceneData, it will be dirtied every time scene bounds or settings are changed.</param>
public ProbeVolumeSceneData(Object parentAsset)
{
SetParentObject(parentAsset);
}
/// <summary>Set a reference to the object holding this ProbeVolumeSceneData.</summary>
/// <param name="parent">The object holding this ProbeVolumeSceneData, it will be dirtied every time scene bounds or settings are changed. </param>
[Obsolete("#from(2023.3)")]
public void SetParentObject(Object parent)
{
parentAsset = parent;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 04fb4740d8c6dbc469086e13c435cd4b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,274 @@
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Unity.Collections;
using CellStreamingScratchBuffer = UnityEngine.Rendering.ProbeReferenceVolume.CellStreamingScratchBuffer;
using CellStreamingScratchBufferLayout = UnityEngine.Rendering.ProbeReferenceVolume.CellStreamingScratchBufferLayout;
namespace UnityEngine.Rendering
{
class ProbeVolumeScratchBufferPool
{
[DebuggerDisplay("ChunkCount = {chunkCount} ElementCount = {pool.Count}")]
class ScratchBufferPool
: IComparable<ScratchBufferPool>
{
public int chunkCount = -1;
public Stack<CellStreamingScratchBuffer> pool = new Stack<CellStreamingScratchBuffer>();
public ScratchBufferPool(int chunkCount)
{
this.chunkCount = chunkCount;
}
private ScratchBufferPool()
{
}
public int CompareTo(ScratchBufferPool other)
{
if (chunkCount < other.chunkCount)
return -1;
else if (chunkCount > other.chunkCount)
return 1;
else
return 0;
}
}
// Size in bytes of a full SH chunk (L0+L1+L2+ValidityMask+Occlusion)
public int chunkSize { get; private set; }
// Maximum number of chunks that should allocated in total. This is a hint, size may differ a bit to ensure at least one scratch buffer for each required size.
public int maxChunkCount { get; private set; }
public int allocatedMemory => chunkSize * m_CurrentlyAllocatedChunkCount;
int m_L0Size;
int m_L1Size;
int m_ValiditySize;
int m_ValidityLayerCount;
int m_L2Size;
int m_ProbeOcclusionSize;
int m_SkyOcclusionSize;
int m_SkyShadingDirectionSize;
int m_CurrentlyAllocatedChunkCount = 0;
// List and not a Dictionary because we need the list sorted.
List<ScratchBufferPool> m_Pools = new List<ScratchBufferPool>();
// We store layouts separately because we might use a bigger buffer than required but we still want the layout to match the exact chunk count.
Dictionary<int, CellStreamingScratchBufferLayout> m_Layouts = new Dictionary<int, CellStreamingScratchBufferLayout>();
public ProbeVolumeScratchBufferPool(ProbeVolumeBakingSet bakingSet, ProbeVolumeSHBands shBands)
{
chunkSize = bakingSet.GetChunkGPUMemory(shBands);
maxChunkCount = bakingSet.maxSHChunkCount;
m_L0Size = bakingSet.L0ChunkSize;
m_L1Size = bakingSet.L1ChunkSize;
m_ValiditySize = bakingSet.sharedValidityMaskChunkSize;
m_ValidityLayerCount = bakingSet.bakedMaskCount;
m_SkyOcclusionSize = bakingSet.sharedSkyOcclusionL0L1ChunkSize;
m_SkyShadingDirectionSize = bakingSet.sharedSkyShadingDirectionIndicesChunkSize;
m_L2Size = bakingSet.L2TextureChunkSize;
m_ProbeOcclusionSize = bakingSet.ProbeOcclusionChunkSize;
}
CellStreamingScratchBufferLayout GetOrCreateScratchBufferLayout(int chunkCount)
{
if (m_Layouts.TryGetValue(chunkCount, out var layout))
{
return layout;
}
else
{
var bufferLayout = new CellStreamingScratchBufferLayout();
bufferLayout._L0Size = m_L0Size;
bufferLayout._L1Size = m_L1Size;
bufferLayout._ValiditySize = m_ValiditySize;
bufferLayout._ValidityProbeSize = m_ValidityLayerCount; // 1layer => 1xbyte => 4 probes at a time.
if (m_SkyOcclusionSize != 0)
{
bufferLayout._SkyOcclusionSize = m_SkyOcclusionSize;
bufferLayout._SkyOcclusionProbeSize = 8; // 4xFP16
if (m_SkyShadingDirectionSize != 0)
{
bufferLayout._SkyShadingDirectionSize = m_SkyShadingDirectionSize;
bufferLayout._SkyShadingDirectionProbeSize = 1; // 1xbyte => 4 probes at a time.
}
else
{
bufferLayout._SkyShadingDirectionSize = 0;
bufferLayout._SkyShadingDirectionProbeSize = 0;
}
}
else
{
bufferLayout._SkyOcclusionSize = 0;
bufferLayout._SkyOcclusionProbeSize = 0;
bufferLayout._SkyShadingDirectionSize = 0;
bufferLayout._SkyShadingDirectionProbeSize = 0;
}
bufferLayout._L2Size = m_L2Size;
if (m_ProbeOcclusionSize != 0)
{
bufferLayout._ProbeOcclusionSize = m_ProbeOcclusionSize;
bufferLayout._ProbeOcclusionProbeSize = 4; // 4xbyte
}
else
{
bufferLayout._ProbeOcclusionSize = 0;
bufferLayout._ProbeOcclusionProbeSize = 0;
}
// TODO: Find a generic way to pass this down? (depends on the gfx format we use).
bufferLayout._L0ProbeSize = 8; // 4xFP16
bufferLayout._L1ProbeSize = 4; // 4xbyte
bufferLayout._L2ProbeSize = 4; // 4xbyte
int destChunksSize = chunkCount * sizeof(uint) * 4; // 1 Chunk == Vector4Int
// First destination chunks at offset 0 (no explicit member for this).
// Then, shared data destination chunks. Can be different from SH data destination in case of blending
// (one pool for blending and one other pool for shared data and blending destination).
ProbeReferenceVolume.BufferLayoutBuilder layoutBuilder = new(destChunksSize);
bufferLayout._SharedDestChunksOffset = layoutBuilder.AddBlock(destChunksSize);
bufferLayout._L0L1rxOffset = layoutBuilder.AddBlock(m_L0Size * chunkCount);
bufferLayout._L1GryOffset = layoutBuilder.AddBlock(m_L1Size * chunkCount);
bufferLayout._L1BrzOffset = layoutBuilder.AddBlock(m_L1Size * chunkCount);
bufferLayout._ValidityOffset = layoutBuilder.AddBlock(m_ValiditySize * chunkCount);
bufferLayout._SkyOcclusionOffset = layoutBuilder.AddBlock(m_SkyOcclusionSize * chunkCount);
bufferLayout._SkyShadingDirectionOffset = layoutBuilder.AddBlock(m_SkyShadingDirectionSize * chunkCount);
bufferLayout._L2_0Offset = layoutBuilder.AddBlock(m_L2Size * chunkCount);
bufferLayout._L2_1Offset = layoutBuilder.AddBlock(m_L2Size * chunkCount);
bufferLayout._L2_2Offset = layoutBuilder.AddBlock(m_L2Size * chunkCount);
bufferLayout._L2_3Offset = layoutBuilder.AddBlock(m_L2Size * chunkCount);
bufferLayout._ProbeOcclusionOffset = layoutBuilder.AddBlock(m_ProbeOcclusionSize * chunkCount);
bufferLayout._ProbeCountInChunkLine = ProbeBrickPool.kChunkProbeCountPerDim;
bufferLayout._ProbeCountInChunkSlice = ProbeBrickPool.kChunkProbeCountPerDim * ProbeBrickPool.kBrickProbeCountPerDim;
m_Layouts.Add(chunkCount, bufferLayout);
return bufferLayout;
}
}
CellStreamingScratchBuffer CreateScratchBuffer(int chunkCount, bool allocateGraphicsBuffers)
{
var scratchBuffer = new CellStreamingScratchBuffer(chunkCount, chunkSize, allocateGraphicsBuffers);
m_CurrentlyAllocatedChunkCount += chunkCount;
return scratchBuffer;
}
// Used to avoid gcalloc in m_Pools.FindIndex
static int s_ChunkCount;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
s_ChunkCount = 0;
}
#endif
// Will return a the smallest GraphicsBuffer with at least enough space for chunkCount chunks.
public bool AllocateScratchBuffer(int chunkCount, out CellStreamingScratchBuffer scratchBuffer, out CellStreamingScratchBufferLayout layout, bool allocateGraphicsBuffers)
{
s_ChunkCount = chunkCount;
int index = m_Pools.FindIndex(0, (o) => o.chunkCount == s_ChunkCount);
// The size of buffer we return may not be the exact requested size (can be bigger).
// So we need to make sure the layout is the right one for the number of requested chunks.
layout = GetOrCreateScratchBufferLayout(chunkCount);
if (index != -1)
{
var pool = m_Pools[index].pool;
// If one is available, return it.
if (pool.Count > 0)
{
scratchBuffer = pool.Pop();
scratchBuffer.Swap();
return true;
}
else
{
// If none are available of the exact size, try to find a bigger buffer instead.
// We won't go above twice the size to avoid "wasting" bigger buffers for requests that are too small.
for (int i = index; i < m_Pools.Count; ++i)
{
var biggerPool = m_Pools[i];
// Next existing pools scratch size are too big. Break out of the loop.
// We don't want to hog a big buffer for a small request.
if (biggerPool.chunkCount >= (chunkCount * 2))
break;
else if (biggerPool.pool.Count > 0)
{
scratchBuffer = biggerPool.pool.Pop();
scratchBuffer.Swap();
return true;
}
}
// We did not find any suitable buffer. Create a new one with the exact requested size.
if ((m_CurrentlyAllocatedChunkCount + chunkCount) < maxChunkCount)
{
scratchBuffer = CreateScratchBuffer(chunkCount, allocateGraphicsBuffers);
return true;
}
// If we are above the maximum, we don't allocate more buffers.
// It's ok since we know at least one buffer will exist for any given chunkCount so we won't get impossible to fulfill requests.
else
{
scratchBuffer = null;
return false;
}
}
}
else
{
// No pool of this size exists. Create a new pool of that size and return a new buffer;
ScratchBufferPool newPool = new ScratchBufferPool(chunkCount);
m_Pools.Add(newPool);
m_Pools.Sort();
scratchBuffer = CreateScratchBuffer(chunkCount, allocateGraphicsBuffers);
return true;
}
}
public void ReleaseScratchBuffer(CellStreamingScratchBuffer scratchBuffer)
{
if (scratchBuffer.chunkSize != chunkSize)
{
scratchBuffer.Dispose();
return;
}
s_ChunkCount = scratchBuffer.chunkCount;
var pool = m_Pools.Find((o) => o.chunkCount == s_ChunkCount);
Debug.Assert(pool != null);
pool.pool.Push(scratchBuffer);
}
public void Cleanup()
{
foreach (var pool in m_Pools)
{
while(pool.pool.Count > 0)
{
var scratchBuffer = pool.pool.Pop();
scratchBuffer.Dispose();
}
}
m_Pools.Clear();
m_CurrentlyAllocatedChunkCount = 0;
chunkSize = 0;
maxChunkCount = 0;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 963afa495f3a6ef43bb488a65fe99d18
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,157 @@
using System;
using System.IO;
using UnityEngine.Serialization;
using Unity.IO.LowLevel.Unsafe;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Rendering
{
// A StreamableAsset is an asset that is converted to a Streaming Asset for builds.
// assetGUID is used in editor to handle the asset and streamableAssetPath is updated at build time and is used at runtime.
[Serializable]
[Scripting.APIUpdating.MovedFrom(false, "UnityEngine.Rendering", "Unity.RenderPipelines.Core.Runtime", "ProbeVolumeBakingSet.StreamableAsset")]
class ProbeVolumeStreamableAsset
{
[Serializable]
[Scripting.APIUpdating.MovedFrom(false, "UnityEngine.Rendering", "Unity.RenderPipelines.Core.Runtime", "ProbeVolumeBakingSet.StreamableAsset.StreamableCellDesc")]
public struct StreamableCellDesc
{
public int offset; // Offset of the cell within the file.
public int elementCount; // Number of elements in the cell (can be data chunks, bricks, debug info, etc)
}
[SerializeField] [FormerlySerializedAs("assetGUID")] string m_AssetGUID = ""; // In the editor, allows us to load the asset through the AssetDatabase.
[SerializeField] [FormerlySerializedAs("streamableAssetPath")]string m_StreamableAssetPath = ""; // At runtime, path of the asset within the StreamingAssets data folder.
[SerializeField] [FormerlySerializedAs("elementSize")]int m_ElementSize; // Size of an element. Can be a data chunk, a brick, etc.
[SerializeField] [FormerlySerializedAs("streamableCellDescs")] SerializedDictionary<int, StreamableCellDesc> m_StreamableCellDescs = new SerializedDictionary<int, StreamableCellDesc>();
[SerializeField] TextAsset m_Asset;
public string assetGUID { get => m_AssetGUID; }
public TextAsset asset { get => m_Asset; }
public int elementSize { get => m_ElementSize; }
public SerializedDictionary<int, StreamableCellDesc> streamableCellDescs { get => m_StreamableCellDescs; }
string m_FinalAssetPath;
FileHandle m_AssetFileHandle;
public ProbeVolumeStreamableAsset(string apvStreamingAssetsPath, SerializedDictionary<int, StreamableCellDesc> cellDescs, int elementSize, string bakingSetGUID, string assetGUID)
{
m_AssetGUID = assetGUID;
m_StreamableCellDescs = cellDescs;
m_ElementSize = elementSize;
m_StreamableAssetPath = Path.Combine(Path.Combine(apvStreamingAssetsPath, bakingSetGUID), m_AssetGUID + ".bytes");
#if UNITY_EDITOR
EnsureAssetLoaded();
#endif
}
internal void RefreshAssetPath()
{
#if UNITY_EDITOR
m_FinalAssetPath = AssetDatabase.GUIDToAssetPath(m_AssetGUID);
#else
m_FinalAssetPath = Path.Combine(Application.streamingAssetsPath, m_StreamableAssetPath);
#endif
}
public string GetAssetPath()
{
// Avoid GCAlloc every frame this is called.
if (string.IsNullOrEmpty(m_FinalAssetPath))
RefreshAssetPath();
return m_FinalAssetPath;
}
internal bool HasValidAssetReference()
{
return m_Asset != null && m_Asset.bytes != null;
}
unsafe public bool FileExists()
{
#if UNITY_EDITOR
if (HasValidAssetReference())
return true;
if (File.Exists(GetAssetPath()))
return true;
// File may not exist if it was moved, refresh path in this case
RefreshAssetPath();
return File.Exists(GetAssetPath());
#else
// When not using streaming assets, this reference should always be valid.
if (m_Asset != null)
return true;
FileInfoResult result;
AsyncReadManager.GetFileInfo(GetAssetPath(), &result).JobHandle.Complete();
return result.FileState == FileState.Exists;
#endif
}
#if UNITY_EDITOR
public void RenameAsset(string newName)
{
AssetDatabase.RenameAsset(AssetDatabase.GUIDToAssetPath(m_AssetGUID), newName);
m_FinalAssetPath = "";
}
// Ensures that the asset is referenced via Unity's serialization layer.
public void EnsureAssetLoaded()
{
m_Asset = AssetDatabase.LoadAssetAtPath<TextAsset>(GetAssetPath());
}
// Temporarily clear the asset reference. Used to prevent serialization of the asset when we are using the StreamingAssets codepath.
public void ClearAssetReferenceForBuild()
{
m_Asset = null;
}
#endif
public long GetFileSize()
{
return new FileInfo(GetAssetPath()).Length;
}
public bool IsOpen()
{
return m_AssetFileHandle.IsValid();
}
public FileHandle OpenFile()
{
if (m_AssetFileHandle.IsValid())
return m_AssetFileHandle;
m_AssetFileHandle = AsyncReadManager.OpenFileAsync(GetAssetPath());
return m_AssetFileHandle;
}
public void CloseFile()
{
if (m_AssetFileHandle.IsValid() && m_AssetFileHandle.JobHandle.IsCompleted)
m_AssetFileHandle.Close();
m_AssetFileHandle = default(FileHandle);
}
public bool IsValid()
{
return !string.IsNullOrEmpty(m_AssetGUID);
}
public void Dispose()
{
if (m_AssetFileHandle.IsValid())
{
m_AssetFileHandle.Close().Complete();
m_AssetFileHandle = default(FileHandle);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e49517d863f9f844b9f192be299100c5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,163 @@
//#pragma enable_d3d11_debug_symbols
#include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeUploadDataCommon.hlsl"
#pragma kernel UploadData
#pragma multi_compile_local _ PROBE_VOLUMES_SHARED_DATA
#pragma multi_compile_local _ PROBE_VOLUMES_SKY_OCCLUSION
#pragma multi_compile_local _ PROBE_VOLUMES_SKY_SHADING_DIRECTION
#pragma multi_compile_local _ PROBE_VOLUMES_PROBE_OCCLUSION
RWTexture3D<half4> _Out_L0_L1Rx;
RWTexture3D<unorm float4> _Out_L1G_L1Ry;
RWTexture3D<unorm float4> _Out_L1B_L1Rz;
#ifdef PROBE_VOLUMES_SHARED_DATA
RWTexture3D<float> _Out_Shared;
#ifdef PROBE_VOLUMES_SKY_OCCLUSION
RWTexture3D<float4> _Out_SkyOcclusionL0L1;
#ifdef PROBE_VOLUMES_SKY_SHADING_DIRECTION
RWTexture3D<float> _Out_SkyShadingDirectionIndices;
#endif
#endif
#endif
#ifdef PROBE_VOLUMES_PROBE_OCCLUSION
RWTexture3D<float4> _Out_ProbeOcclusion;
#endif
[numthreads(64, 1, 1)]
void UploadData(uint3 dispatchThreadID : SV_DispatchThreadID)
{
uint chunkIndex = dispatchThreadID.z;
uint chunkProbeIndex = dispatchThreadID.x * 4; // One thread processes 4 probes.
uint offsetL0_L1Rx = _L0L1rxOffset + chunkIndex * _L0Size + chunkProbeIndex * _L0ProbeSize; // 4 x 8 bytes probes.
uint offsetL1G_L1Ry = _L1GryOffset + chunkIndex * _L1Size + chunkProbeIndex * _L1ProbeSize; // 4 x 4 bytes probes.
uint offsetL1B_L1Rz = _L1BrzOffset + chunkIndex * _L1Size + chunkProbeIndex * _L1ProbeSize; // 4 x 4 bytes probes.
uint offsetValidity = _ValidityOffset + chunkIndex * _ValiditySize + chunkProbeIndex * _ValidityProbeSize; // 4 x 1 bytes probes.
uint offsetSkyOcclusion = _SkyOcclusionOffset + chunkIndex * _SkyOcclusionSize + chunkProbeIndex * _SkyOcclusionProbeSize; // 4 x 8 bytes probes.
uint offsetSkyShadingDirection = _SkyShadingDirectionOffset + chunkIndex * _SkyShadingDirectionSize + chunkProbeIndex * _SkyShadingDirectionProbeSize; // 4 x 1 bytes probes.
uint offsetProbeOcclusion = _ProbeOcclusionOffset + chunkIndex * _ProbeOcclusionSize + chunkProbeIndex * _ProbeOcclusionProbeSize; // 4 x 4 bytes probes.
// We extract 4 probes at a time.
// This is driven by the minimum amount of data that we can load at once with a ByteAddressBuffer
// Minimal data is 1 byte per probe so we can load at minimum 4 probes at a time with one ByteAddressBuffer.Load(uint)
// (either due to sky direction, of validity if rendering layers are not used)
// Extract L0L1Rx (fp16 encoded)
// 1 probe == 8 bytes => 2x2 probes encoded in 2x4 uint
float4 L0_L1Rx_probe_0, L0_L1Rx_probe_1, L0_L1Rx_probe_2, L0_L1Rx_probe_3;
ExtractFP16(_ScratchBuffer.Load4(offsetL0_L1Rx), L0_L1Rx_probe_0, L0_L1Rx_probe_1);
ExtractFP16(_ScratchBuffer.Load4(offsetL0_L1Rx + 16), L0_L1Rx_probe_2, L0_L1Rx_probe_3);
// Extract L1
// 1 probe == 4 bytes => 4 probes encoded in 4 uint (x2, once for each L1 texture)
float4 L1G_L1Ry_probe_0, L1G_L1Ry_probe_1, L1G_L1Ry_probe_2, L1G_L1Ry_probe_3;
ExtractByte(_ScratchBuffer.Load4(offsetL1G_L1Ry), L1G_L1Ry_probe_0, L1G_L1Ry_probe_1, L1G_L1Ry_probe_2, L1G_L1Ry_probe_3);
float4 L1B_L1Rz_probe_0, L1B_L1Rz_probe_1, L1B_L1Rz_probe_2, L1B_L1Rz_probe_3;
ExtractByte(_ScratchBuffer.Load4(offsetL1B_L1Rz), L1B_L1Rz_probe_0, L1B_L1Rz_probe_1, L1B_L1Rz_probe_2, L1B_L1Rz_probe_3);
#ifdef PROBE_VOLUMES_SHARED_DATA
float4 shared_probe_0_3;
if (_ValidityProbeSize == 1)
{
// Extract Shared Data. 1 probe == 1 byte => 4 probes encoded in 1 uint == 4 bytes
ExtractByte(_ScratchBuffer.Load(offsetValidity), shared_probe_0_3);
}
else
{
// When layers are on, 1 probe == 4 byte => 1 probe encoded in 1 uint
// See LoadValidityMask()
uint4 validityAsUint = _ScratchBuffer.Load4(offsetValidity);
shared_probe_0_3 = float4(
asfloat(validityAsUint.x),
asfloat(validityAsUint.y),
asfloat(validityAsUint.z),
asfloat(validityAsUint.w)
);
}
#ifdef PROBE_VOLUMES_SKY_OCCLUSION
float4 SkyOcclusionL0L1_probe_0, SkyOcclusionL0L1_probe_1, SkyOcclusionL0L1_probe_2, SkyOcclusionL0L1_probe_3;
ExtractFP16(_ScratchBuffer.Load4(offsetSkyOcclusion), SkyOcclusionL0L1_probe_0, SkyOcclusionL0L1_probe_1);
ExtractFP16(_ScratchBuffer.Load4(offsetSkyOcclusion + 16), SkyOcclusionL0L1_probe_2, SkyOcclusionL0L1_probe_3);
#ifdef PROBE_VOLUMES_SKY_SHADING_DIRECTION
float4 SkyShadingDirectionIndices_0_3;
ExtractByte(_ScratchBuffer.Load(offsetSkyShadingDirection), SkyShadingDirectionIndices_0_3);
#endif
#endif
#endif
#ifdef PROBE_VOLUMES_PROBE_OCCLUSION
float4 ProbeOcclusion_probe_0, ProbeOcclusion_probe_1, ProbeOcclusion_probe_2, ProbeOcclusion_probe_3;
ExtractByte(_ScratchBuffer.Load4(offsetProbeOcclusion), ProbeOcclusion_probe_0, ProbeOcclusion_probe_1, ProbeOcclusion_probe_2, ProbeOcclusion_probe_3);
#endif
APVResourcesRW output;
LOAD_APV_RES_L1(output, _Out);
uint3 baseProbe;
uint3 loc;
uint3 probe1Offset;
uint3 probe2Offset;
uint3 probe3Offset;
getProbeLocationAndOffsets(chunkIndex, chunkProbeIndex, baseProbe, loc, probe1Offset, probe2Offset, probe3Offset);
#ifdef PROBE_VOLUMES_SHARED_DATA
uint3 sharedDstChunk = _ScratchBuffer.Load4(_SharedDestChunksOffset + chunkIndex * 16).xyz; // *16 because 4 int per chunk.
uint3 sharedLoc = sharedDstChunk + baseProbe;
#endif
_Out_L0_L1Rx[loc] = L0_L1Rx_probe_0;
_Out_L0_L1Rx[loc + probe1Offset] = L0_L1Rx_probe_1;
_Out_L0_L1Rx[loc + probe2Offset] = L0_L1Rx_probe_2;
_Out_L0_L1Rx[loc + probe3Offset] = L0_L1Rx_probe_3;
_Out_L1G_L1Ry[loc] = L1G_L1Ry_probe_0;
_Out_L1G_L1Ry[loc + probe1Offset] = L1G_L1Ry_probe_1;
_Out_L1G_L1Ry[loc + probe2Offset] = L1G_L1Ry_probe_2;
_Out_L1G_L1Ry[loc + probe3Offset] = L1G_L1Ry_probe_3;
_Out_L1B_L1Rz[loc] = L1B_L1Rz_probe_0;
_Out_L1B_L1Rz[loc + probe1Offset] = L1B_L1Rz_probe_1;
_Out_L1B_L1Rz[loc + probe2Offset] = L1B_L1Rz_probe_2;
_Out_L1B_L1Rz[loc + probe3Offset] = L1B_L1Rz_probe_3;
#ifdef PROBE_VOLUMES_SHARED_DATA
_Out_Shared[sharedLoc] = shared_probe_0_3.x;
_Out_Shared[sharedLoc + probe1Offset] = shared_probe_0_3.y;
_Out_Shared[sharedLoc + probe2Offset] = shared_probe_0_3.z;
_Out_Shared[sharedLoc + probe3Offset] = shared_probe_0_3.w;
#ifdef PROBE_VOLUMES_SKY_OCCLUSION
_Out_SkyOcclusionL0L1[sharedLoc] = SkyOcclusionL0L1_probe_0;
_Out_SkyOcclusionL0L1[sharedLoc + probe1Offset] = SkyOcclusionL0L1_probe_1;
_Out_SkyOcclusionL0L1[sharedLoc + probe2Offset] = SkyOcclusionL0L1_probe_2;
_Out_SkyOcclusionL0L1[sharedLoc + probe3Offset] = SkyOcclusionL0L1_probe_3;
#ifdef PROBE_VOLUMES_SKY_SHADING_DIRECTION
_Out_SkyShadingDirectionIndices[sharedLoc] = SkyShadingDirectionIndices_0_3.x;
_Out_SkyShadingDirectionIndices[sharedLoc + probe1Offset] = SkyShadingDirectionIndices_0_3.y;
_Out_SkyShadingDirectionIndices[sharedLoc + probe2Offset] = SkyShadingDirectionIndices_0_3.z;
_Out_SkyShadingDirectionIndices[sharedLoc + probe3Offset] = SkyShadingDirectionIndices_0_3.w;
#endif
#endif
#endif
#ifdef PROBE_VOLUMES_PROBE_OCCLUSION
_Out_ProbeOcclusion[loc] = ProbeOcclusion_probe_0;
_Out_ProbeOcclusion[loc + probe1Offset] = ProbeOcclusion_probe_1;
_Out_ProbeOcclusion[loc + probe2Offset] = ProbeOcclusion_probe_2;
_Out_ProbeOcclusion[loc + probe3Offset] = ProbeOcclusion_probe_3;
#endif
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 0951de5992461754fa73650732c4954c
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,55 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeReferenceVolume.Streaming.cs.hlsl"
ByteAddressBuffer _ScratchBuffer;
float4 UintToFloat4(uint input)
{
float4 result;
result.x = (input & 0x000000FF) / 255.0f;
result.y = ((input >> 8) & 0x000000FF) / 255.0f;
result.z = ((input >> 16) & 0x000000FF) / 255.0f;
result.w = ((input >> 24) & 0x000000FF) / 255.0f;
return result;
}
// Extract two FP16 rgba values encoded in an uint4
void ExtractFP16(uint4 input, out float4 value0, out float4 value1)
{
float4 temp0 = f16tof32(input);
float4 temp1 = f16tof32(input >> 16);
value0.xz = temp0.xy;
value0.yw = temp1.xy;
value1.xz = temp0.zw;
value1.yw = temp1.zw;
}
void ExtractByte(uint4 input, out float4 value0, out float4 value1, out float4 value2, out float4 value3)
{
value0 = UintToFloat4(input.x);
value1 = UintToFloat4(input.y);
value2 = UintToFloat4(input.z);
value3 = UintToFloat4(input.w);
}
void ExtractByte(uint input, out float4 value)
{
value = UintToFloat4(input);
}
void getProbeLocationAndOffsets(uint chunkIndex, uint chunkProbeIndex, out float3 baseProbe, out float3 loc, out float3 probe1Offset, out float3 probe2Offset, out float3 probe3Offset)
{
baseProbe.z = chunkProbeIndex / _ProbeCountInChunkSlice;
uint indexInSlice = chunkProbeIndex - baseProbe.z * _ProbeCountInChunkSlice;
baseProbe.y = indexInSlice / _ProbeCountInChunkLine;
baseProbe.x = indexInSlice - baseProbe.y * _ProbeCountInChunkLine;
uint3 dstChunk = _ScratchBuffer.Load4(chunkIndex * 16).xyz; // *16 because 4 int per chunk.
loc = dstChunk + baseProbe;
probe1Offset = uint3(1, 0, 0);
probe2Offset = uint3(2, 0, 0);
probe3Offset = uint3(3, 0, 0);
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: fb1453f13b855f444a8034b2db10ca61
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,69 @@
//#pragma enable_d3d11_debug_symbols
#include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeUploadDataCommon.hlsl"
#pragma kernel UploadDataL2
RWTexture3D<unorm float4> _Out_L2_0;
RWTexture3D<unorm float4> _Out_L2_1;
RWTexture3D<unorm float4> _Out_L2_2;
RWTexture3D<unorm float4> _Out_L2_3;
[numthreads(64, 1, 1)]
void UploadDataL2(uint3 dispatchThreadID : SV_DispatchThreadID)
{
uint chunkIndex = dispatchThreadID.z;
uint chunkProbeIndex = dispatchThreadID.x * 4; // One thread processes 4 probes.
// We extract 4 probes at a time.
// This is driven by the minimum amount of data that we can load at once with a ByteAddressBuffer
// Shared data is currently 1 byte per probe so we can load at minimum 4 probes at a time with one ByteAddressBuffer.Load(uint)
uint offsetL2_0 = _L2_0Offset + chunkIndex * _L2Size + chunkProbeIndex * _L2ProbeSize; // 4 x 4 bytes probes.
uint offsetL2_1 = _L2_1Offset + chunkIndex * _L2Size + chunkProbeIndex * _L2ProbeSize; // 4 x 4 bytes probes.
uint offsetL2_2 = _L2_2Offset + chunkIndex * _L2Size + chunkProbeIndex * _L2ProbeSize; // 4 x 4 bytes probes.
uint offsetL2_3 = _L2_3Offset + chunkIndex * _L2Size + chunkProbeIndex * _L2ProbeSize; // 4 x 4 bytes probes.
// Extract L2
float4 L2_0_probe_0, L2_0_probe_1, L2_0_probe_2, L2_0_probe_3;
float4 L2_1_probe_0, L2_1_probe_1, L2_1_probe_2, L2_1_probe_3;
float4 L2_2_probe_0, L2_2_probe_1, L2_2_probe_2, L2_2_probe_3;
float4 L2_3_probe_0, L2_3_probe_1, L2_3_probe_2, L2_3_probe_3;
ExtractByte(_ScratchBuffer.Load4(offsetL2_0), L2_0_probe_0, L2_0_probe_1, L2_0_probe_2, L2_0_probe_3);
ExtractByte(_ScratchBuffer.Load4(offsetL2_1), L2_1_probe_0, L2_1_probe_1, L2_1_probe_2, L2_1_probe_3);
ExtractByte(_ScratchBuffer.Load4(offsetL2_2), L2_2_probe_0, L2_2_probe_1, L2_2_probe_2, L2_2_probe_3);
ExtractByte(_ScratchBuffer.Load4(offsetL2_3), L2_3_probe_0, L2_3_probe_1, L2_3_probe_2, L2_3_probe_3);
APVResourcesRW output;
LOAD_APV_RES_L2(output, _Out);
uint3 baseProbe;
uint3 loc;
uint3 probe1Offset;
uint3 probe2Offset;
uint3 probe3Offset;
getProbeLocationAndOffsets(chunkIndex, chunkProbeIndex, baseProbe, loc, probe1Offset, probe2Offset, probe3Offset);
_Out_L2_0[loc] = L2_0_probe_0;
_Out_L2_0[loc + probe1Offset] = L2_0_probe_1;
_Out_L2_0[loc + probe2Offset] = L2_0_probe_2;
_Out_L2_0[loc + probe3Offset] = L2_0_probe_3;
_Out_L2_1[loc] = L2_1_probe_0;
_Out_L2_1[loc + probe1Offset] = L2_1_probe_1;
_Out_L2_1[loc + probe2Offset] = L2_1_probe_2;
_Out_L2_1[loc + probe3Offset] = L2_1_probe_3;
_Out_L2_2[loc] = L2_2_probe_0;
_Out_L2_2[loc + probe1Offset] = L2_2_probe_1;
_Out_L2_2[loc + probe2Offset] = L2_2_probe_2;
_Out_L2_2[loc + probe3Offset] = L2_2_probe_3;
_Out_L2_3[loc] = L2_3_probe_0;
_Out_L2_3[loc + probe1Offset] = L2_3_probe_1;
_Out_L2_3[loc + probe2Offset] = L2_3_probe_2;
_Out_L2_3[loc + probe3Offset] = L2_3_probe_3;
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 6196f34ed825db14b81fb3eb0ea8d931
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
namespace UnityEngine.Rendering
{
static class ProbeVolumeUtil
{
internal static int CellSize(int subdivisionLevel) => (int)Mathf.Pow(ProbeBrickPool.kBrickCellCount, subdivisionLevel);
internal static float BrickSize(float minBrickSize, int subdivisionLevel) => minBrickSize * CellSize(subdivisionLevel);
internal static float MaxBrickSize(float minBrickSize, int maxSubDivision) => BrickSize(minBrickSize, maxSubDivision - 1);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e60162c3a6f6411491059635f101f6b9
timeCreated: 1743000507
@@ -0,0 +1,97 @@
using System;
using UnityEngine.Serialization;
using UnityEngine.Rendering;
namespace UnityEngine.Rendering
{
/// <summary>
/// A <see cref="VolumeParameter"/> that holds a <see cref="APVLeakReductionMode"/> value.
/// </summary>
[Serializable]
public sealed class APVLeakReductionModeParameter : VolumeParameter<APVLeakReductionMode>
{
/// <summary>
/// Creates a new <see cref="APVLeakReductionModeParameter"/> instance.
/// </summary>
/// <param name="value">The initial value to store in the parameter.</param>
/// <param name="overrideState">The initial override state for the parameter.</param>
public APVLeakReductionModeParameter(APVLeakReductionMode value, bool overrideState = false) : base(value, overrideState) { }
}
/// <summary>
/// A volume component that holds settings for the Adaptive Probe Volumes System per-camera options.
/// </summary>
[Serializable, VolumeComponentMenu("Lighting/Adaptive Probe Volumes Options"), SupportedOnRenderPipeline]
[PipelineHelpURL("UniversalRenderPipelineAsset", "urp/probevolumes")]
[PipelineHelpURL("HDRenderPipelineAsset", "probevolumes")]
[DisplayInfo(name = "Adaptive Probe Volumes Options")]
public sealed class ProbeVolumesOptions : VolumeComponent
{
/// <summary>
/// The overridden normal bias to be applied to the world position when sampling the Adaptive Probe Volumes data structure. Unit is meters.
/// </summary>
[Tooltip("The overridden normal bias to be applied to the world position when sampling the Adaptive Probe Volumes data structure. Unit is meters.")]
public ClampedFloatParameter normalBias = new ClampedFloatParameter(0.05f, 0.0f, 2.0f);
/// <summary>
/// A bias alongside the view vector to be applied to the world position when sampling the Adaptive Probe Volumes data structure. Unit is meters.
/// </summary>
[Tooltip("A bias alongside the view vector to be applied to the world position when sampling the Adaptive Probe Volumes data structure. Unit is meters.")]
public ClampedFloatParameter viewBias = new ClampedFloatParameter(0.1f, 0.0f, 2.0f);
/// <summary>
/// Whether to scale the bias for Adaptive Probe Volumes by the minimum distance between probes.
/// </summary>
[Tooltip("Whether to scale the bias for Adaptive Probe Volumes by the minimum distance between probes.")]
public BoolParameter scaleBiasWithMinProbeDistance = new BoolParameter(false);
/// <summary>
/// Noise to be applied to the sampling position. It can hide seams issues between subdivision levels, but introduces noise.
/// </summary>
[Tooltip("Noise to be applied to the sampling position. It can hide seams issues between subdivision levels, but introduces noise.")]
public ClampedFloatParameter samplingNoise = new ClampedFloatParameter(0.1f, 0.0f, 1.0f);
/// <summary>
/// Whether to animate the noise when TAA is enabled, smoothing potentially out the noise pattern introduced.
/// </summary>
[Tooltip("Whether to animate the noise when TAA is enabled. It can potentially remove the visible noise patterns.")]
public BoolParameter animateSamplingNoise = new BoolParameter(true);
/// <summary>
/// Method used to reduce leaks.
/// </summary>
[Tooltip("Method used to reduce leaks. Currently available modes are crude, but cheap methods.")]
public APVLeakReductionModeParameter leakReductionMode = new APVLeakReductionModeParameter(APVLeakReductionMode.Quality);
/// <summary>
/// This parameter isn't used anymore.
/// </summary>
[Obsolete("This parameter isn't used anymore. #from(6000.0)")]
public ClampedFloatParameter minValidDotProductValue = new ClampedFloatParameter(0.1f, -1.0f, 0.33f);
/// <summary>
/// When enabled, reflection probe normalization can only decrease the reflections intensity.
/// </summary>
[Tooltip("When enabled, reflection probe normalization can only decrease the reflection intensity.")]
public BoolParameter occlusionOnlyReflectionNormalization = new BoolParameter(true);
/// <summary>
/// Global probe volumes weight. Allows for fading out probe volumes influence falling back to ambient probe.
/// </summary>
[AdditionalProperty, Tooltip("Global probe volumes weight. Allows for fading out probe volumes influence falling back to ambient probe.")]
public ClampedFloatParameter intensityMultiplier = new ClampedFloatParameter(1.0f, 0.0f, 1.0f);
/// <summary>
/// Multiplier applied on the sky lighting when using sky occlusion.
/// </summary>
[AdditionalProperty, Tooltip("Multiplier applied on the sky lighting when using sky occlusion.")]
public ClampedFloatParameter skyOcclusionIntensityMultiplier = new ClampedFloatParameter(1.0f, 0.0f, 5.0f);
/// <summary>
/// Offset applied at runtime to probe positions in world space.
/// </summary>
[AdditionalProperty, Tooltip("Offset applied at runtime to probe positions in world space.\nThis is not considered while baking.")]
public Vector3Parameter worldOffset = new Vector3Parameter(Vector3.zero);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6bd486065ce11414fa40e631affc4900
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,81 @@
using System;
using Unity.Mathematics;
namespace UnityEngine.Rendering
{
[GenerateHLSL]
class APVDefinitions
{
public const int probeIndexChunkSize = ProbeBrickIndex.kIndexChunkSize;
public const float probeValidityThreshold = 0.05f;
public const int probeMaxRegionCount = 4;
public static readonly Color32[] layerMaskColors = {
new Color32(230, 159, 0, 255),
new Color32(0, 158, 115, 255),
new Color32(0, 114, 178, 255),
new Color32(204, 121, 167, 255),
};
public static readonly Color debugEmptyColor = new Color(0.388f, 0.812f, 0.804f, 1.0f);
}
/// <summary>
/// Defines the constant buffer register that will be used as binding point for the Adaptive Probe Volumes constant buffer.
/// </summary>
public enum APVConstantBufferRegister
{
/// <summary>
/// Global register
/// </summary>
GlobalRegister = 6
}
/// <summary>
/// Defines the method used to reduce leaking.
/// </summary>
[GenerateHLSL]
public enum APVLeakReductionMode
{
/// <summary>
/// Nothing is done to prevent leaking. Cheapest option in terms of cost of sampling.
/// </summary>
None = 0,
/// <summary>
/// The uvw used to sample APV data are warped to try to have invalid probe not contributing to lighting.
/// This samples APV a single time so it's a cheap option but will only work in the simplest cases.
/// </summary>
Performance = 1,
/// <summary>
/// This option samples APV between 1 and 3 times to provide the smoothest result without introducing artifacts.
/// This is as expensive as Performance mode in the simplest cases, and is better and more expensive in the most complex cases.
/// </summary>
Quality = 2,
/// <summary>
/// Obsolete, kept for migration.
/// </summary>
[Obsolete("Performance #from(6000.0)")]
ValidityBased = Performance,
/// <summary>
/// Obsolete, kept for migration.
/// </summary>
[Obsolete("Quality #from(6000.0)")]
ValidityAndNormalBased = Quality,
}
[GenerateHLSL(needAccessors = false, generateCBuffer = true, constantRegister = (int)APVConstantBufferRegister.GlobalRegister)]
internal unsafe struct ShaderVariablesProbeVolumes
{
public Vector4 _Offset_LayerCount;
public Vector4 _MinLoadedCellInEntries_IndirectionEntryDim;
public Vector4 _MaxLoadedCellInEntries_RcpIndirectionEntryDim;
public Vector4 _PoolDim_MinBrickSize;
public Vector4 _RcpPoolDim_XY;
public Vector4 _MinEntryPos_Noise;
public uint4 _EntryCount_X_XY_LeakReduction;
public Vector4 _Biases_NormalizationClamp;
public Vector4 _FrameIndex_Weights;
public uint4 _ProbeVolumeLayerMask;
}
}
@@ -0,0 +1,39 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef SHADERVARIABLESPROBEVOLUMES_CS_HLSL
#define SHADERVARIABLESPROBEVOLUMES_CS_HLSL
//
// UnityEngine.Rendering.APVLeakReductionMode: static fields
//
#define APVLEAKREDUCTIONMODE_NONE (0)
#define APVLEAKREDUCTIONMODE_PERFORMANCE (1)
#define APVLEAKREDUCTIONMODE_QUALITY (2)
#define APVLEAKREDUCTIONMODE_VALIDITY_BASED (1)
#define APVLEAKREDUCTIONMODE_VALIDITY_AND_NORMAL_BASED (2)
//
// UnityEngine.Rendering.APVDefinitions: static fields
//
#define PROBE_INDEX_CHUNK_SIZE (243)
#define PROBE_VALIDITY_THRESHOLD (0.05)
#define PROBE_MAX_REGION_COUNT (4)
// Generated from UnityEngine.Rendering.ShaderVariablesProbeVolumes
// PackingRules = Exact
GLOBAL_CBUFFER_START(ShaderVariablesProbeVolumes, b6)
float4 _Offset_LayerCount;
float4 _MinLoadedCellInEntries_IndirectionEntryDim;
float4 _MaxLoadedCellInEntries_RcpIndirectionEntryDim;
float4 _PoolDim_MinBrickSize;
float4 _RcpPoolDim_XY;
float4 _MinEntryPos_Noise;
uint4 _EntryCount_X_XY_LeakReduction;
float4 _Biases_NormalizationClamp;
float4 _FrameIndex_Weights;
uint4 _ProbeVolumeLayerMask;
CBUFFER_END
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: dcbd446e83bc87d40b82dd90f8814c3c
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6df0bea367f474d46865e94282c99503
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,280 @@
using System;
namespace UnityEngine.Rendering
{
/// <summary>
/// Structure holding Spherical Harmonic L1 coefficient.
/// </summary>
[Serializable]
public struct SphericalHarmonicsL1
{
/// <summary>
/// Red channel of each of the three L1 SH coefficient.
/// </summary>
public Vector4 shAr;
/// <summary>
/// Green channel of each of the three L1 SH coefficient.
/// </summary>
public Vector4 shAg;
/// <summary>
/// Blue channel of each of the three L1 SH coefficient.
/// </summary>
public Vector4 shAb;
/// <summary>
/// A set of L1 coefficients initialized to zero.
/// </summary>
public static readonly SphericalHarmonicsL1 zero = new SphericalHarmonicsL1
{
shAr = Vector4.zero,
shAg = Vector4.zero,
shAb = Vector4.zero
};
// These operators are implemented so that SphericalHarmonicsL1 matches API of SphericalHarmonicsL2.
/// <summary>
/// Sum two SphericalHarmonicsL1.
/// </summary>
/// <param name="lhs">First SphericalHarmonicsL1.</param>
/// <param name="rhs">Second SphericalHarmonicsL1.</param>
/// <returns>The resulting SphericalHarmonicsL1.</returns>
public static SphericalHarmonicsL1 operator +(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs) => new SphericalHarmonicsL1()
{
shAr = lhs.shAr + rhs.shAr,
shAg = lhs.shAg + rhs.shAg,
shAb = lhs.shAb + rhs.shAb
};
/// <summary>
/// Subtract two SphericalHarmonicsL1.
/// </summary>
/// <param name="lhs">First SphericalHarmonicsL1.</param>
/// <param name="rhs">Second SphericalHarmonicsL1.</param>
/// <returns>The resulting SphericalHarmonicsL1.</returns>
public static SphericalHarmonicsL1 operator -(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs) => new SphericalHarmonicsL1()
{
shAr = lhs.shAr - rhs.shAr,
shAg = lhs.shAg - rhs.shAg,
shAb = lhs.shAb - rhs.shAb
};
/// <summary>
/// Multiply two SphericalHarmonicsL1.
/// </summary>
/// <param name="lhs">First SphericalHarmonicsL1.</param>
/// <param name="rhs">Second SphericalHarmonicsL1.</param>
/// <returns>The resulting SphericalHarmonicsL1.</returns>
public static SphericalHarmonicsL1 operator *(SphericalHarmonicsL1 lhs, float rhs) => new SphericalHarmonicsL1()
{
shAr = lhs.shAr * rhs,
shAg = lhs.shAg * rhs,
shAb = lhs.shAb * rhs
};
/// <summary>
/// Divide two SphericalHarmonicsL1.
/// </summary>
/// <param name="lhs">First SphericalHarmonicsL1.</param>
/// <param name="rhs">Second SphericalHarmonicsL1.</param>
/// <returns>The resulting SphericalHarmonicsL1.</returns>
public static SphericalHarmonicsL1 operator /(SphericalHarmonicsL1 lhs, float rhs) => new SphericalHarmonicsL1()
{
shAr = lhs.shAr / rhs,
shAg = lhs.shAg / rhs,
shAb = lhs.shAb / rhs
};
/// <summary>
/// Compare two SphericalHarmonicsL1.
/// </summary>
/// <param name="lhs">First SphericalHarmonicsL1.</param>
/// <param name="rhs">Second SphericalHarmonicsL1.</param>
/// <returns>Whether the SphericalHarmonicsL1 match.</returns>
public static bool operator ==(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs)
{
return lhs.shAr == rhs.shAr
&& lhs.shAg == rhs.shAg
&& lhs.shAb == rhs.shAb;
}
/// <summary>
/// Check two SphericalHarmonicsL1 inequality.
/// </summary>
/// <param name="lhs">First SphericalHarmonicsL1.</param>
/// <param name="rhs">Second SphericalHarmonicsL1.</param>
/// <returns>Whether the SphericalHarmonicsL1 are different.</returns>
public static bool operator !=(SphericalHarmonicsL1 lhs, SphericalHarmonicsL1 rhs)
{
return !(lhs == rhs);
}
/// <summary>
/// Compare this SphericalHarmonicsL1 with an object.
/// </summary>
/// <param name="other">The object to compare with.</param>
/// <returns>Whether the SphericalHarmonicsL1 is equal to the object passed.</returns>
public override bool Equals(object other)
{
if (!(other is SphericalHarmonicsL1)) return false;
return this == (SphericalHarmonicsL1)other;
}
/// <summary>
/// Produces an hash code of the SphericalHarmonicsL1.
/// </summary>
/// <returns>The hash code for this SphericalHarmonicsL1.</returns>
public override int GetHashCode()
{
return ((17 * 23 + shAr.GetHashCode()) * 23 + shAg.GetHashCode()) * 23 + shAb.GetHashCode();
}
}
/// <summary>
/// A collection of utility functions used to access and set SphericalHarmonicsL2 in a more verbose way.
/// </summary>
public class SphericalHarmonicsL2Utils
{
/// <summary>
/// Returns the L1 coefficients organized in such a way that are swizzled per channel rather than per coefficient.
/// </summary>
/// <param name ="sh"> The SphericalHarmonicsL2 data structure to use to query the information.</param>
/// <param name ="L1_R">The red channel of all coefficient for the L1 band.</param>
/// <param name ="L1_G">The green channel of all coefficient for the L1 band.</param>
/// <param name ="L1_B">The blue channel of all coefficient for the L1 band.</param>
public static void GetL1(SphericalHarmonicsL2 sh, out Vector3 L1_R, out Vector3 L1_G, out Vector3 L1_B)
{
L1_R = new Vector3(sh[0, 1],
sh[0, 2],
sh[0, 3]);
L1_G = new Vector3(sh[1, 1],
sh[1, 2],
sh[1, 3]);
L1_B = new Vector3(sh[2, 1],
sh[2, 2],
sh[2, 3]);
}
/// <summary>
/// Returns all the L2 coefficients.
/// </summary>
/// <param name ="sh"> The SphericalHarmonicsL2 data structure to use to query the information.</param>
/// <param name ="L2_0">The first coefficient for the L2 band.</param>
/// <param name ="L2_1">The second coefficient for the L2 band.</param>
/// <param name ="L2_2">The third coefficient for the L2 band.</param>
/// <param name ="L2_3">The fourth coefficient for the L2 band.</param>
/// <param name ="L2_4">The fifth coefficient for the L2 band.</param>
public static void GetL2(SphericalHarmonicsL2 sh, out Vector3 L2_0, out Vector3 L2_1, out Vector3 L2_2, out Vector3 L2_3, out Vector3 L2_4)
{
L2_0 = new Vector3(sh[0, 4],
sh[1, 4],
sh[2, 4]);
L2_1 = new Vector3(sh[0, 5],
sh[1, 5],
sh[2, 5]);
L2_2 = new Vector3(sh[0, 6],
sh[1, 6],
sh[2, 6]);
L2_3 = new Vector3(sh[0, 7],
sh[1, 7],
sh[2, 7]);
L2_4 = new Vector3(sh[0, 8],
sh[1, 8],
sh[2, 8]);
}
/// <summary>
/// Set L0 coefficient.
/// </summary>
/// <param name ="sh">The SphericalHarmonicsL2 data structure to store information on.</param>
/// <param name ="L0">The L0 coefficient to set.</param>
public static void SetL0(ref SphericalHarmonicsL2 sh, Vector3 L0)
{
sh[0, 0] = L0.x;
sh[1, 0] = L0.y;
sh[2, 0] = L0.z;
}
/// <summary>
/// Set the red channel for each of the L1 coefficients.
/// </summary>
/// <param name ="sh">The SphericalHarmonicsL2 data structure to store information on.</param>
/// <param name ="L1_R">The red channels for each L1 coefficient.</param>
public static void SetL1R(ref SphericalHarmonicsL2 sh, Vector3 L1_R)
{
sh[0, 1] = L1_R.x;
sh[0, 2] = L1_R.y;
sh[0, 3] = L1_R.z;
}
/// <summary>
/// Set the green channel for each of the L1 coefficients.
/// </summary>
/// <param name ="sh">The SphericalHarmonicsL2 data structure to store information on.</param>
/// <param name ="L1_G">The green channels for each L1 coefficient.</param>
public static void SetL1G(ref SphericalHarmonicsL2 sh, Vector3 L1_G)
{
sh[1, 1] = L1_G.x;
sh[1, 2] = L1_G.y;
sh[1, 3] = L1_G.z;
}
/// <summary>
/// Set the blue channel for each of the L1 coefficients.
/// </summary>
/// <param name ="sh">The SphericalHarmonicsL2 data structure to store information on.</param>
/// <param name ="L1_B">The blue channels for each L1 coefficient.</param>
public static void SetL1B(ref SphericalHarmonicsL2 sh, Vector3 L1_B)
{
sh[2, 1] = L1_B.x;
sh[2, 2] = L1_B.y;
sh[2, 3] = L1_B.z;
}
/// <summary>
/// Set all L1 coefficients per channel.
/// </summary>
/// <param name ="sh">The SphericalHarmonicsL2 data structure to store information on.</param>
/// <param name ="L1_R">The red channels for each L1 coefficient.</param>
/// <param name ="L1_G">The green channels for each L1 coefficient.</param>
/// <param name ="L1_B">The blue channels for each L1 coefficient.</param>
public static void SetL1(ref SphericalHarmonicsL2 sh, Vector3 L1_R, Vector3 L1_G, Vector3 L1_B)
{
SetL1R(ref sh, L1_R);
SetL1G(ref sh, L1_G);
SetL1B(ref sh, L1_B);
}
/// <summary>
/// Set a spherical harmonics coefficient.
/// </summary>
/// <param name ="sh">The SphericalHarmonicsL2 data structure to store information on.</param>
/// <param name ="index">The index of the coefficient that is set (must be less than 9).</param>
/// <param name ="coefficient">The values of the coefficient is set.</param>
public static void SetCoefficient(ref SphericalHarmonicsL2 sh, int index, Vector3 coefficient)
{
Debug.Assert(index < 9);
sh[0, index] = coefficient.x;
sh[1, index] = coefficient.y;
sh[2, index] = coefficient.z;
}
/// <summary>
/// Get a spherical harmonics coefficient.
/// </summary>
/// <param name ="sh">The SphericalHarmonicsL2 data structure to get information from.</param>
/// <param name ="index">The index of the coefficient that is requested (must be less than 9).</param>
/// <returns>The value of the requested coefficient.</returns>
public static Vector3 GetCoefficient(SphericalHarmonicsL2 sh, int index)
{
Debug.Assert(index < 9);
return new Vector3(sh[0, index], sh[1, index], sh[2, index]);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f89ae72a038989e4780e2087fe3911c7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 30bf2eb104f12174e8c82c29105de9ed
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,6 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Runtime")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Core.Editor.Tests")]
[assembly: InternalsVisibleTo("Unity.SurfaceCache.Tests")]
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 25c1bf0294992764886cfb293ecce80c
@@ -0,0 +1,158 @@
#ifndef SURFACE_CACHE_COMMON
#define SURFACE_CACHE_COMMON
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl"
static const uint patchCapacity = 65536; // Must match C# side.
static const uint cascadeMax = 8; // Must match C# side.
#if UNITY_REVERSED_Z
static const float invalidNdcDepth = 0.0f;
#else
static const float invalidNdcDepth = 1.0f;
#endif
static const uint lowResScreenScaling = 4; // must match cpu side.
float LoadNdcDepth(Texture2D<float> depthBuffer, uint2 pos)
{
const float depthBufferDepth = depthBuffer[pos];
#if UNITY_REVERSED_Z
return depthBufferDepth;
#else
if(depthBufferDepth == 1.0f)
return invalidNdcDepth;
else
return depthBufferDepth * 2.0f - 1.0f;
#endif
}
float2 PixelPosToUvPos(uint2 pixelPos, float2 reciprocalScreenSize)
{
return (float2(pixelPos) + 0.5f) * reciprocalScreenSize;
}
namespace SphericalHarmonics
{
static const float y0 = sqrt(1.0f / PI) * 0.5f;
static const float y1Constant = sqrt(3.0f / PI) * 0.5f;
static const float y20Constant = sqrt(15.0f / PI) * 0.5f;
static const float y21Constant = y20Constant;
static const float y22Constant = sqrt(5.0f / PI) * 0.25f;
static const float y23Constant = y20Constant;
static const float y24Constant = sqrt(15.0f / PI) * 0.25f;
struct RGBL1
{
float3 l0;
float3 l1s[3];
};
float3 Eval(in RGBL1 f, float3 direction)
{
return f.l0 * y0 + y1Constant * (f.l1s[0] * direction.y + f.l1s[1] * direction.z + f.l1s[2] * direction.x);
}
RGBL1 MulPure(RGBL1 f, float multiplier)
{
RGBL1 result;
result.l0 = f.l0 * multiplier;
result.l1s[0] = f.l1s[0] * multiplier;
result.l1s[1] = f.l1s[1] * multiplier;
result.l1s[2] = f.l1s[2] * multiplier;
return result;
}
RGBL1 AddPure(RGBL1 a, RGBL1 b)
{
RGBL1 result;
result.l0 = a.l0 + b.l0;
result.l1s[0] = a.l1s[0] + b.l1s[0];
result.l1s[1] = a.l1s[1] + b.l1s[1];
result.l1s[2] = a.l1s[2] + b.l1s[2];
return result;
}
// Multiply-add: a = a + b * c.
void AddMut(inout RGBL1 a, RGBL1 b)
{
a.l0 += b.l0;
a.l1s[0] += b.l1s[0];
a.l1s[1] += b.l1s[1];
a.l1s[2] += b.l1s[2];
}
// Multiply-add: a = a + b * c.
void MulAddMut(inout RGBL1 a, float b, RGBL1 c)
{
a.l0 += b * c.l0;
a.l1s[0] += b * c.l1s[0];
a.l1s[1] += b * c.l1s[1];
a.l1s[2] += b * c.l1s[2];
}
void MulMut(inout RGBL1 f, float multiplier)
{
f.l0 *= multiplier;
f.l1s[0] *= multiplier;
f.l1s[1] *= multiplier;
f.l1s[2] *= multiplier;
}
RGBL1 Lerp(in RGBL1 a, in RGBL1 b, float3 s)
{
RGBL1 output;
output.l0 = lerp(a.l0, b.l0, s);
output.l1s[0] = lerp(a.l1s[0], b.l1s[0], s);
output.l1s[1] = lerp(a.l1s[1], b.l1s[1], s);
output.l1s[2] = lerp(a.l1s[2], b.l1s[2], s);
return output;
}
// Convolve with cos(theta). https://cseweb.ucsd.edu/~ravir/papers/envmap/envmap.pdf
void CosineConvolve(inout RGBL1 f)
{
const float aHat0 = PI;
const float aHat1 = (2.0f * PI) / 3.0f;
f.l0 *= aHat0;
f.l1s[0] *= aHat1;
f.l1s[1] *= aHat1;
f.l1s[2] *= aHat1;
}
struct ScalarL2
{
float l0;
float l1s[3];
float l2s[5];
};
float Eval(in ScalarL2 f, float3 direction)
{
return f.l0 * y0 +
f.l1s[0] * y1Constant * direction.y +
f.l1s[1] * y1Constant * direction.z +
f.l1s[2] * y1Constant * direction.x +
f.l2s[0] * y20Constant * direction.x * direction.y +
f.l2s[1] * y21Constant * direction.y * direction.z +
f.l2s[2] * y22Constant * (3.0f * direction.z * direction.z - 1.0f) +
f.l2s[3] * y23Constant * direction.x * direction.z +
f.l2s[4] * y24Constant * (direction.x * direction.x - direction.y * direction.y);
}
ScalarL2 Lerp(ScalarL2 a, ScalarL2 b, float s)
{
SphericalHarmonics::ScalarL2 output;
output.l0 = lerp(a.l0, b.l0, s);
output.l1s[0] = lerp(a.l1s[0], b.l1s[0], s);
output.l1s[1] = lerp(a.l1s[1], b.l1s[1], s);
output.l1s[2] = lerp(a.l1s[2], b.l1s[2], s);
output.l2s[0] = lerp(a.l2s[0], b.l2s[0], s);
output.l2s[1] = lerp(a.l2s[1], b.l2s[1], s);
output.l2s[2] = lerp(a.l2s[2], b.l2s[2], s);
output.l2s[3] = lerp(a.l2s[3], b.l2s[3], s);
output.l2s[4] = lerp(a.l2s[4], b.l2s[4], s);
return output;
}
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 9bdf70d328f46724a8d2a29eacb6e8d7
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,89 @@
#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal ps5 switch2
#pragma multi_compile_local SUB_GROUP_SIZE_8 SUB_GROUP_SIZE_16 SUB_GROUP_SIZE_32 SUB_GROUP_SIZE_48 SUB_GROUP_SIZE_64
#ifdef SUB_GROUP_SIZE_8
#define SUB_GROUP_SIZE 8
#endif
#ifdef SUB_GROUP_SIZE_16
#define SUB_GROUP_SIZE 16
#endif
#ifdef SUB_GROUP_SIZE_32
#define SUB_GROUP_SIZE 32
#endif
#ifdef SUB_GROUP_SIZE_48
#define SUB_GROUP_SIZE 48
#endif
#ifdef SUB_GROUP_SIZE_64
#define SUB_GROUP_SIZE 64
#endif
#pragma kernel Defrag
#define RING_BUFFER_USE_RW_RING_CONFIG_BUFFER
#define GROUP_SIZE 512
#include "RingBuffer.hlsl"
#include "PatchUtil.hlsl"
#define THREADING_BLOCK_SIZE GROUP_SIZE
#define THREADING_WAVE_SIZE SUB_GROUP_SIZE
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Threading.hlsl"
RWStructuredBuffer<uint> _RingConfigBuffer;
RWStructuredBuffer<uint> _CellPatchIndices;
RWStructuredBuffer<uint> _PatchCellIndices;
RWStructuredBuffer<SphericalHarmonics::RGBL1> _PatchIrradiances0;
RWStructuredBuffer<SphericalHarmonics::RGBL1> _PatchIrradiances1;
RWStructuredBuffer<PatchUtil::PatchGeometry> _PatchGeometries;
RWStructuredBuffer<PatchUtil::PatchStatisticsSet> _PatchStatistics;
uint _RingConfigReadOffset;
uint _RingConfigWriteOffset;
uint _PatchOffset;
[numthreads(GROUP_SIZE, 1, 1)]
void Defrag(Threading::Group group)
{
const uint patchIdx = (group.dispatchID.x + _PatchOffset) % patchCapacity;
Threading::Wave wave = group.GetWave();
const RingBuffer::Config config = RingBuffer::LoadConfig(_RingConfigBuffer, _RingConfigReadOffset);
const bool isInRingContentRange = RingBuffer::IsPositionInUse(config, patchIdx);
const uint firstLaneIndexOutsideContentRange = wave.Min(!isInRingContentRange ? wave.GetLaneIndex() : UINT_MAX);
const bool isLaneIndexAfterFirstLaneIndexThatIsOutsideContentRange = firstLaneIndexOutsideContentRange == UINT_MAX || firstLaneIndexOutsideContentRange < wave.GetLaneIndex();
const bool startEndHazardCheck = config.start != config.end || !RingBuffer::IsPositionInUseAssumingStartNotEqualEnd((config.start - SUB_GROUP_SIZE) % patchCapacity, config.start, patchIdx);
const uint patchCellIdx = _PatchCellIndices[patchIdx];
const uint isReclaimable =
patchCellIdx == PatchUtil::invalidCellIndex &&
isInRingContentRange &&
isLaneIndexAfterFirstLaneIndexThatIsOutsideContentRange && // Ensures we only defrag elements that are inside the "content range" of the ring buffer.
startEndHazardCheck; // Ensures we avoid defragging "across" the start/end boundary in the special case when start == end.
const uint leftReclaimableCount = wave.PrefixSum(isReclaimable);
const uint reclaimableCount = wave.Sum(isReclaimable);
const uint rightReclaimableCount = reclaimableCount - leftReclaimableCount;
if(patchIdx == config.start)
{
_RingConfigBuffer[_RingConfigWriteOffset + RingBuffer::countConfigIndex] = config.count - reclaimableCount;
_RingConfigBuffer[_RingConfigWriteOffset + RingBuffer::startConfigIndex] = _RingConfigBuffer[_RingConfigReadOffset + RingBuffer::startConfigIndex] + reclaimableCount;
_RingConfigBuffer[_RingConfigWriteOffset + RingBuffer::endConfigIndex] = _RingConfigBuffer[_RingConfigReadOffset + RingBuffer::endConfigIndex];
}
if(reclaimableCount != 0 && !isReclaimable && isInRingContentRange && isLaneIndexAfterFirstLaneIndexThatIsOutsideContentRange && startEndHazardCheck) {
uint oldPatchCellIndex = _PatchCellIndices[patchIdx];
_PatchCellIndices[patchIdx] = PatchUtil::invalidCellIndex;
const uint newPatchIdx = (patchIdx + rightReclaimableCount) % patchCapacity;
_PatchCellIndices[newPatchIdx] = oldPatchCellIndex;
_PatchIrradiances0[newPatchIdx] = _PatchIrradiances0[patchIdx];
_PatchIrradiances1[newPatchIdx] = _PatchIrradiances1[patchIdx];
_PatchGeometries[newPatchIdx] = _PatchGeometries[patchIdx];
_PatchStatistics[newPatchIdx] = _PatchStatistics[patchIdx];
_CellPatchIndices[patchCellIdx] = newPatchIdx;
}
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a183a2d0b1da4904fb3bd71c6111ebb1
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,283 @@
#define PATCH_UTIL_USE_RW_PATCH_IRRADIANCE_BUFFER
#include "Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/Sampling/QuasiRandom.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common.hlsl"
#include "PathTracing.hlsl"
#include "PatchAllocationRequest.hlsl"
#include "RingBuffer.hlsl"
#include "PatchUtil.hlsl"
#include "TemporalFiltering.hlsl"
#include "PunctualLights.hlsl"
RWStructuredBuffer<SphericalHarmonics::RGBL1> _PatchIrradiances;
RWStructuredBuffer<PatchUtil::PatchStatisticsSet> _PatchStatistics;
RWStructuredBuffer<PatchAllocationRequest> _PatchAllocationRequests;
RWStructuredBuffer<uint> _PatchAllocationRequestCount;
StructuredBuffer<uint> _RingConfigBuffer;
StructuredBuffer<PatchUtil::PatchGeometry> _PatchGeometries;
StructuredBuffer<uint> _CellPatchIndices;
StructuredBuffer<int3> _VolumeCascadeOffsets;
StructuredBuffer<MaterialPool::MaterialEntry> _MaterialEntries;
StructuredBuffer<PunctualLightSample> _PunctualLightSamples;
StructuredBuffer<PunctualLight> _PunctualLights;
Texture2DArray _AlbedoTextures;
Texture2DArray _EmissionTextures;
SamplerState sampler_EmissionTextures;
SamplerState sampler_AlbedoTextures;
TextureCube<float3> _EnvironmentCubemap;
SamplerState sampler_EnvironmentCubemap;
UNIFIED_RT_DECLARE_ACCEL_STRUCT(_RayTracingAccelerationStructure);
uint _PunctualLightCount;
uint _FrameIdx;
uint _VolumeSpatialResolution;
uint _VolumeCascadeCount;
float _VolumeVoxelMinSize;
uint _MultiBounce;
uint _SampleCount;
float _ShortHysteresis;
uint _RingConfigOffset;
float3 _VolumeTargetPos;
float _MaterialAtlasTexelSize; // The size of 1 texel in the atlases above
float _AlbedoBoost;
float _EnvironmentIntensityMultiplier;
float _EmissiveTriangleIntensityMultiplier;
uint _PunctualLightSampleCount;
float3 _DirectionalLightDirection;
float3 _DirectionalLightIntensity;
uint _BouncePatchAllocation;
void ProcessAndStoreRadianceSample(RWStructuredBuffer<SphericalHarmonics::RGBL1> patchIrradiances, RWStructuredBuffer<PatchUtil::PatchStatisticsSet> patchStatistics, uint patchIdx, SphericalHarmonics::RGBL1 radianceSample, float shortHysteresis)
{
SphericalHarmonics::CosineConvolve(radianceSample);
PatchUtil::PatchStatisticsSet oldStats = patchStatistics[patchIdx];
const uint oldUpdateCount = PatchUtil::GetUpdateCount(oldStats.counters);
const uint newUpdateCount = min(oldUpdateCount + 1, PatchUtil::updateMax);
const SphericalHarmonics::RGBL1 oldIrradiance = patchIrradiances[patchIdx];
float shortIrradianceUpdateWeight;
if (oldUpdateCount == 0)
shortIrradianceUpdateWeight = 0;
else
shortIrradianceUpdateWeight = min(1.0f - rcp(oldUpdateCount), shortHysteresis);
const float3 newL0ShortIrradiance = lerp(radianceSample.l0, oldStats.mean, shortIrradianceUpdateWeight);
const float3 varianceSample = (radianceSample.l0 - newL0ShortIrradiance) * (radianceSample.l0 - oldStats.mean);
const float3 newVariance = lerp(varianceSample, oldStats.variance, shortHysteresis);
SphericalHarmonics::RGBL1 output = FilterTemporallyVarianceGuided(shortHysteresis, newUpdateCount, newVariance, newL0ShortIrradiance, radianceSample, oldIrradiance);
patchIrradiances[patchIdx] = output;
PatchUtil::PatchStatisticsSet newStats;
newStats.mean = newL0ShortIrradiance;
newStats.variance = newVariance;
newStats.counters = oldStats.counters;
PatchUtil::SetUpdateCount(newStats.counters, newUpdateCount);
patchStatistics[patchIdx] = newStats;
}
void ProjectAndAccumulate(inout SphericalHarmonics::RGBL1 accumulator, float3 sampleRadiance, float3 sampleDirection)
{
accumulator.l0 += sampleRadiance * SphericalHarmonics::y0;
accumulator.l1s[0] += sampleRadiance * SphericalHarmonics::y1Constant * sampleDirection.y;
accumulator.l1s[1] += sampleRadiance * SphericalHarmonics::y1Constant * sampleDirection.z;
accumulator.l1s[2] += sampleRadiance * SphericalHarmonics::y1Constant * sampleDirection.x;
}
float GetAdditionalRayOffset(float volumeVoxelMinSize)
{
// We currently use the OffsetRayOrigin() heuristic to offset ray origins to avoid self-intersections. While this
// helps for Surface Cache it is not enough since the ray origins are relatively imprecise because they are derived
// from output of the rasterizer (as opposed to being reconstructed via barycentrics).
// We fix this by adding an additional offset. This offset is a percentage of the min voxel size to keep it
// somewhat proportional to the scene scale.
return volumeVoxelMinSize * 0.001;
}
void SamplePunctualLightBounceRadiance(
inout QrngKronecker2D rng,
UnifiedRT::RayTracingAccelStruct accelStruct,
UnifiedRT::DispatchInfo dispatchInfo,
StructuredBuffer<PunctualLight> lights,
StructuredBuffer<PunctualLightSample> punctualLightSamples,
uint punctualLightSampleCount,
float volumeVoxelMinSize,
PatchUtil::PatchGeometry patchGeo,
inout SphericalHarmonics::RGBL1 accumulator,
inout bool gotValidSamples)
{
SphericalHarmonics::RGBL1 radianceAccumulator = (SphericalHarmonics::RGBL1)0;
uint validSampleCount = 0;
for(uint sampleIdx = 0; sampleIdx < _SampleCount; ++sampleIdx)
{
// Using `sample` as a variable name causes compilation errors on PS5.
PunctualLightBounceRadianceSample sample_ = SamplePunctualLightBounceRadiance(
dispatchInfo,
accelStruct,
lights,
punctualLightSamples,
punctualLightSampleCount,
rng.GetSample(0).x,
patchGeo.position,
patchGeo.normal,
GetAdditionalRayOffset(volumeVoxelMinSize));
if (!sample_.IsValid())
continue;
validSampleCount++;
ProjectAndAccumulate(radianceAccumulator, sample_.radianceOverDensity, sample_.direction);
rng.NextSample();
}
if (validSampleCount != 0)
{
gotValidSamples = true;
const float normalizationFactor = rcp(validSampleCount);
SphericalHarmonics::AddMut(accumulator, SphericalHarmonics::MulPure(radianceAccumulator, normalizationFactor));
}
}
void SampleEnvironmentAndDirectionalBounceAndMultiBounceRadiance(
bool enablePatchAllocation,
uint frameIndex,
inout QrngKronecker2D rng,
UnifiedRT::RayTracingAccelStruct accelStruct,
UnifiedRT::DispatchInfo dispatchInfo,
MaterialPoolParamSet matPoolParams,
PatchUtil::PatchGeometry patchGeo,
RWStructuredBuffer<PatchUtil::PatchStatisticsSet> patchStatistics,
CellPatchIndexBufferType cellPatchIndices,
PatchUtil::VolumeParamSet volumeParams,
inout SphericalHarmonics::RGBL1 accumulator,
inout bool gotValidSamples)
{
UnifiedRT::Ray ray;
ray.origin = OffsetRayOrigin(patchGeo.position, patchGeo.normal, GetAdditionalRayOffset(volumeParams.voxelMinSize));
ray.tMin = 0;
ray.tMax = FLT_MAX;
SphericalHarmonics::RGBL1 radianceAccumulator = (SphericalHarmonics::RGBL1)0;
uint validSampleCount = 0;
for(uint sampleIdx = 0; sampleIdx < _SampleCount; ++sampleIdx)
{
ray.direction = UniformHemisphereSample(rng.GetSample(0), patchGeo.normal);
const float3 radiance = IncomingEnvironmentAndDirectionalBounceAndMultiBounceRadiance(
dispatchInfo,
accelStruct,
ray,
matPoolParams,
_DirectionalLightDirection,
_DirectionalLightIntensity,
_MultiBounce,
_EnvironmentCubemap,
_EnvironmentIntensityMultiplier,
_EmissiveTriangleIntensityMultiplier,
sampler_EnvironmentCubemap,
_PatchIrradiances,
patchStatistics,
_PatchAllocationRequests,
_PatchAllocationRequestCount,
cellPatchIndices,
volumeParams,
enablePatchAllocation,
frameIndex);
if (all(radiance == invalidRadiance))
continue;
validSampleCount++;
ProjectAndAccumulate(radianceAccumulator, radiance, ray.direction);
rng.NextSample();
}
if (validSampleCount != 0)
{
gotValidSamples = true;
const float reciprocalDensity = 2.0f * PI;
const float normalizationFactor = reciprocalDensity * rcp(validSampleCount);
SphericalHarmonics::AddMut(accumulator, SphericalHarmonics::MulPure(radianceAccumulator, normalizationFactor));
}
}
void Estimate(UnifiedRT::DispatchInfo dispatchInfo)
{
uint patchIdx = dispatchInfo.dispatchThreadID.x;
if (!RingBuffer::IsPositionInUse(_RingConfigBuffer, _RingConfigOffset, patchIdx))
return;
UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(_RayTracingAccelerationStructure);
QrngKronecker2D rng;
const PatchUtil::PatchGeometry patchGeo = _PatchGeometries[patchIdx];
bool enablePatchAllocation;
if (_BouncePatchAllocation)
enablePatchAllocation = (PatchUtil::GetRank(_PatchStatistics[patchIdx].counters) == 0);
else
enablePatchAllocation = false;
MaterialPoolParamSet matPoolParams;
matPoolParams.materialEntries = _MaterialEntries;
matPoolParams.albedoTextures = _AlbedoTextures;
matPoolParams.emissionTextures = _EmissionTextures;
matPoolParams.emissionSampler = sampler_EmissionTextures;
matPoolParams.albedoSampler = sampler_AlbedoTextures;
matPoolParams.atlasTexelSize = _MaterialAtlasTexelSize;
matPoolParams.albedoBoost = _AlbedoBoost;
PatchUtil::VolumeParamSet volumeParams;
volumeParams.spatialResolution = _VolumeSpatialResolution;
volumeParams.voxelMinSize = _VolumeVoxelMinSize;
volumeParams.targetPos = _VolumeTargetPos;
volumeParams.cascadeOffsets = _VolumeCascadeOffsets;
volumeParams.cascadeCount = _VolumeCascadeCount;
SphericalHarmonics::RGBL1 radianceSampleMean = (SphericalHarmonics::RGBL1)0;
bool gotValidSamples = false;
const uint patchIdxHash = LowBiasHash32(patchIdx);
const uint sampleOffset = _FrameIdx * _SampleCount;
rng.Init(patchIdxHash, sampleOffset);
SampleEnvironmentAndDirectionalBounceAndMultiBounceRadiance(
enablePatchAllocation,
_FrameIdx,
rng,
accelStruct,
dispatchInfo,
matPoolParams,
patchGeo,
_PatchStatistics,
_CellPatchIndices,
volumeParams,
radianceSampleMean,
gotValidSamples);
if (_PunctualLightCount != 0)
{
rng.Init(patchIdxHash, sampleOffset);
SamplePunctualLightBounceRadiance(
rng,
accelStruct,
dispatchInfo,
_PunctualLights,
_PunctualLightSamples,
_PunctualLightSampleCount,
_VolumeVoxelMinSize,
patchGeo,
radianceSampleMean,
gotValidSamples);
}
if (gotValidSamples)
ProcessAndStoreRadianceSample(_PatchIrradiances, _PatchStatistics, patchIdx, radianceSampleMean, _ShortHysteresis);
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 87f25dcc02b54e84ab16e783d04d72d8
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,12 @@
#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal ps5 switch2
// We're binding a large number of structured buffers in this shader, more than certain platforms accept
// by default. Using this pragma extends this limit on these platforms at the expense
// of some extra indirections. On platforms that don't have this limit, this is a no-op.
#pragma extended_structured_buffer_bindings
#define UNIFIED_RT_GROUP_SIZE_X 64
#define UNIFIED_RT_GROUP_SIZE_Y 1
#define UNIFIED_RT_GROUP_SIZE_Z 1
#define UNIFIED_RT_RAYGEN_FUNC Estimate
#include "Estimation.hlsl"
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 94a39d12848d8d64ca962a72b74e7c50
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 42d537a8a4089e448a99fc57a06d74a9, type: 3}
@@ -0,0 +1,50 @@
#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal ps5 switch2
#pragma kernel Evict
#include "PatchUtil.hlsl"
StructuredBuffer<uint> _RingConfigBuffer;
RWStructuredBuffer<PatchUtil::PatchStatisticsSet> _PatchStatistics;
RWStructuredBuffer<uint> _CellAllocationMarks;
RWStructuredBuffer<uint> _CellPatchIndices;
RWStructuredBuffer<uint> _PatchCellIndices;
uint _RingConfigOffset;
uint _FrameIdx;
uint _BouncePatchAllocation;
[numthreads(256, 1, 1)]
void Evict(uint patchIdx : SV_DispatchThreadID)
{
if (!RingBuffer::IsPositionInUse(_RingConfigBuffer, _RingConfigOffset, patchIdx))
return;
const uint cellIdx = _PatchCellIndices[patchIdx];
if (cellIdx == PatchUtil::invalidCellIndex)
return;
PatchUtil::PatchStatisticsSet stats = _PatchStatistics[patchIdx];
const uint frameSinceLastAccess = PatchUtil::GetFramesSinceLastAccess(_FrameIdx, PatchUtil::GetLastAccessFrame(stats.counters));
if (PatchUtil::evictionThreshold < frameSinceLastAccess)
{
// If Bounce Patch Allocation is enabled, then rank 0 patches are
// first demoted to rank 1, then later they are evicted.
// If Bounce Patch Allocation is disabled we go directly to
// eviction.
if (_BouncePatchAllocation && PatchUtil::GetRank(stats.counters) == 0)
{
PatchUtil::SetRank(stats.counters, 1);
PatchUtil::SetLastAccessFrame(stats.counters, _FrameIdx);
_PatchStatistics[patchIdx] = stats;
}
else
{
_PatchCellIndices[patchIdx] = PatchUtil::invalidCellIndex;
_CellAllocationMarks[cellIdx] = 0;
_CellPatchIndices[cellIdx] = PatchUtil::invalidPatchIndex;
}
}
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c9f2aeed6ef396f4d9134e4da1edfe19
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,54 @@
#include "Common.hlsl"
#include "VectorLogic.hlsl"
// This compression assumes a few things:
// 1) The coefs must be with respect to the standard orthonormal SH basis. For example,
// the first basis function must be 1/sqrt(4pi).
// 2) Irradiance is calculated by projecting radiance into SH, then converting to
// irradiance using Ramamoorthi's method, https://cseweb.ucsd.edu/~ravir/papers/envmap/envmap.pdf.
// 3) The coefs are exact (as opposed to noisy approximations).
// If these assumptions are met then L1 is guaranteed to be in [0,1] after compression. L0 terms
// are unaffected. If (2) and (3) are not met, then the L1 terms should still be _approximately_ in
// [0,1].
namespace IrradianceCompression
{
void Compress(inout SphericalHarmonics::RGBL1 irradiance)
{
const float3 multiplier = VECTOR_LOGIC_SELECT(irradiance.l0 == 0.0f, 0.0f, sqrt(3.0f) / 4.0f * rcp(irradiance.l0));
const float3 addend = VECTOR_LOGIC_SELECT(irradiance.l0 == 0.0f, 0.0f, 0.5f);
UNITY_UNROLL // To get rid of some shader warnings on some platforms
for (uint i = 0; i < 3; ++i)
irradiance.l1s[i] = irradiance.l1s[i] * multiplier + addend;
}
void Decompress(inout SphericalHarmonics::RGBL1 irradiance)
{
const float3 multiplier = 4.0f / sqrt(3.0f) * irradiance.l0;
const float3 addend = VECTOR_LOGIC_SELECT(irradiance.l0 == 0.0f, 0.0f, -0.5f);
UNITY_UNROLL // To get rid of some shader warnings on some platforms
for (uint i = 0; i < 3; ++i)
irradiance.l1s[i] = (irradiance.l1s[i] + addend) * multiplier;
}
SphericalHarmonics::RGBL1 LoadAndDecompress(Texture2D<float3> l0, Texture2D<float3> l10, Texture2D<float3> l11, Texture2D<float3> l12, uint2 pos)
{
SphericalHarmonics::RGBL1 result;
result.l0 = l0[pos];
result.l1s[0] = l10[pos];
result.l1s[1] = l11[pos];
result.l1s[2] = l12[pos];
IrradianceCompression::Decompress(result);
return result;
}
void CompressAndStore(SphericalHarmonics::RGBL1 irradiance, RWTexture2D<float3> l0, RWTexture2D<float3> l10, RWTexture2D<float3> l11, RWTexture2D<float3> l12, uint2 pos)
{
IrradianceCompression::Compress(irradiance);
l0[pos] = irradiance.l0;
l10[pos] = irradiance.l1s[0];
l11[pos] = irradiance.l1s[1];
l12[pos] = irradiance.l1s[2];
}
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 7be701552a7670148a7c948d2b363156
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,73 @@
#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal ps5 switch2
#pragma kernel Allocate
#include "PatchAllocationRequest.hlsl"
#include "Common.hlsl"
#include "PatchUtil.hlsl"
RWStructuredBuffer<SphericalHarmonics::RGBL1> _PatchIrradiances0;
RWStructuredBuffer<SphericalHarmonics::RGBL1> _PatchIrradiances1;
RWStructuredBuffer<PatchUtil::PatchGeometry> _PatchGeometries;
RWStructuredBuffer<PatchUtil::PatchStatisticsSet> _PatchStatistics;
RWStructuredBuffer<uint> _PatchCellIndices;
RWStructuredBuffer<uint> _CellPatchIndices;
RWStructuredBuffer<uint> _CellAllocationMarks;
RWStructuredBuffer<uint> _RingConfigBuffer;
StructuredBuffer<PatchAllocationRequest> _Requests;
StructuredBuffer<uint> _RequestCount;
StructuredBuffer<int3> _VolumeCascadeOffsets;
uint _RingConfigOffset;
uint _VolumeSpatialResolution;
uint _VolumeCascadeCount;
float _VolumeVoxelMinSize;
float3 _VolumeTargetPos;
uint _FrameIndex;
[numthreads(256, 1, 1)]
void Allocate(uint threadIdx : SV_DispatchThreadID)
{
const uint requestCount = _RequestCount[0];
if (threadIdx < PatchAllocationRequestMax && threadIdx < requestCount)
{
PatchUtil::VolumeParamSet volumeParams;
volumeParams.spatialResolution = _VolumeSpatialResolution;
volumeParams.voxelMinSize = _VolumeVoxelMinSize;
volumeParams.targetPos = _VolumeTargetPos;
volumeParams.cascadeOffsets = _VolumeCascadeOffsets;
volumeParams.cascadeCount = _VolumeCascadeCount;
const PatchAllocationRequest req = _Requests[threadIdx];
PatchUtil::VolumePositionResolution patchPosResolution = PatchUtil::ResolveVolumePosition(req.position, volumeParams);
if (!patchPosResolution.isValid())
return;
const uint directionIdx = PatchUtil::GetDirectionIndex(req.normal, PatchUtil::volumeAngularResolution);
const uint3 positionStorageSpace = PatchUtil::ConvertVolumeSpaceToStorageSpace(patchPosResolution.positionVolumeSpace, volumeParams.spatialResolution, volumeParams.cascadeOffsets[patchPosResolution.cascadeIdx]);
const uint cellIdx = PatchUtil::GetCellIndex(patchPosResolution.cascadeIdx, positionStorageSpace, directionIdx, volumeParams.spatialResolution, PatchUtil::volumeAngularResolution);
PatchUtil::PatchIndexResolutionResult resolutionResult = PatchUtil::ResolvePatchIndex(
_RingConfigBuffer,
_RingConfigOffset,
_CellPatchIndices,
_PatchCellIndices,
_CellAllocationMarks,
cellIdx);
if (resolutionResult.code == PatchUtil::patchIndexResolutionCodeAllocationSuccess)
{
PatchUtil::PatchGeometry geo;
geo.position = req.position;
geo.normal = req.normal;
_PatchGeometries[resolutionResult.patchIdx] = geo;
SphericalHarmonics::RGBL1 irradianceSeed = (SphericalHarmonics::RGBL1)0;
_PatchIrradiances0[resolutionResult.patchIdx] = irradianceSeed;
_PatchIrradiances1[resolutionResult.patchIdx] = irradianceSeed;
_PatchStatistics[resolutionResult.patchIdx] = PatchUtil::InitPatchStatistics(irradianceSeed.l0, _FrameIndex, /*rank*/ 1);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b271ec1ddd8048458fa529e8e7cfe960
timeCreated: 1776242564
@@ -0,0 +1,12 @@
#ifndef SURFACE_CACHE_PATCH_ALLOCATION_REQUEST
#define SURFACE_CACHE_PATCH_ALLOCATION_REQUEST
struct PatchAllocationRequest
{
float3 position;
float3 normal;
};
static const uint PatchAllocationRequestMax = 1024;
#endif
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7ed0dbab70f0403298ce88263059d1d1
timeCreated: 1776245090

Some files were not shown because too many files have changed in this diff Show More