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,332 @@
using System;
using System.Collections.Generic;
using UnityEngine.Assertions;
using UnityEngine.Rendering;
namespace UnityEngine.Rendering
{
/// <summary>
/// Implement a multiple buffering for RenderTextures.
/// </summary>
/// <example>
/// <code>
/// enum BufferType
/// {
/// Color,
/// Depth
/// }
///
/// void Render()
/// {
/// var camera = GetCamera();
/// var buffers = GetFrameHistoryBuffersFor(camera);
///
/// // Set reference size in case the rendering size changed this frame
/// buffers.SetReferenceSize(
/// GetCameraWidth(camera), GetCameraHeight(camera),
/// GetCameraUseMSAA(camera), GetCameraMSAASamples(camera)
/// );
/// buffers.Swap();
///
/// var currentColor = buffer.GetFrameRT((int)BufferType.Color, 0);
/// if (currentColor == null) // Buffer was not allocated
/// {
/// buffer.AllocBuffer(
/// (int)BufferType.Color, // Color buffer id
/// ColorBufferAllocator, // Custom functor to implement allocation
/// 2 // Use 2 RT for this buffer for double buffering
/// );
/// currentColor = buffer.GetFrameRT((int)BufferType.Color, 0);
/// }
///
/// var previousColor = buffers.GetFrameRT((int)BufferType.Color, 1);
///
/// // Use previousColor and write into currentColor
/// }
/// </code>
/// </example>
public class BufferedRTHandleSystem : IDisposable
{
struct RTEntry
{
public RTHandle handle;
public int stableIndex;
}
Dictionary<int, RTEntry[]> m_RTEntries = new Dictionary<int, RTEntry[]>();
RTHandleSystem m_RTHandleSystem = new RTHandleSystem();
bool m_DisposedValue = false;
/// <summary>
/// Maximum allocated width of the Buffered RTHandle System
/// </summary>
public int maxWidth { get { return m_RTHandleSystem.GetMaxWidth(); } }
/// <summary>
/// Maximum allocated height of the Buffered RTHandle System
/// </summary>
public int maxHeight { get { return m_RTHandleSystem.GetMaxHeight(); } }
/// <summary>
/// Current properties of the Buffered RTHandle System
/// </summary>
public RTHandleProperties rtHandleProperties { get { return m_RTHandleSystem.rtHandleProperties; } }
bool TryGetFrameRenderTarget(int bufferId, int frameIndex, out RTEntry rt)
{
if (!m_RTEntries.ContainsKey(bufferId))
{
rt.handle = null;
rt.stableIndex = -1;
return false;
}
Assert.IsTrue(frameIndex >= 0 && frameIndex < m_RTEntries[bufferId].Length);
rt = m_RTEntries[bufferId][frameIndex];
return true;
}
/// <summary>
/// Return the frame RT or null.
/// </summary>
/// <param name="bufferId">Defines the buffer to use.</param>
/// <param name="frameIndex">Defines which frame to access within the buffer.</param>
/// <returns>The frame RT or null when the <paramref name="bufferId"/> was not previously allocated (<see cref="BufferedRTHandleSystem.AllocBuffer(int, Func{RTHandleSystem, int, RTHandle}, int)" />).</returns>
public RTHandle GetFrameRT(int bufferId, int frameIndex)
{
if (TryGetFrameRenderTarget(bufferId, frameIndex, out var rt))
return rt.handle;
return null;
}
/// <summary>
/// Return the frame RT's stable index or -1.
/// A stable index can be used to index into an array of user data assigned to each RT.
/// </summary>
/// <param name="bufferId">Defines the buffer to use.</param>
/// <param name="frameIndex">Defines which frame to access within the buffer.</param>
/// <returns>The frame RT stable index or -1 when the <paramref name="bufferId"/> was not previously allocated (<see cref="BufferedRTHandleSystem.AllocBuffer(int, Func{RTHandleSystem, int, RTHandle}, int)" />).</returns>
public int GetFrameRTStableIndex(int bufferId, int frameIndex)
{
if (TryGetFrameRenderTarget(bufferId, frameIndex, out var rt))
return rt.stableIndex;
return -1;
}
/// <summary>
/// Clears all the previously created history buffers
/// </summary>
/// <param name="cmd">Defines the command buffer used for clearing.</param>
public void ClearBuffers(CommandBuffer cmd)
{
foreach (var rtEntry in m_RTEntries)
{
for (int i = 0; i < rtEntry.Value.Length; ++i)
{
CoreUtils.SetRenderTarget(cmd, rtEntry.Value[i].handle, clearFlag: ClearFlag.Color, clearColor: Color.black);
}
}
}
/// <summary>
/// Allocate RT handles for a buffer.
/// </summary>
/// <param name="bufferId">The buffer to allocate.</param>
/// <param name="allocator">The functor to use for allocation.</param>
/// <param name="bufferCount">The number of RT handles for this buffer.</param>
public void AllocBuffer(
int bufferId,
Func<RTHandleSystem, int, RTHandle> allocator,
int bufferCount
)
{
// This function should only be used when there is a non-zero number of buffers to allocate.
// If the caller provides a value of zero, they're likely doing something unintentional in the calling code.
Debug.Assert(bufferCount > 0);
var buffer = new RTEntry[bufferCount];
m_RTEntries.Add(bufferId, buffer);
// First is autoresized
buffer[0].handle = allocator(m_RTHandleSystem, 0);
buffer[0].stableIndex = 0;
// Other are resized on demand
for (int i = 1, c = buffer.Length; i < c; ++i)
{
buffer[i].handle = allocator(m_RTHandleSystem, i);
buffer[i].stableIndex = i;
m_RTHandleSystem.SwitchResizeMode(buffer[i].handle, RTHandleSystem.ResizeMode.OnDemand);
}
}
/// <summary>
/// Allocate RT handles for a buffer using a RenderTextureDescriptor.
/// </summary>
/// <param name="bufferId">The buffer to allocate.</param>
/// <param name="bufferCount">The number of RT handles for this buffer.</param>
/// <param name="descriptor">RenderTexture descriptor of the RTHandles.</param>
/// <param name="filterMode">Filtering mode of the RTHandles.</param>
/// <param name="wrapMode">Addressing mode of the RTHandles.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="name">Name of the RTHandle.</param>
// NOTE: API is similar to RTHandles.Alloc.
public void AllocBuffer(int bufferId, int bufferCount,
ref RenderTextureDescriptor descriptor,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
string name = "")
{
// This function should only be used when there is a non-zero number of buffers to allocate.
// If the caller provides a value of zero, they're likely doing something unintentional in the calling code.
Debug.Assert(bufferCount > 0);
var buffer = new RTEntry[bufferCount];
m_RTEntries.Add(bufferId, buffer);
RTHandleAllocInfo allocInfo = RTHandles.GetRTHandleAllocInfo(descriptor, filterMode,
wrapMode, anisoLevel, mipMapBias, name);
allocInfo.isShadowMap = isShadowMap;
// First is autoresized
buffer[0].handle = m_RTHandleSystem.Alloc(descriptor.width, descriptor.height, allocInfo);
buffer[0].stableIndex = 0;
// Other are resized on demand
for (int i = 1, c = buffer.Length; i < c; ++i)
{
buffer[i].handle = m_RTHandleSystem.Alloc(descriptor.width, descriptor.height, allocInfo);
buffer[i].stableIndex = i;
}
}
/// <summary>
/// Release a buffer
/// </summary>
/// <param name="bufferId">Id of the buffer that needs to be released.</param>
public void ReleaseBuffer(int bufferId)
{
if (m_RTEntries.TryGetValue(bufferId, out var buffers))
{
foreach (var rt in buffers)
m_RTHandleSystem.Release(rt.handle);
}
m_RTEntries.Remove(bufferId);
}
/// <summary>
/// Swap buffers Set the reference size for this RT Handle System (<see cref="RTHandleSystem.SetReferenceSize(int, int, bool)"/>)
/// </summary>
/// <param name="width">The width of the RTs of this buffer.</param>
/// <param name="height">The height of the RTs of this buffer.</param>
public void SwapAndSetReferenceSize(int width, int height)
{
Swap();
m_RTHandleSystem.SetReferenceSize(width, height);
}
/// <summary>
/// Reset the reference size of the system and reallocate all textures.
/// </summary>
/// <param name="width">New width.</param>
/// <param name="height">New height.</param>
public void ResetReferenceSize(int width, int height)
{
m_RTHandleSystem.ResetReferenceSize(width, height);
}
/// <summary>
/// Queries the number of RT handle buffers allocated for a buffer ID.
/// </summary>
/// <param name="bufferId">The buffer ID to query.</param>
/// <returns>The num of frames allocated</returns>
public int GetNumFramesAllocated(int bufferId)
{
if (!m_RTEntries.ContainsKey(bufferId))
return 0;
return m_RTEntries[bufferId].Length;
}
/// <summary>
/// Returns the ratio against the current target's max resolution
/// </summary>
/// <param name="width">width to utilize</param>
/// <param name="height">height to utilize</param>
/// <returns> retruns the width,height / maxTargetSize.xy ratio. </returns>
public Vector2 CalculateRatioAgainstMaxSize(int width, int height)
{
return m_RTHandleSystem.CalculateRatioAgainstMaxSize(new Vector2Int(width, height));
}
void Swap()
{
foreach (var rtEntry in m_RTEntries)
{
// Do not index out of bounds...
if (rtEntry.Value.Length > 1)
{
var nextFirst = rtEntry.Value[rtEntry.Value.Length - 1];
for (int i = rtEntry.Value.Length - 1; i > 0; --i)
rtEntry.Value[i] = rtEntry.Value[i - 1];
rtEntry.Value[0] = nextFirst;
// First is autoresize, other are on demand
m_RTHandleSystem.SwitchResizeMode(rtEntry.Value[0].handle, RTHandleSystem.ResizeMode.Auto);
m_RTHandleSystem.SwitchResizeMode(rtEntry.Value[1].handle, RTHandleSystem.ResizeMode.OnDemand);
}
else
{
m_RTHandleSystem.SwitchResizeMode(rtEntry.Value[0].handle, RTHandleSystem.ResizeMode.Auto);
}
}
}
void Dispose(bool disposing)
{
if (!m_DisposedValue)
{
if (disposing)
{
ReleaseAll();
m_RTHandleSystem.Dispose();
m_RTHandleSystem = null;
}
m_DisposedValue = true;
}
}
/// <summary>
/// Dispose implementation
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Deallocate and clear all buffers.
/// </summary>
public void ReleaseAll()
{
foreach (var rtEntry in m_RTEntries)
{
for (int i = 0, c = rtEntry.Value.Length; i < c; ++i)
{
m_RTHandleSystem.Release(rtEntry.Value[i].handle);
}
}
m_RTEntries.Clear();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cc56f4b85f1be9749add0bb4a25a4e4b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,20 @@
namespace UnityEngine.Rendering
{
/// <summary>
/// Bit depths of a Depth render texture.
/// Some values may not be supported on all platforms.
/// </summary>
public enum DepthBits
{
/// <summary>No Depth Buffer.</summary>
None = 0,
/// <summary>8 bits Depth Buffer.</summary>
Depth8 = 8,
/// <summary>16 bits Depth Buffer.</summary>
Depth16 = 16,
/// <summary>24 bits Depth Buffer.</summary>
Depth24 = 24,
/// <summary>32 bits Depth Buffer.</summary>
Depth32 = 32
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d063f57ca4b7cd346a14a1be20de65b4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,17 @@
namespace UnityEngine.Rendering
{
/// <summary>
/// Number of MSAA samples.
/// </summary>
public enum MSAASamples
{
/// <summary>No MSAA.</summary>
None = 1,
/// <summary>MSAA 2X.</summary>
MSAA2x = 2,
/// <summary>MSAA 4X.</summary>
MSAA4x = 4,
/// <summary>MSAA 8X.</summary>
MSAA8x = 8
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9abeb67ba9136f940a7b78095f5b43d8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,498 @@
using System;
using System.Collections.Generic;
using UnityEngine.Experimental.Rendering;
namespace UnityEngine.Rendering
{
/// <summary>
/// Texture atlas with rectangular power of two size.
/// </summary>
public class PowerOfTwoTextureAtlas : Texture2DAtlas
{
readonly int m_MipPadding;
const float k_MipmapFactorApprox = 1.33f;
private Dictionary<TextureIdentifier, Vector2Int> m_RequestedTextures = new Dictionary<TextureIdentifier, Vector2Int>();
/// <summary>
/// Create a new texture atlas, must have power of two size.
/// </summary>
/// <param name="size">The size of the atlas in pixels. Must be power of two.</param>
/// <param name="mipPadding">Amount of mip padding in power of two.</param>
/// <param name="format">Atlas texture format</param>
/// <param name="filterMode">Atlas texture filter mode.</param>
/// <param name="name">Name of the atlas</param>
/// <param name="useMipMap">Use mip maps</param>
public PowerOfTwoTextureAtlas(int size, int mipPadding, GraphicsFormat format, FilterMode filterMode = FilterMode.Point, string name = "", bool useMipMap = true)
: base(size, size, format, filterMode, true, name, useMipMap)
{
this.m_MipPadding = mipPadding;
// Check if size is a power of two
if ((size & (size - 1)) != 0)
Debug.Assert(false, "Power of two atlas was constructed with non power of two size: " + size);
}
/// <summary>
/// Used mipmap padding size in power of two.
/// </summary>
public int mipPadding => m_MipPadding;
int GetTexturePadding() => (int)Mathf.Pow(2, m_MipPadding) * 2;
/// <summary>
/// Get location of the actual texture data without padding in the atlas.
/// </summary>
/// <param name="texture">The source texture cached in the atlas.</param>
/// <param name="scaleOffset">Cached atlas location (scale and offset) for the source texture.</param>
/// <returns>Scale and offset for the source texture without padding.</returns>
public Vector4 GetPayloadScaleOffset(Texture texture, in Vector4 scaleOffset)
{
int pixelPadding = GetTexturePadding();
Vector2 paddingSize = Vector2.one * pixelPadding;
Vector2 textureSize = GetPowerOfTwoTextureSize(texture);
return GetPayloadScaleOffset(textureSize, paddingSize, scaleOffset);
}
/// <summary>
/// Get location of the actual texture data without padding in the atlas.
/// </summary>
/// <param name="textureSize">Size of the source texture</param>
/// <param name="paddingSize">Padding size used for the source texture. </param>
/// <param name="scaleOffset">Cached atlas location (scale and offset) for the source texture.</param>
/// <returns>Scale and offset for the source texture without padding.</returns>
static public Vector4 GetPayloadScaleOffset(in Vector2 textureSize, in Vector2 paddingSize, in Vector4 scaleOffset)
{
// Scale, Offset is a padded atlas sub-texture rectangle.
// Actual texture data (payload) is inset, i.e. padded inwards.
Vector2 subTexScale = new Vector2(scaleOffset.x, scaleOffset.y);
Vector2 subTexOffset = new Vector2(scaleOffset.z, scaleOffset.w);
// NOTE: Should match Blit() padding calculations.
Vector2 scalePadding = ((textureSize + paddingSize) / textureSize); // Size of padding (sampling) rectangle relative to the payload texture.
Vector2 offsetPadding = (paddingSize / 2.0f) / (textureSize + paddingSize); // Padding offset in the padding rectangle
Vector2 insetScale = subTexScale / scalePadding; // Size of payload rectangle in sub-tex
Vector2 insetOffset = subTexOffset + subTexScale * offsetPadding; // Offset of payload rectangle in sub-tex
return new Vector4(insetScale.x, insetScale.y, insetOffset.x, insetOffset.y);
}
private enum BlitType
{
Padding,
PaddingMultiply,
OctahedralPadding,
OctahedralPaddingMultiply,
}
private void Blit2DTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, BlitType blitType)
{
int mipCount = GetTextureMipmapCount(texture.width, texture.height);
int pixelPadding = GetTexturePadding();
Vector2 textureSize = GetPowerOfTwoTextureSize(texture);
bool bilinear = texture.filterMode != FilterMode.Point;
if (!blitMips)
mipCount = 1;
using (new ProfilingScope(cmd, CoreProfilingSamplers.BlitTextureInPotAtlas, texture))
{
for (int mipLevel = 0; mipLevel < mipCount; mipLevel++)
{
cmd.SetRenderTarget(m_AtlasTexture, mipLevel);
switch (blitType)
{
case BlitType.Padding: Blitter.BlitQuadWithPadding(cmd, texture, textureSize, sourceScaleOffset, scaleOffset, mipLevel, bilinear, pixelPadding); break;
case BlitType.PaddingMultiply: Blitter.BlitQuadWithPaddingMultiply(cmd, texture, textureSize, sourceScaleOffset, scaleOffset, mipLevel, bilinear, pixelPadding); break;
case BlitType.OctahedralPadding: Blitter.BlitOctahedralWithPadding(cmd, texture, textureSize, sourceScaleOffset, scaleOffset, mipLevel, bilinear, pixelPadding); break;
case BlitType.OctahedralPaddingMultiply: Blitter.BlitOctahedralWithPaddingMultiply(cmd, texture, textureSize, sourceScaleOffset, scaleOffset, mipLevel, bilinear, pixelPadding); break;
}
}
}
}
/// <summary>
/// Blit texture into the atlas with padding.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="blitMips">Blit mip maps.</param>
/// <param name="overrideInstanceID">Override texture instance ID.</param>
[Obsolete("BlitTexture(CommandBuffer, Vector4, Texture, Vector4, bool, int) is obsolete, use BlitTexture(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.", true)]
public override void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, int overrideInstanceID)
{
int instanceID = overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId();
TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID);
BlitTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, identifier);
}
/// <summary>
/// Blit texture into the atlas with padding.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="overrideInstanceID">Override texture instance ID.</param>
[Obsolete("BlitTexture(CommandBuffer, Vector4, Texture, Vector4, int) is obsolete, use BlitTexture(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.", true)]
public override void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, int overrideInstanceID)
{
BlitTexture(cmd, scaleOffset, texture, sourceScaleOffset, true, overrideInstanceID);
}
/// <summary>
/// Blit texture into the atlas with padding.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="blitMips">Blit mip maps.</param>
/// <param name="overrideIdentifier">Override texture identifier.</param>
public override void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, TextureIdentifier overrideIdentifier = default)
{
// We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering
if (Is2D(texture))
{
Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.Padding);
MarkGPUTextureValid(overrideIdentifier != default ? overrideIdentifier : GetTextureIdentifier(texture), blitMips);
}
}
/// <summary>
/// Blit texture into the atlas with padding and blending.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="blitMips">Blit mip maps.</param>
/// <param name="overrideInstanceID">Override texture instance ID.</param>
[Obsolete("BlitTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool, int) is obsolete, use BlitTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.", true)]
public void BlitTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, int overrideInstanceID)
{
int instanceID = overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId();
TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID);
BlitTextureMultiply(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, identifier);
}
/// <summary>
/// Blit texture into the atlas with padding and blending.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="overrideInstanceID">Override texture instance ID.</param>
[Obsolete("BlitTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, int) is obsolete, use BlitTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.", true)]
public void BlitTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, int overrideInstanceID)
{
BlitTextureMultiply(cmd, scaleOffset, texture, sourceScaleOffset, true, overrideInstanceID);
}
/// <summary>
/// Blit texture into the atlas with padding and blending.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="blitMips">Blit mip maps.</param>
/// <param name="overrideIdentifier">Override texture identifier.</param>
public void BlitTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, TextureIdentifier overrideIdentifier = default)
{
// We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering
if (Is2D(texture))
{
Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.PaddingMultiply);
MarkGPUTextureValid(overrideIdentifier != default ? overrideIdentifier : GetTextureIdentifier(texture), blitMips);
}
}
/// <summary>
/// Blit octahedral texture into the atlas with padding.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="blitMips">Blit mip maps.</param>
/// <param name="overrideInstanceID">Override texture instance ID.</param>
[Obsolete("BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, bool, int) is obsolete, use BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, bool ,TextureIdentifier ) instead.", true)]
public override void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, int overrideInstanceID)
{
int instanceID = overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId();
TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID);
BlitOctahedralTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, identifier);
}
/// <summary>
/// Blit octahedral texture into the atlas with padding.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="overrideInstanceID">Override texture instance ID.</param>
[Obsolete("BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, int) is obsolete, use BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, bool ,TextureIdentifier ) instead.", true)]
public override void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, int overrideInstanceID)
{
BlitOctahedralTexture(cmd, scaleOffset, texture, sourceScaleOffset, true, overrideInstanceID);
}
/// <summary>
/// Blit octahedral texture into the atlas with padding.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="blitMips">Blit mip maps.</param>
/// <param name="textureIdentifier">Override texture identifier.</param>
public override void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, TextureIdentifier textureIdentifier = default)
{
// We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering
if (Is2D(texture))
{
Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.OctahedralPadding);
MarkGPUTextureValid(textureIdentifier != default ? textureIdentifier : GetTextureIdentifier(texture), blitMips);
}
}
/// <summary>
/// Blit octahedral texture into the atlas with padding.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="blitMips">Blit mip maps.</param>
/// <param name="overrideInstanceID">Override texture instance ID.</param>
[Obsolete("BlitOctahedralTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool, int) is obsolete, use BlitOctahedralTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool,TextureIdentifier ) instead.", true)]
public void BlitOctahedralTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, int overrideInstanceID )
{
int instanceID = overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId();
TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID);
BlitOctahedralTextureMultiply(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, identifier);
}
/// <summary>
/// Blit octahedral texture into the atlas with padding.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="overrideInstanceID">Override texture instance ID.</param>
[Obsolete("BlitOctahedralTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, int) is obsolete, use BlitOctahedralTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool,TextureIdentifier ) instead.", true)]
public void BlitOctahedralTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, int overrideInstanceID )
{
BlitOctahedralTextureMultiply(cmd, scaleOffset, texture, sourceScaleOffset, true, overrideInstanceID);
}
/// <summary>
/// Blit octahedral texture into the atlas with padding.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Destination scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="sourceScaleOffset">Source scale (.xy) and offset(.zw).</param>
/// <param name="blitMips">Blit mip maps.</param>
/// <param name="overrideIdentifier">Override texture identifier.</param>
public void BlitOctahedralTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, TextureIdentifier overrideIdentifier = default)
{
// We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering
if (Is2D(texture))
{
Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.OctahedralPaddingMultiply);
MarkGPUTextureValid(overrideIdentifier != default ? overrideIdentifier : GetTextureIdentifier(texture), blitMips);
}
}
void TextureSizeToPowerOfTwo(Texture texture, ref int width, ref int height)
{
// Change the width and height of the texture to be power of two
width = Mathf.NextPowerOfTwo(width);
height = Mathf.NextPowerOfTwo(height);
}
Vector2 GetPowerOfTwoTextureSize(Texture texture)
{
int width = texture.width, height = texture.height;
TextureSizeToPowerOfTwo(texture, ref width, ref height);
return new Vector2(width, height);
}
// Override the behavior when we add a texture so all non-pot textures are blitted to a pot target zone
/// <summary>
/// Allocate space from the atlas for a texture and copy texture contents into the atlas.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Allocated scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="width">Request width in pixels.</param>
/// <param name="height">Request height in pixels.</param>
/// <param name="overrideInstanceID">Override texture instance ID.</param>
/// <returns>True on success, false otherwise.</returns>
[Obsolete("AllocateTexture(CommandBuffer, ref Vector4, Texture, int, int, int) is obsolete, use AllocateTexture(CommandBuffer, ref Vector4, Texture, int, int, TextureIdentifier) instead.", true)]
public override bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, Texture texture, int width, int height, int overrideInstanceID)
{
TextureIdentifier identifier = new TextureIdentifier((ulong)overrideInstanceID);
return AllocateTexture(cmd, ref scaleOffset, texture, width, height, identifier);
}
// Override the behavior when we add a texture so all non-pot textures are blitted to a pot target zone
/// <summary>
/// Allocate space from the atlas for a texture and copy texture contents into the atlas.
/// </summary>
/// <param name="cmd">Target command buffer for graphics commands.</param>
/// <param name="scaleOffset">Allocated scale (.xy) and offset (.zw)</param>
/// <param name="texture">Source Texture</param>
/// <param name="width">Request width in pixels.</param>
/// <param name="height">Request height in pixels.</param>
/// <param name="overrideIdentifier">Override texture identifier.</param>
/// <returns>True on success, false otherwise.</returns>
public override bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, Texture texture, int width, int height, TextureIdentifier overrideIdentifier = default)
{
// This atlas only supports square textures
if (height != width)
{
Debug.LogError("Can't place " + texture + " in the atlas " + m_AtlasTexture.name + ": Only squared texture are allowed in this atlas.");
return false;
}
TextureSizeToPowerOfTwo(texture, ref height, ref width);
return base.AllocateTexture(cmd, ref scaleOffset, texture, width, height, default(TextureIdentifier));
}
/// <summary>
/// Clear tracked requested textures.
/// </summary>
public void ResetRequestedTexture() => m_RequestedTextures.Clear();
/// <summary>
/// Reserves the space on the texture atlas
/// </summary>
/// <param name="texture">The source texture</param>
/// <returns>True if the space is reserved</returns>
public bool ReserveSpace(Texture texture) => ReserveSpace(texture, texture.width, texture.height);
/// <summary>
/// Reserves the space on the texture atlas
/// </summary>
/// <param name="texture">The source texture</param>
/// <param name="width">The width</param>
/// <param name="height">The height</param>
/// <returns>True if the space is reserved</returns>
public bool ReserveSpace(Texture texture, int width, int height)
=> ReserveSpace(GetTextureIdentifier(texture), width, height);
/// <summary>
/// Reserves the space on the texture atlas
/// </summary>
/// <param name="textureA">The source texture A</param>
/// <param name="textureB">The source texture B</param>
/// <param name="width">The width</param>
/// <param name="height">The height</param>
/// <returns>True if the space is reserved</returns>
public bool ReserveSpace(Texture textureA, Texture textureB, int width, int height)
=> ReserveSpace(GetTextureIdentifier(textureA, textureB), width, height);
/// <summary>
/// Reserves the space on the texture atlas
/// </summary>
/// <param name="id">The id</param>
/// <param name="width">The width</param>
/// <param name="height">The height</param>
/// <returns>True if the space is reserved</returns>
[Obsolete("ReserveSpace with int id is obsolete, use the TextureIdentifier version instead.", true)]
public bool ReserveSpace(int id, int width, int height)
{
TextureIdentifier identifier = new TextureIdentifier((ulong)id);
return ReserveSpace(identifier, width, height);
}
/// <summary>
/// Reserves the space on the texture atlas
/// </summary>
/// <param name="identifier">The id</param>
/// <param name="width">The width</param>
/// <param name="height">The height</param>
/// <returns>True if the space is reserved</returns>
public bool ReserveSpace(TextureIdentifier identifier, int width, int height)
{
m_RequestedTextures[identifier] = new Vector2Int(width, height);
// Cookie texture resolution changing between frame is a special case, so we handle it here.
// The texture will be re-allocated and may cause holes in the atlas texture, which is fine
// because when it doesn't have any more space, it will re-layout the texture correctly.
var cachedSize = GetCachedTextureSize(identifier);
if (!IsCached(out _, identifier) || cachedSize.x != width || cachedSize.y != height)
{
Vector4 scaleBias = Vector4.zero;
if (!AllocateTextureWithoutBlit(identifier, width, height, ref scaleBias))
return false;
}
return true;
}
/// <summary>
/// sort all the requested allocation from biggest to smallest and re-insert them.
/// This function does not moves the textures in the atlas, it only changes their coordinates
/// </summary>
/// <returns>True if all textures have successfully been re-inserted in the atlas</returns>
public bool RelayoutEntries()
{
var entries = new List<(TextureIdentifier identifier, Vector2Int size)>();
foreach (var entry in m_RequestedTextures)
entries.Add((entry.Key, entry.Value));
ResetAllocator();
// Sort entries from biggest to smallest
entries.Sort((c1, c2) =>
{
return c2.size.magnitude.CompareTo(c1.size.magnitude);
});
bool success = true;
Vector4 newScaleOffset = Vector4.zero;
foreach (var e in entries)
success &= AllocateTextureWithoutBlit(e.identifier, e.size.x, e.size.y, ref newScaleOffset);
return success;
}
/// <summary>
/// Get cache size in bytes.
/// </summary>
/// <param name="nbElement">The number of elements stored in the cache.</param>
/// <param name="resolution">Atlas resolution (square).</param>
/// <param name="hasMipmap">Atlas uses mip maps.</param>
/// <param name="format">Atlas format.</param>
/// <returns>The approximate size of the cache in bytes.</returns>
public static long GetApproxCacheSizeInByte(int nbElement, int resolution, bool hasMipmap, GraphicsFormat format)
=> (long)(nbElement * resolution * resolution * (double)((hasMipmap ? k_MipmapFactorApprox : 1.0f) * GraphicsFormatUtility.GetBlockSize(format)));
/// <summary>
/// Compute the max size of a power of two atlas for a given size in byte (weight).
/// </summary>
/// <param name="weight">Atlas size in bytes.</param>
/// <param name="hasMipmap">Atlas uses mip maps.</param>
/// <param name="format">Atlas format.</param>
/// <returns>The largest possible resolution for a square atlas, constrained by weight, as a power of two value.</returns>
public static int GetMaxCacheSizeForWeightInByte(int weight, bool hasMipmap, GraphicsFormat format)
{
float bytePerPixel = (float)GraphicsFormatUtility.GetBlockSize(format) * (hasMipmap ? k_MipmapFactorApprox : 1.0f);
var maxAtlasSquareSize = Mathf.Sqrt((float)weight / bytePerPixel);
return CoreUtils.PreviousPowerOfTwo((int)maxAtlasSquareSize);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b265844b35f3cf14bb3e83aa57395937
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,343 @@
using System;
using System.Collections.Generic;
using UnityEngine.Rendering;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Rendering
{
/// <summary>
/// This struct contains some static helpers that can be used when converting RTid to RThandle
/// The common use case is to convert rtId to rtHandle and use the handle with other handle compatible core APIs
/// </summary>
public struct RTHandleStaticHelpers
{
/// <summary>
/// Static RTHandle wrapper around RenderTargetIdentifier to avoid gc.alloc
/// Set this wrapper through `RTHandleStaticHelpers.SetRTHandleStaticWrapper`
/// </summary>
public static RTHandle s_RTHandleWrapper;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
s_RTHandleWrapper = null;
}
#endif
/// <summary>
/// Set static RTHandle wrapper given a RTid. The static RTHandle wrapper is treated as external handle in RTHandleSystem
/// Get the static wrapper through `RTHandleStaticHelpers.s_RTHandleWrapper`.
/// </summary>
/// <param name="rtId">Input render target identifier to be converted.</param>
public static void SetRTHandleStaticWrapper(RenderTargetIdentifier rtId)
{
if (s_RTHandleWrapper == null)
s_RTHandleWrapper = RTHandles.Alloc(rtId);
else
s_RTHandleWrapper.SetTexture(rtId);
}
/// <summary>
/// Set user managed RTHandle wrapper given a RTid. The wrapper is treated as external handle in RTHandleSystem
/// </summary>
/// <param name="rtWrapper">User managed RTHandle wrapper.</param>
/// <param name="rtId">Input render target identifier to be set.</param>
public static void SetRTHandleUserManagedWrapper(ref RTHandle rtWrapper, RenderTargetIdentifier rtId)
{
// User managed wrapper is null, just return here.
if (rtWrapper == null)
return;
#if UNITY_ENABLE_CHECKS
// Check user managed RTHandle wrapper is actually a wrapper around RTid
if (rtWrapper.m_RT != null)
throw new ArgumentException($"Input wrapper must be a wrapper around RenderTargetIdentifier. Passed in wrapper contains valid RenderTexture {rtWrapper.m_RT.name} and cannot be used as wrapper.");
if (rtWrapper.m_ExternalTexture != null)
throw new ArgumentException($"Input wrapper must be a wrapper around RenderTargetIdentifier. Passed in wrapper contains valid Texture {rtWrapper.m_ExternalTexture.name} and cannot be used as wrapper.");
#endif
rtWrapper.SetTexture(rtId);
}
}
/// <summary>
/// A RTHandle is a RenderTexture that scales automatically with the camera size.
/// This allows proper reutilization of RenderTexture memory when different cameras with various sizes are used during rendering.
/// <see cref="RTHandleSystem"/>
/// </summary>
public class RTHandle
{
internal RTHandleSystem m_Owner;
internal RenderTexture m_RT;
internal Texture m_ExternalTexture;
internal RenderTargetIdentifier m_NameID;
internal bool m_EnableMSAA = false;
internal bool m_EnableRandomWrite = false;
internal bool m_EnableHWDynamicScale = false;
internal bool m_RTHasOwnership = true;
internal string m_Name;
internal bool m_UseCustomHandleScales = false;
internal RTHandleProperties m_CustomHandleProperties;
/// <summary>
/// By default, rtHandleProperties gets the global state of scalers against the global reference mode.
/// This method lets the current RTHandle use a local custom RTHandleProperties. This function is being used
/// by scalers such as TAAU and DLSS, which require to have a different resolution for color (independent of the RTHandleSystem).
/// </summary>
/// <param name="properties">Properties to set.</param>
public void SetCustomHandleProperties(in RTHandleProperties properties)
{
m_UseCustomHandleScales = true;
m_CustomHandleProperties = properties;
}
/// <summary>
/// Method that clears any custom handle property being set.
/// </summary>
public void ClearCustomHandleProperties()
{
m_UseCustomHandleScales = false;
}
/// <summary>
/// Scale factor applied to the RTHandle reference size.
/// </summary>
public Vector2 scaleFactor { get; internal set; }
internal ScaleFunc scaleFunc;
/// <summary>
/// Returns true if the RTHandle uses automatic scaling.
/// </summary>
public bool useScaling { get; internal set; }
/// <summary>
/// Reference size of the RTHandle System associated with the RTHandle
/// </summary>
public Vector2Int referenceSize { get; internal set; }
/// <summary>
/// Current properties of the RTHandle System. If a custom property has been set through SetCustomHandleProperties method, it will be used that one instead.
/// </summary>
public RTHandleProperties rtHandleProperties { get { return m_UseCustomHandleScales ? m_CustomHandleProperties : m_Owner.rtHandleProperties; } }
/// <summary>
/// RenderTexture associated with the RTHandle
/// </summary>
public RenderTexture rt { get { return m_RT; } }
/// <summary>
/// Texture associated with the RTHandle when constructed from an external Texture or RenderTexture
/// </summary>
public Texture externalTexture { get { return m_ExternalTexture; } }
/// <summary>
/// RenderTargetIdentifier associated with the RTHandle
/// </summary>
public RenderTargetIdentifier nameID { get { return m_NameID; } }
/// <summary>
/// Name of the RTHandle
/// </summary>
public string name { get { return m_Name; } }
/// <summary>
/// Returns true is MSAA is enabled, false otherwise.
/// </summary>
public bool isMSAAEnabled { get { return m_EnableMSAA; } }
// Keep constructor private
internal RTHandle(RTHandleSystem owner)
{
m_Owner = owner;
}
/// <summary>
/// Implicit conversion operator to RenderTargetIdentifier
/// </summary>
/// <param name="handle">Input RTHandle</param>
/// <returns>RenderTargetIdentifier representation of the RTHandle.</returns>
public static implicit operator RenderTargetIdentifier(RTHandle handle)
{
return handle != null ? handle.nameID : default(RenderTargetIdentifier);
}
/// <summary>
/// Implicit conversion operator to Texture
/// </summary>
/// <param name="handle">Input RTHandle</param>
/// <returns>Texture representation of the RTHandle.</returns>
public static implicit operator Texture(RTHandle handle)
{
// If RTHandle is null then conversion should give a null Texture
if (handle == null)
return null;
Debug.Assert(handle.m_ExternalTexture != null || handle.rt != null);
return (handle.rt != null) ? handle.rt : handle.m_ExternalTexture;
}
/// <summary>
/// Implicit conversion operator to RenderTexture
/// </summary>
/// <param name="handle">Input RTHandle</param>
/// <returns>RenderTexture representation of the RTHandle.</returns>
public static implicit operator RenderTexture(RTHandle handle)
{
// If RTHandle is null then conversion should give a null RenderTexture
if (handle == null)
return null;
Debug.Assert(handle.rt != null, "RTHandle was created using a regular Texture and is used as a RenderTexture");
return handle.rt;
}
internal void SetRenderTexture(RenderTexture rt, bool transferOwnership = true)
{
m_RT = rt;
m_ExternalTexture = null;
m_RTHasOwnership = transferOwnership;
m_NameID = new RenderTargetIdentifier(rt);
}
internal void SetTexture(Texture tex)
{
m_RT = null;
m_ExternalTexture = tex;
m_NameID = new RenderTargetIdentifier(tex);
}
internal void SetTexture(RenderTargetIdentifier tex)
{
m_RT = null;
m_ExternalTexture = null;
m_NameID = tex;
}
/// <summary>
/// Get the identifier of the RTHandle.
/// </summary>
/// <returns>The RTHandle identifier.</returns>
public ulong GetUniqueID()
{
if (m_RT != null)
return EntityId.ToULong(m_RT.GetEntityId());
else if (m_ExternalTexture != null)
return EntityId.ToULong(m_ExternalTexture.GetEntityId());
else
return (ulong)m_NameID.GetHashCode(); // No instance ID so we return the hash code.
}
/// <summary>
/// Get the Instance ID of the RTHandle.
/// </summary>
/// <returns>The RTHandle Instance ID.</returns>
[Obsolete("GetInstanceID() is obsolete, use GetUniqueID() instead.", true)]
public int GetInstanceID()
{
if (m_RT != null)
return m_RT.GetInstanceID();
else if (m_ExternalTexture != null)
return m_ExternalTexture.GetInstanceID();
else
return m_NameID.GetHashCode(); // No instance ID so we return the hash code.
}
/// <summary>
/// Release the RTHandle
/// </summary>
public void Release()
{
m_Owner.Remove(this);
if (m_RTHasOwnership)
CoreUtils.Destroy(m_RT);
m_NameID = BuiltinRenderTextureType.None;
m_RT = null;
m_ExternalTexture = null;
m_RTHasOwnership = true;
}
/// <summary>
/// Return the input size, scaled by the RTHandle scale factor.
/// </summary>
/// <param name="refSize">Input size</param>
/// <returns>Input size scaled by the RTHandle scale factor.</returns>
public Vector2Int GetScaledSize(Vector2Int refSize)
{
if (!useScaling)
return refSize;
if (scaleFunc != null)
{
return scaleFunc(refSize);
}
else
{
return new Vector2Int(
x: Mathf.RoundToInt(scaleFactor.x * refSize.x),
y: Mathf.RoundToInt(scaleFactor.y * refSize.y)
);
}
}
/// <summary>
/// Return the scaled size of the RTHandle.
/// </summary>
/// <returns>The scaled size of the RTHandle.</returns>
public Vector2Int GetScaledSize()
{
if (!useScaling)
return referenceSize;
if (scaleFunc != null)
{
return scaleFunc(referenceSize);
}
else
{
return new Vector2Int(
x: Mathf.RoundToInt(scaleFactor.x * referenceSize.x),
y: Mathf.RoundToInt(scaleFactor.y * referenceSize.y)
);
}
}
/// <summary>
/// Switch the render target to fast memory on platform that have it.
/// </summary>
/// <param name="cmd">Command buffer used for rendering.</param>
/// <param name="residencyFraction">How much of the render target is to be switched into fast memory (between 0 and 1).</param>
/// <param name="flags">Flag to determine what parts of the render target is spilled if not fully resident in fast memory.</param>
/// <param name="copyContents">Whether the content of render target are copied or not when switching to fast memory.</param>
public void SwitchToFastMemory(CommandBuffer cmd,
float residencyFraction = 1.0f,
FastMemoryFlags flags = FastMemoryFlags.SpillTop,
bool copyContents = false
)
{
residencyFraction = Mathf.Clamp01(residencyFraction);
cmd.SwitchIntoFastMemory(m_RT, flags, residencyFraction, copyContents);
}
/// <summary>
/// Switch the render target to fast memory on platform that have it and copies the content.
/// </summary>
/// <param name="cmd">Command buffer used for rendering.</param>
/// <param name="residencyFraction">How much of the render target is to be switched into fast memory (between 0 and 1).</param>
/// <param name="flags">Flag to determine what parts of the render target is spilled if not fully resident in fast memory.</param>
public void CopyToFastMemory(CommandBuffer cmd,
float residencyFraction = 1.0f,
FastMemoryFlags flags = FastMemoryFlags.SpillTop
)
{
SwitchToFastMemory(cmd, residencyFraction, flags, copyContents: true);
}
/// <summary>
/// Switch out the render target from fast memory back to main memory on platforms that have fast memory.
/// </summary>
/// <param name="cmd">Command buffer used for rendering.</param>
/// <param name="copyContents">Whether the content of render target are copied or not when switching out fast memory.</param>
public void SwitchOutFastMemory(CommandBuffer cmd, bool copyContents = true)
{
cmd.SwitchOutOfFastMemory(m_RT, copyContents);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f01477642fe8bcf46af0f654f65043cf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ee2d997a8a7c5de408c0a4194b1a8b4d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,834 @@
using System;
using System.Runtime.CompilerServices;
using UnityEngine.Assertions;
using UnityEngine.Experimental.Rendering;
namespace UnityEngine.Rendering
{
/// <summary>
/// Default instance of a RTHandleSystem
/// </summary>
public static class RTHandles
{
static RTHandleSystem s_DefaultInstance = new RTHandleSystem();
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
s_DefaultInstance?.Dispose();
s_DefaultInstance = new RTHandleSystem();
}
#endif
/// <summary>
/// Maximum allocated width of the default RTHandle System
/// </summary>
public static int maxWidth { get { return s_DefaultInstance.GetMaxWidth(); } }
/// <summary>
/// Maximum allocated height of the default RTHandle System
/// </summary>
public static int maxHeight { get { return s_DefaultInstance.GetMaxHeight(); } }
/// <summary>
/// Current properties of the default RTHandle System
/// </summary>
public static RTHandleProperties rtHandleProperties { get { return s_DefaultInstance.rtHandleProperties; } }
/// <summary>
/// Calculate the dimensions (in pixels) of the RTHandles given the scale factor.
/// </summary>
/// <param name="scaleFactor">The scale factor to use when calculating the dimensions. The base unscaled size used, is the sizes passed to the last ResetReferenceSize call.</param>
/// <returns>The calculated dimensions.</returns>
public static Vector2Int CalculateDimensions(Vector2 scaleFactor)
{
return s_DefaultInstance.CalculateDimensions(scaleFactor);
}
/// <summary>
/// Calculate the dimensions (in pixels) of the RTHandles given the scale function. The base unscaled size used, is the sizes passed to the last ResetReferenceSize call.
/// </summary>
/// <param name="scaleFunc">The scale function to use when calculating the dimensions.</param>
/// <returns>The calculated dimensions.</returns>
public static Vector2Int CalculateDimensions(ScaleFunc scaleFunc)
{
return s_DefaultInstance.CalculateDimensions(scaleFunc);
}
/// <summary>
/// Allocate a new fixed sized RTHandle with the default RTHandle System.
/// </summary>
/// <param name="width">With of the RTHandle.</param>
/// <param name="height">height of the RTHandle.</param>
/// <param name="slices">Number of slices of the RTHandle.</param>
/// <param name="depthBufferBits">Bit depths of a depth buffer.</param>
/// <param name="colorFormat">GraphicsFormat of a color buffer.</param>
/// <param name="filterMode">Filtering mode of the RTHandle.</param>
/// <param name="wrapMode">Addressing mode of the RTHandle.</param>
/// <param name="dimension">Texture dimension of the RTHandle.</param>
/// <param name="enableRandomWrite">Set to true to enable UAV random read writes on the texture.</param>
/// <param name="useMipMap">Set to true if the texture should have mipmaps.</param>
/// <param name="autoGenerateMips">Set to true to automatically generate mipmaps.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="msaaSamples">Number of MSAA samples for the RTHandle.</param>
/// <param name="bindTextureMS">Set to true if the texture needs to be bound as a multisampled texture in the shader.</param>
/// <param name="useDynamicScale">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="useDynamicScaleExplicit">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="memoryless">Use this property to set the render texture memoryless modes.</param>
/// <param name="vrUsage">Special treatment of the VR eye texture used in stereoscopic rendering.</param>
/// <param name="name">Name of the RTHandle.</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(
int width,
int height,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
GraphicsFormat colorFormat = GraphicsFormat.R8G8B8A8_SRGB,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
bool useDynamicScaleExplicit = false,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
VRTextureUsage vrUsage = VRTextureUsage.None,
string name = ""
)
{
return s_DefaultInstance.Alloc(
width,
height,
slices,
depthBufferBits,
colorFormat,
filterMode,
wrapMode,
dimension,
enableRandomWrite,
useMipMap,
autoGenerateMips,
isShadowMap,
anisoLevel,
mipMapBias,
msaaSamples,
bindTextureMS,
useDynamicScale,
useDynamicScaleExplicit,
memoryless,
vrUsage,
name
);
}
/// <summary>
/// Allocate a new fixed sized RTHandle with the default RTHandle System.
/// </summary>
/// <param name="width">With of the RTHandle.</param>
/// <param name="height">height of the RTHandle.</param>
/// <param name="format">GraphicsFormat of a color or depth stencil buffer.</param>
/// <param name="slices">Number of slices of the RTHandle.</param>
/// <param name="filterMode">Filtering mode of the RTHandle.</param>
/// <param name="wrapMode">Addressing mode of the RTHandle.</param>
/// <param name="dimension">Texture dimension of the RTHandle.</param>
/// <param name="enableRandomWrite">Set to true to enable UAV random read writes on the texture.</param>
/// <param name="useMipMap">Set to true if the texture should have mipmaps.</param>
/// <param name="autoGenerateMips">Set to true to automatically generate mipmaps.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="msaaSamples">Number of MSAA samples for the RTHandle.</param>
/// <param name="bindTextureMS">Set to true if the texture needs to be bound as a multisampled texture in the shader.</param>
/// <param name="useDynamicScale">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="useDynamicScaleExplicit">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="memoryless">Use this property to set the render texture memoryless modes.</param>
/// <param name="vrUsage">Special treatment of the VR eye texture used in stereoscopic rendering.</param>
/// <param name="name">Name of the RTHandle.</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(
int width,
int height,
GraphicsFormat format,
int slices = 1,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
bool useDynamicScaleExplicit = false,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
VRTextureUsage vrUsage = VRTextureUsage.None,
string name = ""
)
{
return s_DefaultInstance.Alloc(
width,
height,
format,
slices,
filterMode,
wrapMode,
dimension,
enableRandomWrite,
useMipMap,
autoGenerateMips,
isShadowMap,
anisoLevel,
mipMapBias,
msaaSamples,
bindTextureMS,
useDynamicScale,
useDynamicScaleExplicit,
memoryless,
vrUsage,
name
);
}
/// <summary>
/// Allocate a new fixed sized RTHandle with the default RTHandle System.
/// </summary>
/// <param name="width">With of the RTHandle.</param>
/// <param name="height">height of the RTHandle.</param>
/// <param name="wrapModeU">U coordinate wrapping mode of the RTHandle.</param>
/// <param name="wrapModeV">V coordinate wrapping mode of the RTHandle.</param>
/// <param name="wrapModeW">W coordinate wrapping mode of the RTHandle.</param>
/// <param name="slices">Number of slices of the RTHandle.</param>
/// <param name="depthBufferBits">Bit depths of a depth buffer.</param>
/// <param name="colorFormat">GraphicsFormat of a color buffer.</param>
/// <param name="filterMode">Filtering mode of the RTHandle.</param>
/// <param name="dimension">Texture dimension of the RTHandle.</param>
/// <param name="enableRandomWrite">Set to true to enable UAV random read writes on the texture.</param>
/// <param name="useMipMap">Set to true if the texture should have mipmaps.</param>
/// <param name="autoGenerateMips">Set to true to automatically generate mipmaps.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="msaaSamples">Number of MSAA samples for the RTHandle.</param>
/// <param name="bindTextureMS">Set to true if the texture needs to be bound as a multisampled texture in the shader.</param>
/// <param name="useDynamicScale">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="useDynamicScaleExplicit">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="memoryless">Use this property to set the render texture memoryless modes.</param>
/// <param name="vrUsage">Special treatment of the VR eye texture used in stereoscopic rendering.</param>
/// <param name="name">Name of the RTHandle.</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(
int width,
int height,
TextureWrapMode wrapModeU,
TextureWrapMode wrapModeV,
TextureWrapMode wrapModeW = TextureWrapMode.Repeat,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
GraphicsFormat colorFormat = GraphicsFormat.R8G8B8A8_SRGB,
FilterMode filterMode = FilterMode.Point,
TextureDimension dimension = TextureDimension.Tex2D,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
bool useDynamicScaleExplicit = false,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
VRTextureUsage vrUsage = VRTextureUsage.None,
string name = ""
)
{
return s_DefaultInstance.Alloc(
width,
height,
wrapModeU,
wrapModeV,
wrapModeW,
slices,
depthBufferBits,
colorFormat,
filterMode,
dimension,
enableRandomWrite,
useMipMap,
autoGenerateMips,
isShadowMap,
anisoLevel,
mipMapBias,
msaaSamples,
bindTextureMS,
useDynamicScale,
useDynamicScaleExplicit,
memoryless,
vrUsage,
name
);
}
/// <summary>
/// Allocate a new fixed sized RTHandle with the default RTHandle System.
/// </summary>
/// <param name="width">With of the RTHandle.</param>
/// <param name="height">Height of the RTHandle.</param>
/// <param name="info">Struct containing details of allocation</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(int width, int height, RTHandleAllocInfo info)
{
return s_DefaultInstance.Alloc(width, height, info);
}
/// <summary>
/// Allocate a new fixed sized RTHandle with the default RTHandle System.
/// </summary>
/// <param name="descriptor">RenderTexture descriptor of the RTHandle.</param>
/// <param name="filterMode">Filtering mode of the RTHandle.</param>
/// <param name="wrapMode">Addressing mode of the RTHandle.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="name">Name of the RTHandle.</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(
in RenderTextureDescriptor descriptor,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
string name = ""
)
{
return s_DefaultInstance.Alloc(descriptor.width, descriptor.height,
GetRTHandleAllocInfo(descriptor, filterMode, wrapMode, anisoLevel, mipMapBias, name));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static internal GraphicsFormat GetFormat(GraphicsFormat colorFormat, GraphicsFormat depthStencilFormat)
{
return (depthStencilFormat==GraphicsFormat.None) ? colorFormat : depthStencilFormat;
}
// Internal RtDesc to RtAllocInfo conversion utility function.
// Keep internal for future changes.
//
// NOTE: It has no default values to avoid param ambiguity of the flat RtHandleAlloc API.
// NOTE: There isn't 100% field to field mapping, so some fields might need manual adjustment afterwards.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static RTHandleAllocInfo GetRTHandleAllocInfo(in RenderTextureDescriptor desc, FilterMode filterMode, TextureWrapMode wrapMode, int anisoLevel, float mipMapBias, string name)
{
return new RTHandleAllocInfo(name)
{
slices = desc.volumeDepth,
format = RTHandles.GetFormat(desc.graphicsFormat, desc.depthStencilFormat),
filterMode = filterMode,
wrapModeU = wrapMode,
wrapModeV = wrapMode,
wrapModeW = wrapMode,
dimension = desc.dimension,
enableRandomWrite = desc.enableRandomWrite,
useMipMap = desc.useMipMap,
autoGenerateMips = desc.autoGenerateMips,
isShadowMap = desc.shadowSamplingMode != ShadowSamplingMode.None,
anisoLevel = anisoLevel,
mipMapBias = mipMapBias,
msaaSamples = (MSAASamples)desc.msaaSamples,
bindTextureMS = desc.bindMS,
useDynamicScale = desc.useDynamicScale,
useDynamicScaleExplicit = desc.useDynamicScaleExplicit,
memoryless = desc.memoryless,
vrUsage = desc.vrUsage,
enableShadingRate = desc.enableShadingRate,
};
}
/// <summary>
/// Allocate a new automatically sized RTHandle for the default RTHandle System.
/// </summary>
/// <param name="scaleFactor">Constant scale for the RTHandle size computation.</param>
/// <param name="slices">Number of slices of the RTHandle.</param>
/// <param name="depthBufferBits">Bit depths of a depth buffer.</param>
/// <param name="colorFormat">GraphicsFormat of a color buffer.</param>
/// <param name="filterMode">Filtering mode of the RTHandle.</param>
/// <param name="wrapMode">Addressing mode of the RTHandle.</param>
/// <param name="dimension">Texture dimension of the RTHandle.</param>
/// <param name="enableRandomWrite">Set to true to enable UAV random read writes on the texture.</param>
/// <param name="useMipMap">Set to true if the texture should have mipmaps.</param>
/// <param name="autoGenerateMips">Set to true to automatically generate mipmaps.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="msaaSamples">Number of MSAA samples.</param>
/// <param name="bindTextureMS">Set to true if the texture needs to be bound as a multisampled texture in the shader.</param>
/// <param name="useDynamicScale">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="useDynamicScaleExplicit">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="memoryless">Use this property to set the render texture memoryless modes.</param>
/// <param name="vrUsage">Special treatment of the VR eye texture used in stereoscopic rendering.</param>
/// <param name="name">Name of the RTHandle.</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(
Vector2 scaleFactor,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
GraphicsFormat colorFormat = GraphicsFormat.R8G8B8A8_SRGB,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
bool useDynamicScaleExplicit = false,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
VRTextureUsage vrUsage = VRTextureUsage.None,
string name = ""
)
{
return s_DefaultInstance.Alloc(
scaleFactor,
slices,
depthBufferBits,
colorFormat,
filterMode,
wrapMode,
dimension,
enableRandomWrite,
useMipMap,
autoGenerateMips,
isShadowMap,
anisoLevel,
mipMapBias,
msaaSamples,
bindTextureMS,
useDynamicScale,
useDynamicScaleExplicit,
memoryless,
vrUsage,
name
);
}
/// <summary>
/// Allocate a new automatically sized RTHandle for the default RTHandle System.
/// </summary>
/// <param name="scaleFactor">Constant scale for the RTHandle size computation.</param>
/// <param name="format">GraphicsFormat of a color or depth stencil buffer.</param>
/// <param name="slices">Number of slices of the RTHandle.</param>
/// <param name="filterMode">Filtering mode of the RTHandle.</param>
/// <param name="wrapMode">Addressing mode of the RTHandle.</param>
/// <param name="dimension">Texture dimension of the RTHandle.</param>
/// <param name="enableRandomWrite">Set to true to enable UAV random read writes on the texture.</param>
/// <param name="useMipMap">Set to true if the texture should have mipmaps.</param>
/// <param name="autoGenerateMips">Set to true to automatically generate mipmaps.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="msaaSamples">Number of MSAA samples.</param>
/// <param name="bindTextureMS">Set to true if the texture needs to be bound as a multisampled texture in the shader.</param>
/// <param name="useDynamicScale">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="useDynamicScaleExplicit">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="memoryless">Use this property to set the render texture memoryless modes.</param>
/// <param name="vrUsage">Special treatment of the VR eye texture used in stereoscopic rendering.</param>
/// <param name="name">Name of the RTHandle.</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(
Vector2 scaleFactor,
GraphicsFormat format,
int slices = 1,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
bool useDynamicScaleExplicit = false,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
VRTextureUsage vrUsage = VRTextureUsage.None,
string name = ""
)
{
return s_DefaultInstance.Alloc(
scaleFactor,
format,
slices,
filterMode,
wrapMode,
dimension,
enableRandomWrite,
useMipMap,
autoGenerateMips,
isShadowMap,
anisoLevel,
mipMapBias,
msaaSamples,
bindTextureMS,
useDynamicScale,
useDynamicScaleExplicit,
memoryless,
vrUsage,
name
);
}
/// <summary>
/// Allocate a new automatically sized RTHandle for the default RTHandle System.
/// </summary>
/// <param name="scaleFactor">Constant scale for the RTHandle size computation.</param>
/// <param name="descriptor">RenderTexture descriptor of the RTHandle.</param>
/// <param name="filterMode">Filtering mode of the RTHandle.</param>
/// <param name="wrapMode">Addressing mode of the RTHandle.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="name">Name of the RTHandle.</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(
Vector2 scaleFactor,
in RenderTextureDescriptor descriptor,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
string name = ""
)
{
return s_DefaultInstance.Alloc(scaleFactor,
GetRTHandleAllocInfo(descriptor, filterMode, wrapMode, anisoLevel, mipMapBias, name));
}
/// <summary>
/// Allocate a new automatically sized RTHandle for the default RTHandle System.
/// </summary>
/// <param name="scaleFactor">Constant scale for the RTHandle size computation.</param>
/// <param name="info">Struct containing details of allocation</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(Vector2 scaleFactor, RTHandleAllocInfo info)
{
return s_DefaultInstance.Alloc(scaleFactor, info);
}
/// <summary>
/// Allocate a new automatically sized RTHandle for the default RTHandle System.
/// </summary>
/// <param name="scaleFunc">Function used for the RTHandle size computation.</param>
/// <param name="slices">Number of slices of the RTHandle.</param>
/// <param name="depthBufferBits">Bit depths of a depth buffer.</param>
/// <param name="colorFormat">GraphicsFormat of a color buffer.</param>
/// <param name="filterMode">Filtering mode of the RTHandle.</param>
/// <param name="wrapMode">Addressing mode of the RTHandle.</param>
/// <param name="dimension">Texture dimension of the RTHandle.</param>
/// <param name="enableRandomWrite">Set to true to enable UAV random read writes on the texture.</param>
/// <param name="useMipMap">Set to true if the texture should have mipmaps.</param>
/// <param name="autoGenerateMips">Set to true to automatically generate mipmaps.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="msaaSamples">Number of MSAA samples.</param>
/// <param name="bindTextureMS">Set to true if the texture needs to be bound as a multisampled texture in the shader.</param>
/// <param name="useDynamicScale">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="useDynamicScaleExplicit">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="memoryless">Use this property to set the render texture memoryless modes.</param>
/// <param name="vrUsage">Special treatment of the VR eye texture used in stereoscopic rendering.</param>
/// <param name="name">Name of the RTHandle.</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(
ScaleFunc scaleFunc,
int slices = 1,
DepthBits depthBufferBits = DepthBits.None,
GraphicsFormat colorFormat = GraphicsFormat.R8G8B8A8_SRGB,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
bool useDynamicScaleExplicit = false,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
VRTextureUsage vrUsage = VRTextureUsage.None,
string name = ""
)
{
return s_DefaultInstance.Alloc(
scaleFunc,
slices,
depthBufferBits,
colorFormat,
filterMode,
wrapMode,
dimension,
enableRandomWrite,
useMipMap,
autoGenerateMips,
isShadowMap,
anisoLevel,
mipMapBias,
msaaSamples,
bindTextureMS,
useDynamicScale,
useDynamicScaleExplicit,
memoryless,
vrUsage,
name
);
}
/// <summary>
/// Allocate a new automatically sized RTHandle for the default RTHandle System.
/// </summary>
/// <param name="scaleFunc">Function used for the RTHandle size computation.</param>
/// <param name="format">GraphicsFormat of a color or depth stencil buffer.</param>
/// <param name="slices">Number of slices of the RTHandle.</param>
/// <param name="filterMode">Filtering mode of the RTHandle.</param>
/// <param name="wrapMode">Addressing mode of the RTHandle.</param>
/// <param name="dimension">Texture dimension of the RTHandle.</param>
/// <param name="enableRandomWrite">Set to true to enable UAV random read writes on the texture.</param>
/// <param name="useMipMap">Set to true if the texture should have mipmaps.</param>
/// <param name="autoGenerateMips">Set to true to automatically generate mipmaps.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="msaaSamples">Number of MSAA samples.</param>
/// <param name="bindTextureMS">Set to true if the texture needs to be bound as a multisampled texture in the shader.</param>
/// <param name="useDynamicScale">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="useDynamicScaleExplicit">[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</param>
/// <param name="memoryless">Use this property to set the render texture memoryless modes.</param>
/// <param name="vrUsage">Special treatment of the VR eye texture used in stereoscopic rendering.</param>
/// <param name="name">Name of the RTHandle.</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(
ScaleFunc scaleFunc,
GraphicsFormat format,
int slices = 1,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
TextureDimension dimension = TextureDimension.Tex2D,
bool enableRandomWrite = false,
bool useMipMap = false,
bool autoGenerateMips = true,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
MSAASamples msaaSamples = MSAASamples.None,
bool bindTextureMS = false,
bool useDynamicScale = false,
bool useDynamicScaleExplicit = false,
RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
VRTextureUsage vrUsage = VRTextureUsage.None,
string name = ""
)
{
return s_DefaultInstance.Alloc(
scaleFunc,
format,
slices,
filterMode,
wrapMode,
dimension,
enableRandomWrite,
useMipMap,
autoGenerateMips,
isShadowMap,
anisoLevel,
mipMapBias,
msaaSamples,
bindTextureMS,
useDynamicScale,
useDynamicScaleExplicit,
memoryless,
vrUsage,
name
);
}
/// <summary>
/// Allocate a new automatically sized RTHandle for the default RTHandle System.
/// </summary>
/// <param name="scaleFunc">Function used for the RTHandle size computation.</param>
/// <param name="descriptor">RenderTexture descriptor of the RTHandle.</param>
/// <param name="filterMode">Filtering mode of the RTHandle.</param>
/// <param name="wrapMode">Addressing mode of the RTHandle.</param>
/// <param name="isShadowMap">Set to true if the depth buffer should be used as a shadow map.</param>
/// <param name="anisoLevel">Anisotropic filtering level.</param>
/// <param name="mipMapBias">Bias applied to mipmaps during filtering.</param>
/// <param name="name">Name of the RTHandle.</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(
ScaleFunc scaleFunc,
in RenderTextureDescriptor descriptor,
FilterMode filterMode = FilterMode.Point,
TextureWrapMode wrapMode = TextureWrapMode.Repeat,
bool isShadowMap = false,
int anisoLevel = 1,
float mipMapBias = 0,
string name = ""
)
{
Assert.IsFalse(descriptor.graphicsFormat != GraphicsFormat.None && descriptor.depthStencilFormat != GraphicsFormat.None,
"The RenderTextureDescriptor used to create RTHandle " + name + " contains both graphicsFormat and depthStencilFormat which is not allowed.");
return s_DefaultInstance.Alloc(scaleFunc,
GetRTHandleAllocInfo(descriptor, filterMode, wrapMode, anisoLevel, mipMapBias, name));
}
/// <summary>
/// Allocate a new automatically sized RTHandle for the default RTHandle System.
/// </summary>
/// <param name="scaleFunc">Function used for the RTHandle size computation.</param>
/// <param name="info">Struct containing details of allocation</param>
/// <returns>A new RTHandle.</returns>
public static RTHandle Alloc(ScaleFunc scaleFunc, RTHandleAllocInfo info)
{
return s_DefaultInstance.Alloc(scaleFunc, info);
}
/// <summary>
/// Allocate a RTHandle from a regular Texture for the default RTHandle system.
/// </summary>
/// <param name="tex">Input texture</param>
/// <returns>A new RTHandle referencing the input texture.</returns>
public static RTHandle Alloc(Texture tex)
{
return s_DefaultInstance.Alloc(tex);
}
/// <summary>
/// Allocate a RTHandle from a regular RenderTexture for the default RTHandle system.
/// </summary>
/// <param name="tex">Input texture</param>
/// <param name="transferOwnership">To transfer ownership of the RenderTexture to the default RTHandles system, false by default</param>
/// <returns>A new RTHandle referencing the input texture.</returns>
public static RTHandle Alloc(RenderTexture tex, bool transferOwnership = false)
{
return s_DefaultInstance.Alloc(tex, transferOwnership);
}
/// <summary>
/// Allocate a RTHandle from a regular render target identifier for the default RTHandle system.
/// </summary>
/// <param name="tex">Input render target identifier.</param>
/// <returns>A new RTHandle referencing the input render target identifier.</returns>
public static RTHandle Alloc(RenderTargetIdentifier tex)
{
return s_DefaultInstance.Alloc(tex);
}
/// <summary>
/// Allocate a RTHandle from a regular render target identifier for the default RTHandle system.
/// </summary>
/// <param name="tex">Input render target identifier.</param>
/// <param name="name">Name of the render target.</param>
/// <returns>A new RTHandle referencing the input render target identifier.</returns>
public static RTHandle Alloc(RenderTargetIdentifier tex, string name)
{
return s_DefaultInstance.Alloc(tex, name);
}
private static RTHandle Alloc(RTHandle tex)
{
Debug.LogError("Allocation a RTHandle from another one is forbidden.");
return null;
}
/// <summary>
/// Initialize the default RTHandle system.
/// </summary>
/// <param name="width">Initial reference rendering width.</param>
/// <param name="height">Initial reference rendering height.</param>
public static void Initialize(int width, int height)
{
s_DefaultInstance.Initialize(width, height);
}
/// <summary>
/// Initialize the default RTHandle system.
/// </summary>
/// <param name="width">Initial reference rendering width.</param>
/// <param name="height">Initial reference rendering height.</param>
/// <param name="useLegacyDynamicResControl">Use legacy hardware DynamicResolution control in the default RTHandle system.</param>
[Obsolete("useLegacyDynamicResControl is deprecated. Please use SetHardwareDynamicResolutionState() instead. #from(2023.3)")]
public static void Initialize(int width, int height, bool useLegacyDynamicResControl = false)
{
s_DefaultInstance.Initialize(width, height, useLegacyDynamicResControl);
}
/// <summary>
/// Release memory of a RTHandle from the default RTHandle System
/// </summary>
/// <param name="rth">RTHandle that should be released.</param>
public static void Release(RTHandle rth)
{
s_DefaultInstance.Release(rth);
}
/// <summary>
/// Enable or disable hardware dynamic resolution for the default RTHandle System
/// </summary>
/// <param name="hwDynamicResRequested">State of hardware dynamic resolution.</param>
public static void SetHardwareDynamicResolutionState(bool hwDynamicResRequested)
{
s_DefaultInstance.SetHardwareDynamicResolutionState(hwDynamicResRequested);
}
/// <summary>
/// Sets the reference rendering size for subsequent rendering for the default RTHandle System
/// </summary>
/// <param name="width">Reference rendering width for subsequent rendering.</param>
/// <param name="height">Reference rendering height for subsequent rendering.</param>
public static void SetReferenceSize(int width, int height)
{
s_DefaultInstance.SetReferenceSize(width, height);
}
/// <summary>
/// Reset the reference size of the system and reallocate all textures.
/// </summary>
/// <param name="width">New width.</param>
/// <param name="height">New height.</param>
public static void ResetReferenceSize(int width, int height)
{
s_DefaultInstance.ResetReferenceSize(width, height);
}
/// <summary>
/// Returns the ratio against the current target's max resolution
/// </summary>
/// <param name="width">width to utilize</param>
/// <param name="height">height to utilize</param>
/// <returns> retruns the width,height / maxTargetSize.xy ratio. </returns>
public static Vector2 CalculateRatioAgainstMaxSize(int width, int height)
{
return s_DefaultInstance.CalculateRatioAgainstMaxSize(new Vector2Int(width, height));
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4eb3ce06cfe568d41b5658c020b72c8e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 081cfbdef2e1c014aa1d1c9aa16fb952
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,341 @@
using Unity.Scripting.LifecycleManagement;
using UnityEngine.Experimental.Rendering;
namespace UnityEngine.Rendering
{
/// <summary>
/// Utility class providing default textures compatible in any XR setup.
/// </summary>
public static partial class TextureXR
{
[OnCodeInitializing]
static void ResetStaticsOnLoad()
{
Cleanup();
s_MaxViews = 1;
}
// Property set by XRSystem — manually reset alongside textures in Cleanup()
[NoAutoStaticsCleanup]
private static int s_MaxViews = 1;
/// <summary>
/// Maximum number of views handled by the XR system.
/// </summary>
public static int maxViews
{
set
{
s_MaxViews = value;
}
}
// Property accessed when allocating a render target
/// <summary>
/// Number of slices used by the XR system.
/// </summary>
public static int slices { get => s_MaxViews; }
// Must be in sync with shader define in TextureXR.hlsl
/// <summary>
/// Returns true if the XR system uses texture arrays.
/// </summary>
public static bool useTexArray
{
get
{
switch (SystemInfo.graphicsDeviceType)
{
case GraphicsDeviceType.Direct3D11:
case GraphicsDeviceType.Direct3D12:
case GraphicsDeviceType.PlayStation4:
case GraphicsDeviceType.PlayStation5:
case GraphicsDeviceType.PlayStation5NGGC:
case GraphicsDeviceType.Vulkan:
case GraphicsDeviceType.Metal:
case GraphicsDeviceType.OpenGLES3:
case GraphicsDeviceType.OpenGLCore:
return true;
default:
return false;
}
}
}
/// <summary>
/// Dimension of XR textures.
/// </summary>
public static TextureDimension dimension
{
get
{
// TEXTURE2D_X macros will now expand to TEXTURE2D or TEXTURE2D_ARRAY
return useTexArray ? TextureDimension.Tex2DArray : TextureDimension.Tex2D;
}
}
// Need to keep both the Texture and the RTHandle in order to be able to track lifetime properly.
// Manually cleaned up via Cleanup() which calls RTHandles.Release()
[NoAutoStaticsCleanup]
static Texture s_BlackUIntTexture2DArray;
[NoAutoStaticsCleanup]
static Texture s_BlackUIntTexture;
[NoAutoStaticsCleanup]
static RTHandle s_BlackUIntTexture2DArrayRTH;
[NoAutoStaticsCleanup]
static RTHandle s_BlackUIntTextureRTH;
/// <summary>
/// Default black unsigned integer texture.
/// </summary>
/// <returns>The default black unsigned integer texture.</returns>
public static RTHandle GetBlackUIntTexture() { return useTexArray ? s_BlackUIntTexture2DArrayRTH : s_BlackUIntTextureRTH; }
[NoAutoStaticsCleanup]
static Texture2DArray s_ClearTexture2DArray;
[NoAutoStaticsCleanup]
static Texture2D s_ClearTexture;
[NoAutoStaticsCleanup]
static RTHandle s_ClearTexture2DArrayRTH;
[NoAutoStaticsCleanup]
static RTHandle s_ClearTextureRTH;
/// <summary>
/// Default clear color (0, 0, 0, 1) texture.
/// </summary>
/// <returns>The default clear color texture.</returns>
public static RTHandle GetClearTexture() { return useTexArray ? s_ClearTexture2DArrayRTH : s_ClearTextureRTH; }
[NoAutoStaticsCleanup]
static Texture2DArray s_MagentaTexture2DArray;
[NoAutoStaticsCleanup]
static Texture2D s_MagentaTexture;
[NoAutoStaticsCleanup]
static RTHandle s_MagentaTexture2DArrayRTH;
[NoAutoStaticsCleanup]
static RTHandle s_MagentaTextureRTH;
/// <summary>
/// Default magenta texture.
/// </summary>
/// <returns>The default magenta texture.</returns>
public static RTHandle GetMagentaTexture() { return useTexArray ? s_MagentaTexture2DArrayRTH : s_MagentaTextureRTH; }
[NoAutoStaticsCleanup]
static Texture2D s_BlackTexture;
[NoAutoStaticsCleanup]
static Texture3D s_BlackTexture3D;
[NoAutoStaticsCleanup]
static Texture2DArray s_BlackTexture2DArray;
[NoAutoStaticsCleanup]
static RTHandle s_BlackTexture2DArrayRTH;
[NoAutoStaticsCleanup]
static RTHandle s_BlackTextureRTH;
[NoAutoStaticsCleanup]
static RTHandle s_BlackTexture3DRTH;
/// <summary>
/// Default black texture.
/// </summary>
/// <returns>The default black texture.</returns>
public static RTHandle GetBlackTexture() { return useTexArray ? s_BlackTexture2DArrayRTH : s_BlackTextureRTH; }
/// <summary>
/// Default black texture array.
/// </summary>
/// <returns>The default black texture array.</returns>
public static RTHandle GetBlackTextureArray() { return s_BlackTexture2DArrayRTH; }
/// <summary>
/// Default black texture 3D.
/// </summary>
/// <returns>The default black texture 3D.</returns>
public static RTHandle GetBlackTexture3D() { return s_BlackTexture3DRTH; }
[NoAutoStaticsCleanup]
static Texture2DArray s_WhiteTexture2DArray;
[NoAutoStaticsCleanup]
static RTHandle s_WhiteTexture2DArrayRTH;
[NoAutoStaticsCleanup]
static RTHandle s_WhiteTextureRTH;
/// <summary>
/// Default white texture.
/// </summary>
/// <returns>The default white texture.</returns>
public static RTHandle GetWhiteTexture() { return useTexArray ? s_WhiteTexture2DArrayRTH : s_WhiteTextureRTH; }
/// <summary>
/// Is TextureXR initialized?
/// </summary>
public static bool initialized => s_BlackUIntTexture2DArray != null; // We assume that everything is valid if one is valid.
/// <summary>
/// Initialize XR textures. Must be called at least once.
/// </summary>
/// <param name="cmd">Command Buffer used to initialize textures.</param>
/// <param name="clearR32_UIntShader">Compute shader used to intitialize unsigned integer textures.</param>
public static void Initialize(CommandBuffer cmd, ComputeShader clearR32_UIntShader)
{
if (initialized)
return;
// Black UINT
s_BlackUIntTexture2DArray = CreateBlackUIntTextureArray(cmd, clearR32_UIntShader);
s_BlackUIntTexture2DArrayRTH = RTHandles.Alloc(s_BlackUIntTexture2DArray);
s_BlackUIntTexture = CreateBlackUintTexture(cmd, clearR32_UIntShader);
s_BlackUIntTextureRTH = RTHandles.Alloc(s_BlackUIntTexture);
// Clear
s_ClearTexture = new Texture2D(1, 1, GraphicsFormat.R8G8B8A8_SRGB, TextureCreationFlags.None) { name = "Clear Texture" };
s_ClearTexture.SetPixel(0, 0, Color.clear);
s_ClearTexture.Apply();
s_ClearTextureRTH = RTHandles.Alloc(s_ClearTexture);
s_ClearTexture2DArray = CreateTexture2DArrayFromTexture2D(s_ClearTexture, "Clear Texture2DArray");
s_ClearTexture2DArrayRTH = RTHandles.Alloc(s_ClearTexture2DArray);
// Magenta
s_MagentaTexture = new Texture2D(1, 1, GraphicsFormat.R8G8B8A8_SRGB, TextureCreationFlags.None) { name = "Magenta Texture" };
s_MagentaTexture.SetPixel(0, 0, Color.magenta);
s_MagentaTexture.Apply();
s_MagentaTextureRTH = RTHandles.Alloc(s_MagentaTexture);
s_MagentaTexture2DArray = CreateTexture2DArrayFromTexture2D(s_MagentaTexture, "Magenta Texture2DArray");
s_MagentaTexture2DArrayRTH = RTHandles.Alloc(s_MagentaTexture2DArray);
// Black
s_BlackTexture = new Texture2D(1, 1, GraphicsFormat.R8G8B8A8_SRGB, TextureCreationFlags.None) { name = "Black Texture" };
s_BlackTexture.SetPixel(0, 0, Color.black);
s_BlackTexture.Apply();
s_BlackTextureRTH = RTHandles.Alloc(s_BlackTexture);
s_BlackTexture2DArray = CreateTexture2DArrayFromTexture2D(s_BlackTexture, "Black Texture2DArray");
s_BlackTexture2DArrayRTH = RTHandles.Alloc(s_BlackTexture2DArray);
s_BlackTexture3D = CreateBlackTexture3D("Black Texture3D");
s_BlackTexture3DRTH = RTHandles.Alloc(s_BlackTexture3D);
// White
s_WhiteTextureRTH = RTHandles.Alloc(Texture2D.whiteTexture);
s_WhiteTexture2DArray = CreateTexture2DArrayFromTexture2D(Texture2D.whiteTexture, "White Texture2DArray");
s_WhiteTexture2DArrayRTH = RTHandles.Alloc(s_WhiteTexture2DArray);
}
/// <summary>
/// Release XR textures. Must be called at when destroying a RenderPipeline using TextureXR
/// </summary>
public static void Cleanup()
{
if (!initialized)
return;
// Black UINT
RTHandles.Release(s_BlackUIntTexture2DArrayRTH);
s_BlackUIntTexture2DArrayRTH = null;
CoreUtils.Destroy(s_BlackUIntTexture2DArray);
s_BlackUIntTexture2DArray = null;
RTHandles.Release(s_BlackUIntTextureRTH);
s_BlackUIntTextureRTH = null;
CoreUtils.Destroy(s_BlackUIntTexture);
s_BlackUIntTexture = null;
// Clear
RTHandles.Release(s_ClearTextureRTH);
s_ClearTextureRTH = null;
CoreUtils.Destroy(s_ClearTexture);
s_ClearTexture = null;
RTHandles.Release(s_ClearTexture2DArrayRTH);
s_ClearTexture2DArrayRTH = null;
CoreUtils.Destroy(s_ClearTexture2DArray);
s_ClearTexture2DArray = null;
// Magenta
RTHandles.Release(s_MagentaTextureRTH);
s_MagentaTextureRTH = null;
CoreUtils.Destroy(s_MagentaTexture);
s_MagentaTexture = null;
RTHandles.Release(s_MagentaTexture2DArrayRTH);
s_MagentaTexture2DArrayRTH = null;
CoreUtils.Destroy(s_MagentaTexture2DArray);
s_MagentaTexture2DArray = null;
// Black
RTHandles.Release(s_BlackTextureRTH);
s_BlackTextureRTH = null;
CoreUtils.Destroy(s_BlackTexture);
s_BlackTexture = null;
RTHandles.Release(s_BlackTexture2DArrayRTH);
s_BlackTexture2DArrayRTH = null;
CoreUtils.Destroy(s_BlackTexture2DArray);
s_BlackTexture2DArray = null;
RTHandles.Release(s_BlackTexture3DRTH);
s_BlackTexture3DRTH = null;
CoreUtils.Destroy(s_BlackTexture3D);
s_BlackTexture3D = null;
// White
RTHandles.Release(s_WhiteTextureRTH);
s_WhiteTextureRTH = null;
RTHandles.Release(s_WhiteTexture2DArrayRTH);
s_WhiteTexture2DArrayRTH = null;
CoreUtils.Destroy(s_WhiteTexture2DArray);
s_WhiteTexture2DArray = null;
}
static Texture2DArray CreateTexture2DArrayFromTexture2D(Texture2D source, string name)
{
Texture2DArray texArray = new Texture2DArray(source.width, source.height, slices, source.format, false) { name = name };
for (int i = 0; i < slices; ++i)
Graphics.CopyTexture(source, 0, 0, texArray, i, 0);
return texArray;
}
static Texture CreateBlackUIntTextureArray(CommandBuffer cmd, ComputeShader clearR32_UIntShader)
{
RenderTexture blackUIntTexture2DArray = new RenderTexture(1, 1, 0, GraphicsFormat.R32_UInt)
{
dimension = TextureDimension.Tex2DArray,
volumeDepth = slices,
useMipMap = false,
autoGenerateMips = false,
enableRandomWrite = true,
name = "Black UInt Texture Array"
};
blackUIntTexture2DArray.Create();
// Workaround because we currently can't create a Texture2DArray using an R32_UInt format
// So we create a R32_UInt RenderTarget and clear it using a compute shader, because we can't
// Clear this type of target on metal devices (output type nor compatible: float4 vs uint)
int kernel = clearR32_UIntShader.FindKernel("ClearUIntTextureArray");
cmd.SetComputeTextureParam(clearR32_UIntShader, kernel, "_TargetArray", blackUIntTexture2DArray);
cmd.DispatchCompute(clearR32_UIntShader, kernel, 1, 1, slices);
return blackUIntTexture2DArray as Texture;
}
static Texture CreateBlackUintTexture(CommandBuffer cmd, ComputeShader clearR32_UIntShader)
{
RenderTexture blackUIntTexture2D = new RenderTexture(1, 1, 0, GraphicsFormat.R32_UInt)
{
dimension = TextureDimension.Tex2D,
volumeDepth = 1,
useMipMap = false,
autoGenerateMips = false,
enableRandomWrite = true,
name = "Black UInt Texture"
};
blackUIntTexture2D.Create();
// Workaround because we currently can't create a Texture2D using an R32_UInt format
// So we create a R32_UInt RenderTarget and clear it using a compute shader, because we can't
// Clear this type of target on metal devices (output type nor compatible: float4 vs uint)
int kernel = clearR32_UIntShader.FindKernel("ClearUIntTexture");
cmd.SetComputeTextureParam(clearR32_UIntShader, kernel, "_Target", blackUIntTexture2D);
cmd.DispatchCompute(clearR32_UIntShader, kernel, 1, 1, 1);
return blackUIntTexture2D as Texture;
}
static Texture3D CreateBlackTexture3D(string name)
{
Texture3D texture3D = new Texture3D(width: 1, height: 1, depth: 1, GraphicsFormat.R8G8B8A8_SRGB, TextureCreationFlags.None);
texture3D.name = name;
texture3D.SetPixel(0, 0, 0, Color.black, 0);
texture3D.Apply(updateMipmaps: false);
return texture3D;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 350bf58f26d861246982bc0e3ad67632
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: