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,47 @@
using NUnit.Framework;
namespace UnityEngine.Rendering.Universal.Tests
{
class DecalTests
{
GameObject m_DecalProjector;
GameObject m_DecalProjector2;
DecalEntityManager m_EntityManager;
Shader m_Shader;
[SetUp]
public void Setup()
{
m_EntityManager = new DecalEntityManager();
m_DecalProjector = new GameObject("DecalProjector");
m_DecalProjector2 = new GameObject("DecalProjector");
m_Shader = Shader.Find("Hidden/InternalErrorShader");
}
[TearDown]
public void Cleanup()
{
m_EntityManager.Dispose();
Object.DestroyImmediate(m_DecalProjector);
Object.DestroyImmediate(m_DecalProjector2);
}
[Test]
public void DecalDestroyEmptyChunk()
{
var decalProjector = m_DecalProjector.AddComponent<DecalProjector>();
decalProjector.material = new Material(m_Shader);
var decalProjector2 = m_DecalProjector.AddComponent<DecalProjector>();
decalProjector2.material = new Material(m_Shader);
var entity = m_EntityManager.CreateDecalEntity(decalProjector);
var entity2 = m_EntityManager.CreateDecalEntity(decalProjector2);
m_EntityManager.DestroyDecalEntity(entity);
m_EntityManager.Update();
Assert.AreEqual(1, m_EntityManager.chunkCount);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e8d6afcb728d4974abc7ecfec3d77a6d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,180 @@
using System.Collections;
using NUnit.Framework;
using UnityEngine.Rendering.Universal;
using UnityEngine.TestTools;
namespace UnityEngine.Rendering.Universal.Tests
{
[TestFixture]
class MultipleObjectLight2DTests
{
GameObject m_TestObject1;
GameObject m_TestObject2;
GameObject m_TestObject3;
GameObject m_TestObject4;
GameObject m_TestObjectCached;
// Some residual Game Objects from previous test scenes can be left over,
// We destroy everything so they don't interfere with these tests
[OneTimeSetUp]
public void OneTimeSetup()
{
var allGameObjectsInScene = Object.FindObjectsByType<GameObject>();
foreach (var go in allGameObjectsInScene)
{
Object.DestroyImmediate(go);
}
}
[SetUp]
public void Setup()
{
m_TestObject1 = new GameObject("Test Object 1");
m_TestObject2 = new GameObject("Test Object 2");
m_TestObject3 = new GameObject("Test Object 3");
m_TestObject4 = new GameObject("Test Object 4");
m_TestObjectCached = new GameObject("Test Object Cached");
}
[TearDown]
public void Cleanup()
{
Object.DestroyImmediate(m_TestObjectCached);
Object.DestroyImmediate(m_TestObject4);
Object.DestroyImmediate(m_TestObject3);
Object.DestroyImmediate(m_TestObject2);
Object.DestroyImmediate(m_TestObject1);
}
[Test]
public void LightsAreSortedByLightOrder()
{
var light1 = m_TestObject1.AddComponent<Light2D>();
var light2 = m_TestObject2.AddComponent<Light2D>();
var light3 = m_TestObject3.AddComponent<Light2D>();
light1.lightOrder = 1;
light2.lightOrder = 2;
light3.lightOrder = 0;
var camera = m_TestObject4.AddComponent<Camera>();
var cameraPos = camera.transform.position;
light1.transform.position = cameraPos;
light2.transform.position = cameraPos;
light3.transform.position = cameraPos;
light1.UpdateMesh(true);
light1.UpdateBoundingSphere();
light2.UpdateMesh(true);
light2.UpdateBoundingSphere();
light3.UpdateMesh(true);
light3.UpdateBoundingSphere();
var cullResult = new Light2DCullResult();
var cullingParams = new ScriptableCullingParameters();
camera.TryGetCullingParameters(out cullingParams);
cullResult.SetupCulling(ref cullingParams, camera);
Assert.AreSame(light3, cullResult.visibleLights[0]);
Assert.AreSame(light1, cullResult.visibleLights[1]);
Assert.AreSame(light2, cullResult.visibleLights[2]);
}
[Test]
public void LightIsInVisibleListIfInCameraView()
{
var camera = m_TestObject1.AddComponent<Camera>();
var light = m_TestObject2.AddComponent<Light2D>();
light.transform.position = camera.transform.position;
light.UpdateMesh(true);
light.UpdateBoundingSphere();
var cullResult = new Light2DCullResult();
var cullingParams = new ScriptableCullingParameters();
camera.TryGetCullingParameters(out cullingParams);
cullResult.SetupCulling(ref cullingParams, camera);
Assert.Contains(light, cullResult.visibleLights);
}
[Test]
public void LightIsNotInVisibleListIfNotInCameraView()
{
var camera = m_TestObject1.AddComponent<Camera>();
var light = m_TestObject2.AddComponent<Light2D>();
light.transform.position = camera.transform.position + new Vector3(9999.0f, 0.0f, 0.0f);
light.UpdateMesh(true);
light.UpdateBoundingSphere();
var cullResult = new Light2DCullResult();
var cullingParams = new ScriptableCullingParameters();
camera.TryGetCullingParameters(out cullingParams);
cullResult.SetupCulling(ref cullingParams, camera);
Assert.IsFalse(cullResult.visibleLights.Contains(light));
}
[Test]
public void CachedMeshDataIsUpdatedOnChange()
{
var shapePath = new Vector3[4] { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 1, 0), new Vector3(0, 1, 0) };
var light = m_TestObjectCached.AddComponent<Light2D>();
light.lightType = Light2D.LightType.Freeform;
light.SetShapePath(shapePath);
light.UpdateMesh(true);
Assert.AreEqual(true, light.hasCachedMesh);
}
[Test]
public void CachedMeshDataIsOverriddenByRuntimeChanges()
{
var shapePath = new Vector3[4] { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 1, 0), new Vector3(0, 1, 0) };
var light = m_TestObjectCached.AddComponent<Light2D>();
light.lightType = Light2D.LightType.Freeform;
light.SetShapePath(shapePath);
light.UpdateMesh(true);
int vertexCount = 0, triangleCount = 0;
// Check if Cached Data and the actual data are the same.
Assert.AreEqual(true, light.hasCachedMesh);
vertexCount = light.lightMesh.triangles.Length;
triangleCount = light.lightMesh.vertices.Length;
// Simulate Runtime Behavior.
var shapePathChanged = new Vector3[5] { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(1, 1, 0), new Vector3(0.5f, 1.5f, 0), new Vector3(0, 1, 0) };
light.SetShapePath(shapePathChanged);
light.UpdateMesh(true);
// Check if Cached Data and the actual data are no longer the same. (We don't save cache on Runtime)
Assert.AreNotEqual(vertexCount, light.lightMesh.triangles.Length);
Assert.AreNotEqual(triangleCount, light.lightMesh.vertices.Length);
}
// UUM-154810: a Freeform light created from script, with no SetShapePath call,
// must start with the default square instead of a null path.
[Test]
public void FreeformLightCreatedFromScriptHasDefaultShape()
{
var light = m_TestObjectCached.AddComponent<Light2D>();
light.lightType = Light2D.LightType.Freeform;
Assert.DoesNotThrow(() => light.UpdateMesh(true));
Assert.AreEqual(new[] { new Vector3(-0.5f, -0.5f), new Vector3(0.5f, -0.5f), new Vector3(0.5f, 0.5f), new Vector3(-0.5f, 0.5f) }, light.shapePath);
Assert.Greater(light.lightMesh.vertexCount, 0);
}
[Test]
public void EnsureShapeMeshGenerationDoesNotOverflowAllocation()
{
var shapePath = new Vector3[4] { new Vector3(-76.04548f, 7.522535f, 0f), new Vector3(-66.52518f, 18.88778f, 0f), new Vector3(-66.35441f, 24.34475f, 0), new Vector3(-75.15407f, 33.0358f, 0) };
var light = m_TestObjectCached.AddComponent<Light2D>();
light.lightType = Light2D.LightType.Freeform;
LightUtility.GenerateShapeMesh(light, shapePath, 180.0f, 0);
Assert.AreEqual(true, light.hasCachedMesh);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 27afde9fbf110b740bc75164f58d4f21
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a545bf4d761e01b42818d52899606ced
@@ -0,0 +1,37 @@
using NUnit.Framework;
namespace UnityEngine.Rendering.Universal.Tests
{
[TestFixture]
class LightTests
{
[Test]
public void TestMainLightRenderingLayerMaskSyncWithUniversalLightAndShadowLayers()
{
var lightObject = new GameObject("Light");
var light = lightObject.AddComponent<Light>();
var lightData = light.GetUniversalAdditionalLightData();
lightData.renderingLayers = (1 << 1);
lightData.shadowRenderingLayers = (1 << 2);
lightData.customShadowLayers = false;
Assert.AreEqual(light.renderingLayerMask, (int)lightData.renderingLayers);
lightData.customShadowLayers = true;
Assert.AreEqual(light.renderingLayerMask, (int)lightData.shadowRenderingLayers);
lightData.customShadowLayers = false;
lightData.renderingLayers = (1 << 3);
lightData.shadowRenderingLayers = (1 << 4);
Assert.AreEqual(light.renderingLayerMask, (int)lightData.renderingLayers);
lightData.customShadowLayers = true;
lightData.renderingLayers = (1 << 5);
lightData.shadowRenderingLayers = (1 << 6);
Assert.AreEqual(light.renderingLayerMask, (int)lightData.shadowRenderingLayers);
Object.DestroyImmediate(lightObject);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3db6f9b04a31ea949aa7369a94fbbb8e
@@ -0,0 +1,326 @@
using NUnit.Framework;
using UnityEngine.Rendering.Universal;
namespace UnityEngine.Rendering.Universal.Tests
{
internal class PixelPerfectCameraTests
{
internal class PixelPerfectCameraTestComponent : IPixelPerfectCamera
{
public int assetsPPU { get; set; }
public int refResolutionX { get; set; }
public int refResolutionY { get; set; }
public bool upscaleRT { get; set; }
public bool pixelSnapping { get; set; }
public bool cropFrameX { get; set; }
public bool cropFrameY { get; set; }
public bool stretchFill { get; set; }
}
internal class CalculateCameraPropertiesResult
{
public int zoom;
public bool useOffscreenRT;
public int offscreenRTWidth;
public int offscreenRTHeight;
public Rect pixelRect;
public float orthoSize;
public float unitsPerPixel;
}
[UnityEngine.Scripting.Preserve]
private static object[] GetCalculateCameraPropertiesTestCases()
{
object[] testCaseArray = new object[9];
for (int i = 0; i < testCaseArray.Length; ++i)
{
PixelPerfectCameraTestComponent testComponent = new PixelPerfectCameraTestComponent();
int screenWidth = 0;
int screenHeight = 0;
CalculateCameraPropertiesResult expected = new CalculateCameraPropertiesResult();
switch (i)
{
case 0:
testComponent.assetsPPU = 100;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
testComponent.upscaleRT = false;
testComponent.pixelSnapping = true;
testComponent.cropFrameX = true;
testComponent.cropFrameY = true;
testComponent.stretchFill = true;
screenWidth = 800;
screenHeight = 500;
expected.zoom = 1;
expected.useOffscreenRT = true;
expected.offscreenRTWidth = 400;
expected.offscreenRTHeight = 300;
expected.pixelRect = new Rect(0.0f, 0.0f, 400, 300);
expected.orthoSize = 1.5f;
expected.unitsPerPixel = 0.01f;
break;
case 1:
testComponent.assetsPPU = 100;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
testComponent.upscaleRT = true;
testComponent.pixelSnapping = true;
testComponent.cropFrameX = true;
testComponent.cropFrameY = true;
testComponent.stretchFill = true;
screenWidth = 1100;
screenHeight = 900;
expected.zoom = 2;
expected.useOffscreenRT = true;
expected.offscreenRTWidth = 400;
expected.offscreenRTHeight = 300;
expected.pixelRect = new Rect(0.0f, 0.0f, 400, 300);
expected.orthoSize = 1.5f;
expected.unitsPerPixel = 0.01f;
break;
case 2:
testComponent.assetsPPU = 100;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
testComponent.upscaleRT = true;
testComponent.pixelSnapping = true;
testComponent.cropFrameX = false;
testComponent.cropFrameY = true;
testComponent.stretchFill = false;
screenWidth = 400;
screenHeight = 250;
expected.zoom = 1;
expected.useOffscreenRT = true;
expected.offscreenRTWidth = 400;
expected.offscreenRTHeight = 300;
expected.pixelRect = new Rect(0.0f, 0.0f, 400, 300);
expected.orthoSize = 1.5f;
expected.unitsPerPixel = 0.01f;
break;
case 3:
testComponent.assetsPPU = 100;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
testComponent.upscaleRT = true;
testComponent.pixelSnapping = true;
testComponent.cropFrameX = true;
testComponent.cropFrameY = false;
testComponent.stretchFill = false;
screenWidth = 1600;
screenHeight = 1200;
expected.zoom = 4;
expected.useOffscreenRT = true;
expected.offscreenRTWidth = 400;
expected.offscreenRTHeight = 300;
expected.pixelRect = new Rect(0.0f, 0.0f, 400, 300);
expected.orthoSize = 1.5f;
expected.unitsPerPixel = 0.01f;
break;
case 4:
testComponent.assetsPPU = 100;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
testComponent.upscaleRT = true;
testComponent.pixelSnapping = true;
testComponent.cropFrameX = false;
testComponent.cropFrameY = false;
testComponent.stretchFill = false;
screenWidth = 1600;
screenHeight = 1100;
expected.zoom = 3;
expected.useOffscreenRT = true;
expected.offscreenRTWidth = 532;
expected.offscreenRTHeight = 366;
expected.pixelRect = new Rect(0.0f, 0.0f, 532, 366);
expected.orthoSize = 1.83f;
expected.unitsPerPixel = 0.01f;
break;
case 5:
testComponent.assetsPPU = 100;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
testComponent.upscaleRT = false;
testComponent.pixelSnapping = false;
testComponent.cropFrameX = false;
testComponent.cropFrameY = false;
testComponent.stretchFill = true;
screenWidth = 800;
screenHeight = 600;
expected.zoom = 2;
expected.useOffscreenRT = false;
expected.offscreenRTWidth = 0;
expected.offscreenRTHeight = 0;
expected.pixelRect = Rect.zero;
expected.orthoSize = 1.5f;
expected.unitsPerPixel = 0.005f;
break;
case 6:
testComponent.assetsPPU = 100;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
testComponent.upscaleRT = false;
testComponent.pixelSnapping = false;
testComponent.cropFrameX = true;
testComponent.cropFrameY = true;
testComponent.stretchFill = false;
screenWidth = 800;
screenHeight = 700;
expected.zoom = 2;
expected.useOffscreenRT = true;
expected.offscreenRTWidth = 800;
expected.offscreenRTHeight = 600;
expected.pixelRect = new Rect(0.0f, 0.0f, 800, 600);
expected.orthoSize = 1.5f;
expected.unitsPerPixel = 0.005f;
break;
case 7:
testComponent.assetsPPU = 100;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
testComponent.upscaleRT = false;
testComponent.pixelSnapping = true;
testComponent.cropFrameX = false;
testComponent.cropFrameY = true;
testComponent.stretchFill = false;
screenWidth = 900;
screenHeight = 600;
expected.zoom = 2;
expected.useOffscreenRT = true;
expected.offscreenRTWidth = 900;
expected.offscreenRTHeight = 600;
expected.pixelRect = new Rect(0.0f, 0.0f, 900, 600);
expected.orthoSize = 1.5f;
expected.unitsPerPixel = 0.01f;
break;
case 8:
testComponent.assetsPPU = 100;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
testComponent.upscaleRT = false;
testComponent.pixelSnapping = true;
testComponent.cropFrameX = true;
testComponent.cropFrameY = false;
testComponent.stretchFill = false;
screenWidth = 900;
screenHeight = 600;
expected.zoom = 2;
expected.useOffscreenRT = true;
expected.offscreenRTWidth = 800;
expected.offscreenRTHeight = 600;
expected.pixelRect = new Rect(0.0f, 0.0f, 800, 600);
expected.orthoSize = 1.5f;
expected.unitsPerPixel = 0.01f;
break;
}
testCaseArray[i] = new object[] { testComponent, screenWidth, screenHeight, expected };
}
return testCaseArray;
}
[Test, TestCaseSource("GetCalculateCameraPropertiesTestCases")]
public void CalculateCameraPropertiesProvidesCorrectResultsWithVariousInputs(PixelPerfectCameraTestComponent testComponent, int screenWidth, int screenHeight, CalculateCameraPropertiesResult expected)
{
PixelPerfectCameraInternal internals = new PixelPerfectCameraInternal(testComponent);
internals.CalculateCameraProperties(screenWidth, screenHeight);
Assert.AreEqual(expected.zoom, internals.zoom);
Assert.AreEqual(expected.useOffscreenRT, internals.useOffscreenRT);
Assert.AreEqual(expected.offscreenRTWidth, internals.offscreenRTWidth);
Assert.AreEqual(expected.offscreenRTHeight, internals.offscreenRTHeight);
Assert.AreEqual(expected.pixelRect, internals.pixelRect);
Assert.AreEqual(expected.orthoSize, internals.orthoSize);
Assert.AreEqual(expected.unitsPerPixel, internals.unitsPerPixel);
}
[Test]
public void CalculateFinalBlitPixelRectStretchToFitHeightWorks()
{
PixelPerfectCameraTestComponent testComponent = new PixelPerfectCameraTestComponent();
testComponent.refResolutionX = 200;
testComponent.refResolutionY = 100;
PixelPerfectCameraInternal internals = new PixelPerfectCameraInternal(testComponent);
internals.useStretchFill = true;
Rect pixelRect = internals.CalculateFinalBlitPixelRect(400, 100);
Rect expected = new Rect(100.0f, 0.0f, 200.0f, 100.0f);
Assert.AreEqual(expected, pixelRect);
}
[Test]
public void CalculateFinalBlitPixelRectStretchToFitWidthWorks()
{
PixelPerfectCameraTestComponent testComponent = new PixelPerfectCameraTestComponent();
testComponent.refResolutionX = 200;
testComponent.refResolutionY = 100;
PixelPerfectCameraInternal internals = new PixelPerfectCameraInternal(testComponent);
internals.useStretchFill = true;
Rect pixelRect = internals.CalculateFinalBlitPixelRect(200, 200);
Rect expected = new Rect(0.0f, 50.0f, 200.0f, 100.0f);
Assert.AreEqual(expected, pixelRect);
}
[Test]
public void CalculateFinalBlitPixelRectCenteredWorksWithUpscaleRT()
{
PixelPerfectCameraTestComponent testComponent = new PixelPerfectCameraTestComponent();
testComponent.upscaleRT = true;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
PixelPerfectCameraInternal internals = new PixelPerfectCameraInternal(testComponent);
internals.useStretchFill = false;
internals.zoom = 2;
internals.offscreenRTWidth = 400;
internals.offscreenRTHeight = 300;
Rect pixelRect = internals.CalculateFinalBlitPixelRect(1600, 1200);
Rect expected = new Rect(400.0f, 300.0f, 800.0f, 600.0f);
Assert.AreEqual(expected, pixelRect);
}
[Test]
public void CalculateFinalBlitPixelRectCenteredWorksWithoutUpscaleRT()
{
PixelPerfectCameraTestComponent testComponent = new PixelPerfectCameraTestComponent();
testComponent.upscaleRT = false;
testComponent.refResolutionX = 400;
testComponent.refResolutionY = 300;
PixelPerfectCameraInternal internals = new PixelPerfectCameraInternal(testComponent);
internals.useStretchFill = false;
internals.zoom = 2;
internals.offscreenRTWidth = 400;
internals.offscreenRTHeight = 300;
Rect pixelRect = internals.CalculateFinalBlitPixelRect(1600, 1200);
Rect expected = new Rect(600.0f, 450.0f, 400.0f, 300.0f);
Assert.AreEqual(expected, pixelRect);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: df6ed9946a0fc5142a177c1a33ba7c2d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,584 @@
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
using UnityEngine.TestTools;
namespace UnityEngine.Rendering.Universal.Tests
{
// Verifies the real back buffer MSAA optimization end to end: URP requests a single-sampled back
// buffer for frames where no camera renders MSAA directly into it, and keeps it multisampled
// otherwise. Each scenario asserts:
// - the *requested* count (Screen.msaaSamples) settles to the expected value, both per frame and at
// the instant each camera renders (so a one-frame apply lag is caught),
// - the *current* back buffer count (Screen.currentBackbufferMSAASamples) - the actual applied count -
// agrees with the request at the instant each camera renders, and
// - that each on-screen camera actually rendered the way the scenario intends - directly to the back
// buffer, or through an intermediate - via UniversalResourceData.isActiveTargetBackBuffer probed
// after opaques. This makes the tests robust: a camera that is silently forced through an
// intermediate (e.g. by some default setting) is caught instead of masquerading as "direct".
//
// "Uses an intermediate" is forced directly by a ScriptableRenderPass with
// requiresIntermediateTexture = true (injected per camera via beginCameraRendering), so the tests are
// decoupled from how any specific URP feature happens to trigger an intermediate.
//
// The fixture is skipped where MSAA must be resolved explicitly (editor, desktop, Intel/AMD Mac): the
// request is always 1 there with nothing to discriminate. The meaningful coverage runs on the
// device/player jobs (Android/iOS/Metal) via the Foundation/PostPro testables.
[TestFixture]
class RealBackbufferMSAATests
{
const int k_AssetMsaaSampleCount = 4;
// Downgrade hysteresis + one-frame apply lag + margin for frame-pacing jitter.
const int k_SettleFrames = UniversalRenderPipeline.realBackbufferMSAADowngradeDelayFrames + 1 + 3;
const int k_StabilityFrames = 8;
// Upgrades skip the hysteresis, so they must apply promptly: 1 frame to set the request + 1 frame for
// the backend to reallocate. Strict bound to catch a regression that delays re-enabling back buffer
// MSAA when a camera needs it.
const int k_UpgradeFrames = 3;
RenderPipelineAsset m_PreviousQualityRenderPipelineAsset;
int m_PreviousMsaaSamples;
UniversalRenderPipelineAsset m_Asset;
UniversalRendererData m_RendererData;
readonly List<Camera> m_DisabledCameras = new();
readonly List<Object> m_TestObjects = new();
readonly HashSet<Camera> m_ProbeCameras = new(); // on-screen cameras whose target we verify
readonly HashSet<Camera> m_IntermediateCameras = new(); // cameras expected to use an intermediate
readonly ForceIntermediatePass m_ForceIntermediatePass = new();
readonly ActiveTargetProbePass m_ProbePass = new();
// Per-frame applied back buffer MSAA, dumped in the failure diagnostics so a transition or
// reallocation lag is visible frame by frame, not just at the settled state.
readonly List<int> m_CurrentBackbufferMsaaPerFrame = new();
[OneTimeSetUp]
public void OneTimeSetUp()
{
// Capture the global state we may mutate BEFORE any early-out. NUnit runs OneTimeTearDown even
// when OneTimeSetUp calls Assert.Ignore, so these must already hold the real previous values -
// otherwise teardown restores defaults (null pipeline / 0 samples) and clobbers the active URP
// asset for the rest of the test session (silently dropping sibling graphics tests to BiRP).
m_PreviousQualityRenderPipelineAsset = QualitySettings.renderPipeline;
m_PreviousMsaaSamples = Screen.msaaSamples;
if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset)
IgnoreWithLog("These tests only run when URP is the active render pipeline.");
// No multisampled back buffer where MSAA is resolved explicitly (editor, desktop, Intel/AMD Mac),
// so the request is always 1 and there is nothing to discriminate. Real coverage runs on the
// device/player jobs (see fixture header).
if (UniversalRenderer.PlatformRequiresExplicitMsaaResolve())
IgnoreWithLog("Platform resolves MSAA explicitly (no multisampled back buffer); the real back buffer MSAA request is always 1, so there is nothing to test here.");
// Under XR, URP renders into the XR-owned back buffer and never multisamples it directly, so the
// optimization is inactive. A global gate (rather than URP's per-camera xr.enabled check) is enough
// to skip the device XR and mock-XR jobs, where the fixture is meaningless.
if (XRSystem.displayActive || XRGraphicsAutomatedTests.enabled)
IgnoreWithLog("XR is active; URP renders into the XR-owned back buffer and never multisamples it directly, so there is nothing to test here.");
// Frame isolation: only cameras a test creates should contribute to the per-frame back
// buffer MSAA aggregation, so disable any cameras already present in the scene.
foreach (var cam in Object.FindObjectsByType<Camera>(FindObjectsInactive.Exclude))
{
if (!cam.enabled)
continue;
cam.enabled = false;
m_DisabledCameras.Add(cam);
}
m_Asset = CreateAsset();
m_RendererData = (UniversalRendererData)m_Asset.rendererDataList[0];
QualitySettings.renderPipeline = m_Asset;
RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
QualitySettings.renderPipeline = m_PreviousQualityRenderPipelineAsset;
// Don't leak the changed back buffer MSAA request into sibling fixtures in the same run.
if (Screen.msaaSamples != m_PreviousMsaaSamples)
Screen.SetMSAASamples(m_PreviousMsaaSamples);
foreach (var cam in m_DisabledCameras)
{
if (cam != null)
cam.enabled = true;
}
m_DisabledCameras.Clear();
if (m_RendererData != null)
Object.DestroyImmediate(m_RendererData);
if (m_Asset != null)
Object.DestroyImmediate(m_Asset);
}
[SetUp]
public void SetUp()
{
m_Asset.msaaSampleCount = k_AssetMsaaSampleCount;
}
[TearDown]
public void TearDown()
{
if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed)
LogFailureDiagnostics();
// Detach render textures from cameras before releasing them (releasing an RT still set as
// Camera.targetTexture logs an error that would fail the test).
foreach (var obj in m_TestObjects)
{
if (obj is GameObject go && go != null && go.TryGetComponent<Camera>(out var cam))
cam.targetTexture = null;
}
foreach (var obj in m_TestObjects)
{
if (obj != null)
Object.DestroyImmediate(obj);
}
m_TestObjects.Clear();
m_ProbeCameras.Clear();
m_IntermediateCameras.Clear();
m_ProbePass.observedActiveTargetIsBackbuffer.Clear();
m_ProbePass.observedCurrentBackbufferMsaa.Clear();
m_ProbePass.observedRequestedMsaa.Clear();
m_CurrentBackbufferMsaaPerFrame.Clear();
}
// Injects the per-camera passes: the active-target probe on every on-screen camera we verify, and
// the force-intermediate pass on cameras the test marks as "uses an intermediate". Done via
// beginCameraRendering + EnqueuePass so it doesn't depend on any URP feature.
void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
{
if (!camera.TryGetComponent<UniversalAdditionalCameraData>(out var data))
return;
if (m_IntermediateCameras.Contains(camera))
data.scriptableRenderer.EnqueuePass(m_ForceIntermediatePass);
if (m_ProbeCameras.Contains(camera))
data.scriptableRenderer.EnqueuePass(m_ProbePass);
}
// ---- Scenarios ----------------------------------------------------------------------------
[UnityTest]
public IEnumerator SingleCamera_DirectToBackbuffer_KeepsMSAA()
{
CreateScreenCamera(intermediate: false);
yield return SettleAndAssert(needsRealBackbufferMSAA: true);
}
[UnityTest]
public IEnumerator SingleCamera_DirectButCameraMSAADisabled_DisablesMSAA()
{
// Even when rendering directly to the back buffer, a camera with allowMSAA == false doesn't need
// it multisampled - one of the per-camera checks the previous optimization lacked.
var camera = CreateScreenCamera(intermediate: false);
camera.allowMSAA = false;
yield return SettleAndAssert(needsRealBackbufferMSAA: false);
}
[UnityTest]
public IEnumerator SingleCamera_Intermediate_DisablesMSAA()
{
CreateScreenCamera(intermediate: true);
yield return SettleAndAssert(needsRealBackbufferMSAA: false);
}
[UnityTest]
public IEnumerator MultipleCameras_AllDirect_KeepsMSAA()
{
CreateScreenCamera(intermediate: false);
CreateScreenCamera(intermediate: false);
yield return SettleAndAssert(needsRealBackbufferMSAA: true);
}
[UnityTest]
public IEnumerator MultipleCameras_AllIntermediate_DisablesMSAA()
{
CreateScreenCamera(intermediate: true);
CreateScreenCamera(intermediate: true);
yield return SettleAndAssert(needsRealBackbufferMSAA: false);
}
[UnityTest]
public IEnumerator MultipleCameras_MixedDirectAndIntermediate_KeepsMSAA()
{
CreateScreenCamera(intermediate: true); // resolves through an intermediate
CreateScreenCamera(intermediate: false); // renders direct -> vetoes, keeps MSAA on
yield return SettleAndAssert(needsRealBackbufferMSAA: true);
}
[UnityTest]
public IEnumerator CameraStack_BaseUsesIntermediate_DisablesMSAA()
{
// A base camera with a stack always composites through an intermediate, so the back buffer
// only receives the resolved single-sampled result. Mark the base as intermediate so the
// active-target probe expects (and confirms) the intermediate.
var baseCamera = CreateScreenCamera(intermediate: true);
var baseData = baseCamera.GetComponent<UniversalAdditionalCameraData>();
var overlayGo = new GameObject("MSAA Test Overlay Camera");
m_TestObjects.Add(overlayGo);
var overlayCamera = overlayGo.AddComponent<Camera>();
var overlayData = overlayGo.AddComponent<UniversalAdditionalCameraData>();
overlayData.renderType = CameraRenderType.Overlay;
overlayData.SetRenderer(0);
Assume.That(baseData.TryAddCameraToStack(overlayCamera), "Could not add the overlay camera to the stack.");
yield return SettleAndAssert(needsRealBackbufferMSAA: false);
}
[UnityTest]
public IEnumerator SingleCamera_RenderTexture_DisablesMSAA()
{
CreateRenderTextureCamera();
// Nothing renders to the real back buffer, so it doesn't need MSAA.
yield return SettleAndAssert(needsRealBackbufferMSAA: false);
}
[UnityTest]
public IEnumerator TileOnly_DirectCamera_KeepsMSAA()
{
// Tile-only must be set at renderer construction, so use a dedicated asset. Tile-only's whole
// point is to keep rendering on-tile and avoid intermediates, so a direct camera should render
// straight to the (multisampled) back buffer - the probe confirms no intermediate is added.
var previousAsset = QualitySettings.renderPipeline;
var tileOnlyAsset = CreateAsset(tileOnly: true);
QualitySettings.renderPipeline = tileOnlyAsset;
try
{
CreateScreenCamera(intermediate: false);
// Let the renderer build, then confirm tile-only actually engaged on this platform.
yield return null;
var renderer = tileOnlyAsset.GetRenderer(0) as UniversalRenderer;
if (renderer == null || !renderer.useTileOnlyMode)
Assert.Ignore("Tile-only mode is not active on this platform.");
yield return SettleAndAssert(needsRealBackbufferMSAA: true);
}
finally
{
QualitySettings.renderPipeline = previousAsset;
var rendererData = tileOnlyAsset.rendererDataList[0];
Object.DestroyImmediate(tileOnlyAsset);
if (rendererData != null)
Object.DestroyImmediate(rendererData);
}
}
[UnityTest]
public IEnumerator RenderRequest_DoesNotChangeBackbufferMSAA()
{
// Establish a converged state with an on-screen camera.
CreateScreenCamera(intermediate: false);
yield return TickFrames(k_SettleFrames);
int requestedBefore = Screen.msaaSamples;
// A camera that would render directly to the back buffer, but only ever via a render request
// (disabled so it never participates in the normal frame loop).
var go = new GameObject("MSAA Test Request Camera");
m_TestObjects.Add(go);
var requestCamera = go.AddComponent<Camera>();
requestCamera.allowMSAA = true;
requestCamera.enabled = false;
var data = go.AddComponent<UniversalAdditionalCameraData>();
data.SetRenderer(0);
var rt = new RenderTexture(128, 128, 16);
m_TestObjects.Add(rt);
// SubmitRenderRequest renders synchronously, so the before/after read brackets exactly its effect.
RenderPipeline.SubmitRenderRequest(requestCamera, new RenderPipeline.StandardRequest { destination = rt });
Assert.AreEqual(requestedBefore, Screen.msaaSamples,
"A render request must not change the real back buffer MSAA request.");
}
[UnityTest]
public IEnumerator Transition_CameraMSAATogglesWithinSession_BackbufferFollows()
{
// Drives the real reallocation path the fresh-fixture scenarios never hit: transitions within one
// continuous session (4 -> 1 -> 4). AssertStableForFrames adds the steady-state no-churn check.
int multisampledCount = m_Asset.msaaSampleCount;
var camera = CreateScreenCamera(intermediate: false);
// Direct camera with MSAA -> the back buffer must be multisampled, and stay there.
yield return SettleAndAssert(needsRealBackbufferMSAA: true);
yield return AssertStableForFrames(multisampledCount, k_StabilityFrames);
// Same camera still rendering directly, but MSAA off -> the back buffer must drop to single-sampled.
int before = Screen.currentBackbufferMSAASamples;
camera.allowMSAA = false;
yield return SettleAndAssert(needsRealBackbufferMSAA: false);
Assert.AreNotEqual(before, Screen.currentBackbufferMSAASamples, "Expected the back buffer MSAA to transition down when MSAA was disabled.");
yield return AssertStableForFrames(1, k_StabilityFrames);
// MSAA back on -> the back buffer must become multisampled again, and stay there.
before = Screen.currentBackbufferMSAASamples;
camera.allowMSAA = true;
yield return SettleAndAssert(needsRealBackbufferMSAA: true);
Assert.AreNotEqual(before, Screen.currentBackbufferMSAASamples, "Expected the back buffer MSAA to transition back up when MSAA was re-enabled.");
yield return AssertStableForFrames(multisampledCount, k_StabilityFrames);
}
// ---- Helpers ------------------------------------------------------------------------------
// Assert.Ignore writes its reason to the NUnit result XML, but not to the player log. On device/player
// jobs the player log (TestRunnerLog.txt) is what's at hand, so mirror the skip reason and the caps
// that drove it there first - this is how we confirm, from the device itself, why a platform skipped
// (e.g. what supportsMultisampleAutoResolve / supportsMultisampledBackBuffer actually report on iOS).
static void IgnoreWithLog(string reason)
{
Debug.Log($"[RealBackbufferMSAATests] Skipping fixture: {reason} " +
$"(graphicsDeviceType={SystemInfo.graphicsDeviceType}, " +
$"supportsMultisampleAutoResolve={SystemInfo.supportsMultisampleAutoResolve}, " +
$"supportsMultisampledBackBuffer={SystemInfo.supportsMultisampledBackBuffer}, " +
$"explicitMsaaResolve={UniversalRenderer.PlatformRequiresExplicitMsaaResolve()}, " +
$"xrDisplayActive={XRSystem.displayActive}, xrAutomatedTests={XRGraphicsAutomatedTests.enabled})");
Assert.Ignore(reason);
}
// Ticks 'count' frames, recording the applied back buffer MSAA each one for the diagnostics timeline.
IEnumerator TickFrames(int count)
{
for (int i = 0; i < count; i++)
{
yield return null;
m_CurrentBackbufferMsaaPerFrame.Add(Screen.currentBackbufferMSAASamples);
}
}
// Asserts the applied back buffer MSAA stays at 'expected' for 'count' frames - the steady-state
// no-churn check. Observes the applied count, so it can't see a redundant SetMSAASamples(sameValue)
// reallocation (no managed hook for that).
IEnumerator AssertStableForFrames(int expected, int count)
{
int start = m_CurrentBackbufferMsaaPerFrame.Count;
yield return TickFrames(count);
for (int i = start; i < m_CurrentBackbufferMsaaPerFrame.Count; i++)
Assert.AreEqual(expected, m_CurrentBackbufferMsaaPerFrame[i],
$"Back buffer MSAA churned at steady state (frame index {i} was {m_CurrentBackbufferMsaaPerFrame[i]}, expected a stable {expected}). " +
$"Current MSAA per ticked frame: [{string.Join(", ", m_CurrentBackbufferMsaaPerFrame)}]");
}
// Establishes an MSAA-on baseline the real way: a needing camera appears (back buffer goes
// multisampled), then leaves - so the off-test measures a genuine downgrade, not an already-off state.
IEnumerator EstablishMsaaOn()
{
int multisampledCount = m_Asset.msaaSampleCount;
var go = new GameObject("MSAA Test Baseline Camera");
m_TestObjects.Add(go);
var camera = go.AddComponent<Camera>();
camera.allowMSAA = true;
camera.allowHDR = false;
camera.allowDynamicResolution = false;
camera.targetTexture = null;
camera.rect = new Rect(0f, 0f, 1f, 1f);
var data = go.AddComponent<UniversalAdditionalCameraData>();
data.SetRenderer(0);
data.renderPostProcessing = false;
// Tick at least once with the camera present (even if the back buffer is already multisampled
// from a prior test) so the helper actually drives the baseline and resets the downgrade clock,
// making the following downgrade deterministic.
for (int i = 0; i < k_SettleFrames; i++)
{
yield return null;
m_CurrentBackbufferMsaaPerFrame.Add(Screen.currentBackbufferMSAASamples);
if (Screen.currentBackbufferMSAASamples == multisampledCount)
break;
}
Assert.AreEqual(multisampledCount, Screen.currentBackbufferMSAASamples,
"Failed to establish the MSAA-on baseline before measuring the downgrade.");
Object.DestroyImmediate(go);
}
IEnumerator SettleAndAssert(bool needsRealBackbufferMSAA)
{
// The fixture only runs where the platform supports a multisampled back buffer (see
// OneTimeSetUp), so a camera that needs it keeps the asset's sample count; otherwise it's 1.
int expectedRequest = needsRealBackbufferMSAA ? m_Asset.msaaSampleCount : 1;
// Arrange the opposite baseline (asserted), so each test measures a real transition rather
// than an incidental steady state.
if (needsRealBackbufferMSAA)
{
// Off baseline via the cameras' off form - allowMSAA=false still renders direct, so routing
// is unchanged - then enable MSAA and require the upgrade within its tight bound.
foreach (var camera in m_ProbeCameras)
camera.allowMSAA = false;
yield return TickFrames(k_SettleFrames);
Assert.AreEqual(1, Screen.currentBackbufferMSAASamples,
"Failed to establish the MSAA-off baseline before measuring the upgrade.");
foreach (var camera in m_ProbeCameras)
camera.allowMSAA = true;
yield return TickFrames(k_UpgradeFrames);
}
else
{
yield return EstablishMsaaOn();
yield return TickFrames(k_SettleFrames);
}
// What the optimization decided to request.
Assert.AreEqual(expectedRequest, Screen.msaaSamples,
$"Requested real back buffer MSAA should be {expectedRequest} (needs={needsRealBackbufferMSAA}).");
foreach (var camera in m_ProbeCameras)
{
// Confirm the camera actually rendered the way the scenario intends, so a camera silently
// forced through an intermediate can't pass as "direct" (or vice versa).
bool expectedDirect = !m_IntermediateCameras.Contains(camera);
Assert.IsTrue(m_ProbePass.observedActiveTargetIsBackbuffer.TryGetValue(camera, out bool renderedDirect),
$"Camera '{camera.name}' did not render, so its back buffer usage couldn't be probed.");
Assert.AreEqual(expectedDirect, renderedDirect,
$"Camera '{camera.name}' should render {(expectedDirect ? "directly to the back buffer (no intermediate)" : "through an intermediate")}.");
// Confirm the request is already settled to the expected count at the instant the camera
// renders - not just by teardown - so a one-frame apply lag would be caught.
Assert.IsTrue(m_ProbePass.observedRequestedMsaa.TryGetValue(camera, out int requestedAtRender),
$"Camera '{camera.name}' did not render, so its requested back buffer MSAA couldn't be probed.");
Assert.AreEqual(expectedRequest, requestedAtRender,
$"Camera '{camera.name}' requested back buffer MSAA at render time should be {expectedRequest}.");
// The actual applied count must match the request once settled (SettleFrames absorbs the
// one-frame apply lag), so any remaining disagreement is a real bug.
Assert.IsTrue(m_ProbePass.observedCurrentBackbufferMsaa.TryGetValue(camera, out int currentAtRender),
$"Camera '{camera.name}' did not render, so its current back buffer MSAA couldn't be probed.");
Assert.AreEqual(expectedRequest, currentAtRender,
$"Camera '{camera.name}' current back buffer MSAA at render time should be {expectedRequest}.");
}
}
// On any failure in this fixture, dump the captured back buffer MSAA state so CI logs explain why
// without needing a device repro: the platform/caps, the requested vs current counts, and per camera
// how it actually rendered (direct vs intermediate) and the current back buffer MSAA seen at render time.
void LogFailureDiagnostics()
{
var sb = new System.Text.StringBuilder();
sb.AppendLine($"[RealBackbufferMSAATests] '{TestContext.CurrentContext.Test.Name}' failed. Captured state:");
sb.AppendLine($" graphicsDeviceType={SystemInfo.graphicsDeviceType}, supportsMultisampledBackBuffer={SystemInfo.supportsMultisampledBackBuffer}, explicitMsaaResolve={UniversalRenderer.PlatformRequiresExplicitMsaaResolve()}");
sb.AppendLine($" asset.msaaSampleCount={m_Asset.msaaSampleCount}, Screen.msaaSamples(requested)={Screen.msaaSamples}, Screen.currentBackbufferMSAASamples(in teardown)={Screen.currentBackbufferMSAASamples}");
foreach (var camera in m_ProbeCameras)
{
string rendered = m_ProbePass.observedActiveTargetIsBackbuffer.TryGetValue(camera, out bool isBackbuffer)
? (isBackbuffer ? "direct" : "intermediate") : "<not rendered>";
string current = m_ProbePass.observedCurrentBackbufferMsaa.TryGetValue(camera, out int currentMsaa)
? currentMsaa.ToString() : "<not rendered>";
string requestedAtProbe = m_ProbePass.observedRequestedMsaa.TryGetValue(camera, out int reqMsaa)
? reqMsaa.ToString() : "<not rendered>";
sb.AppendLine($" camera '{camera.name}': expectedIntermediate={m_IntermediateCameras.Contains(camera)}, rendered={rendered}, requestedMSAA(at render time)={requestedAtProbe}, currentBackbufferMSAA(at render time)={current}");
}
sb.AppendLine($" current back buffer MSAA per ticked frame: [{string.Join(", ", m_CurrentBackbufferMsaaPerFrame)}]");
Debug.Log(sb.ToString());
}
Camera CreateScreenCamera(bool intermediate)
{
var go = new GameObject("MSAA Test Screen Camera");
m_TestObjects.Add(go);
var camera = go.AddComponent<Camera>();
// Pin every camera setting that would otherwise push the camera through an intermediate, so a
// "direct" camera is direct because the test says so, not because of defaults.
camera.allowMSAA = true;
camera.allowHDR = false;
camera.allowDynamicResolution = false;
camera.targetTexture = null;
camera.rect = new Rect(0f, 0f, 1f, 1f);
var data = go.AddComponent<UniversalAdditionalCameraData>();
data.SetRenderer(0);
data.renderPostProcessing = false;
m_ProbeCameras.Add(camera);
if (intermediate)
m_IntermediateCameras.Add(camera);
return camera;
}
Camera CreateRenderTextureCamera()
{
var rt = new RenderTexture(128, 128, 16) { antiAliasing = k_AssetMsaaSampleCount };
m_TestObjects.Add(rt);
var go = new GameObject("MSAA Test RenderTexture Camera");
m_TestObjects.Add(go);
var camera = go.AddComponent<Camera>();
camera.allowMSAA = true;
camera.targetTexture = rt;
var data = go.AddComponent<UniversalAdditionalCameraData>();
data.SetRenderer(0);
return camera;
}
UniversalRenderPipelineAsset CreateAsset(bool tileOnly = false)
{
var rendererData = ScriptableObject.CreateInstance<UniversalRendererData>();
rendererData.renderingMode = RenderingMode.Forward;
rendererData.tileOnlyMode = tileOnly;
var instance = ScriptableObject.CreateInstance<UniversalRenderPipelineAsset>();
instance.m_RendererDataList[0] = rendererData;
// Pin every setting that feeds RequiresIntermediateColorTexture, rather than trusting fresh-asset
// defaults: any of these flipping on would push a "direct" camera through an intermediate and
// silently invalidate the test. With these off, the direct-vs-intermediate distinction is
// controlled solely by the force-intermediate pass.
instance.msaaSampleCount = k_AssetMsaaSampleCount;
instance.supportsHDR = false;
instance.supportsCameraOpaqueTexture = false;
instance.supportsCameraDepthTexture = false;
instance.renderScale = 1.0f;
return instance;
}
// A no-op pass that only declares it needs an intermediate texture, forcing URP to render the
// camera through an intermediate attachment (decoupled from any specific URP feature).
class ForceIntermediatePass : ScriptableRenderPass
{
public ForceIntermediatePass()
{
requiresIntermediateTexture = true;
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
}
}
// Records, per camera, whether the active render target after opaques is the back buffer (direct)
// or an intermediate. Read back by the test to verify each camera rendered as intended.
class ActiveTargetProbePass : ScriptableRenderPass
{
public readonly Dictionary<Camera, bool> observedActiveTargetIsBackbuffer = new();
public readonly Dictionary<Camera, int> observedCurrentBackbufferMsaa = new();
public readonly Dictionary<Camera, int> observedRequestedMsaa = new();
public ActiveTargetProbePass()
{
renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
var cameraData = frameData.Get<UniversalCameraData>();
var resourceData = frameData.Get<UniversalResourceData>();
observedActiveTargetIsBackbuffer[cameraData.camera] = resourceData.isActiveTargetBackBuffer;
// Capture applied and requested counts at the same instant the camera renders, so a failure
// shows whether they disagree mid-render rather than just by teardown.
observedCurrentBackbufferMsaa[cameraData.camera] = Screen.currentBackbufferMSAASamples;
observedRequestedMsaa[cameraData.camera] = Screen.msaaSamples;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 61abe3cacdf844c6aa82da8e6114defb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,361 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using NUnit.Framework;
using UnityEngine.Rendering.RenderGraphModule;
using UnityEngine.TestTools;
namespace UnityEngine.Rendering.Universal.Tests
{
[TestFixture]
class RenderGraphConstraintsTests
{
RenderPipelineAsset m_PreviousQualityRenderPipelineAsset;
Type m_PreviousSessionType;
UniversalRenderPipelineAsset m_UniversalRenderPipelineAsset;
UniversalRendererData m_UniversalRendererData;
OnTileValidationConfiguration m_DefaultOnTileValidationConfiguration;
EntityId m_CameraEntityId;
static UniversalAdditionalCameraData s_AdditionalCameraData;
static PostProcessData s_PostProcessData;
static HashSet<RenderingMode> s_RenderingModes;
readonly HashSet<string> m_ResourceTestNames = new()
{
"_CameraTargetAttachmentA",
"_CameraTargetAttachmentB",
"_CameraTargetAttachment",
"_CameraDepthAttachment",
"_CameraDepthTexture",
"_CameraOpaqueTexture",
"_CameraNormalsTexture",
"_MotionVectorTexture",
"_MotionVectorDepthTexture",
"_CameraRenderingLayersTexture",
"_GBuffer0",
"_GBuffer1",
"_GBuffer2",
"_GBuffer3",
"_GBuffer4",
"_GBuffer5",
"_GBuffer6",
"_DBufferTexture0",
"_DBufferTexture1",
"_DBufferTexture2",
"_ScreenSpaceShadowmapTexture",
"_CameraColorAfterPostProcessing",
"_CameraColorFullScreenPass",
};
[OneTimeSetUp]
public void OneTimeSetUp()
{
if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset)
Assert.Ignore($"This test will be only executed when URP is the current pipeline");
#if UNITY_EDITOR
if (UnityEditor.EditorWindow.HasOpenInstances<UnityEditor.Rendering.RenderGraphViewer>())
UnityEditor.EditorWindow.GetWindow<UnityEditor.Rendering.RenderGraphViewer>().Close();
#endif
m_PreviousSessionType = RenderGraphDebugSession.currentDebugSession?.GetType();
m_PreviousQualityRenderPipelineAsset = QualitySettings.renderPipeline;
RenderGraphDebugSession.Create<TestRenderGraphDebugSession>();
// Create new URP asset
m_UniversalRenderPipelineAsset = Create();
QualitySettings.renderPipeline = m_UniversalRenderPipelineAsset;
Assume.That(m_UniversalRenderPipelineAsset.rendererDataList != null && m_UniversalRenderPipelineAsset.rendererDataList.Length > 0);
// Get URP Renderer Data
m_UniversalRendererData = m_UniversalRenderPipelineAsset.rendererDataList[0] as UniversalRendererData;
Assume.That(m_UniversalRendererData != null);
m_DefaultOnTileValidationConfiguration = new OnTileValidationConfiguration();
var gameObject = new GameObject();
var camera = gameObject.AddComponent<Camera>();
m_CameraEntityId = camera.GetEntityId();
s_AdditionalCameraData = gameObject.AddComponent<UniversalAdditionalCameraData>();
s_AdditionalCameraData.renderPostProcessing = true;
s_AdditionalCameraData.SetRenderer(0);
}
[UnitySetUp]
public IEnumerator SetUp()
{
m_DefaultOnTileValidationConfiguration.ApplyToAssetAndRenderer(m_UniversalRenderPipelineAsset, m_UniversalRendererData);
yield return null;
if (!RenderGraphDebugSession.GetRegisteredGraphs().Contains("URPRenderGraph"))
Assert.Ignore("Ignore this test as we couldn't setup debug session for URPRenderGraph.");
}
UniversalRenderPipelineAsset Create()
{
// Create Universal RP Asset
var instance = ScriptableObject.CreateInstance<UniversalRenderPipelineAsset>();
// Initialize default renderer data
instance.m_RendererDataList[0] = ScriptableObject.CreateInstance<UniversalRendererData>();
// Setup PP from existing urp asset
s_RenderingModes = new HashSet<RenderingMode>();
ProcessRenderPipelineAsset(GraphicsSettings.defaultRenderPipeline, instance);
for (int i = 0; i < QualitySettings.count; i++)
ProcessRenderPipelineAsset(QualitySettings.GetRenderPipelineAssetAt(i), instance);
return instance;
}
static void ProcessRenderPipelineAsset(RenderPipelineAsset rpAsset, UniversalRenderPipelineAsset instance)
{
if (rpAsset == null || rpAsset is not UniversalRenderPipelineAsset urpAsset)
return;
foreach (var existingRendererData in urpAsset.rendererDataList)
{
if (existingRendererData == null || existingRendererData is not UniversalRendererData urpRendererData)
continue;
if (urpRendererData.postProcessData != null && s_PostProcessData == null)
{
s_PostProcessData = urpRendererData.postProcessData;
((UniversalRendererData)instance.m_RendererDataList[0]).postProcessData =
urpRendererData.postProcessData;
}
s_RenderingModes.Add(urpRendererData.renderingMode);
}
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
if (m_PreviousSessionType != null)
RenderGraphDebugSession.Create(m_PreviousSessionType);
else
RenderGraphDebugSession.EndSession();
QualitySettings.renderPipeline = m_PreviousQualityRenderPipelineAsset;
Object.DestroyImmediate(m_UniversalRenderPipelineAsset);
Object.DestroyImmediate(m_UniversalRendererData);
Object.DestroyImmediate(s_AdditionalCameraData.gameObject);
}
public class OnTileValidationConfiguration
{
public bool supportsCameraOpaqueTexture { get; set; } = false;
public bool supportsCameraDepthTexture { get; set; } = false;
public bool supportsHDR { get; set; } = false;
public int msaaSampleCount { get; set; } = 1;
public RenderingMode renderingMode { get; set; } = RenderingMode.Forward;
public bool occlusionCulling { get; set; } = false;
public float renderScale { get; set; } = 1.0f;
public bool postProcessingEnabled { get; set; } = false;
public bool tileOnlyMode { get; set; } = false;
public List<ScriptableRendererFeature> rendererFeatures { get; set; } = new();
bool TryApplyToAssetAndRenderer(UniversalRenderPipelineAsset asset, UniversalRendererData rendererData)
{
// Apply asset settings
asset.supportsCameraDepthTexture = supportsCameraDepthTexture;
asset.supportsCameraOpaqueTexture = supportsCameraOpaqueTexture;
asset.supportsHDR = supportsHDR;
asset.msaaSampleCount = msaaSampleCount;
asset.renderScale = renderScale;
if (occlusionCulling)
{
if (!Application.isEditor)
return false;
#if UNITY_EDITOR
if (UnityEditor.Rendering.EditorGraphicsSettings.batchRendererGroupShaderStrippingMode !=
UnityEditor.Rendering.BatchRendererGroupStrippingMode.KeepAll)
return false;
#endif
asset.gpuResidentDrawerMode = GPUResidentDrawerMode.InstancedDrawing;
asset.gpuResidentDrawerEnableOcclusionCullingInCameras = occlusionCulling;
renderingMode = RenderingMode.ForwardPlus;
}
// Apply renderer settings
rendererData.tileOnlyMode = tileOnlyMode;
if (renderingMode != RenderingMode.Forward && !s_RenderingModes.Contains(renderingMode))
return false;
rendererData.renderingMode = renderingMode;
if (postProcessingEnabled && s_PostProcessData == null)
return false;
rendererData.postProcessData = s_PostProcessData != null ? s_PostProcessData : null;
// Clear
rendererData.rendererFeatures.Clear();
foreach (var feature in rendererFeatures)
rendererData.rendererFeatures.Add(feature);
return true;
}
public void ApplyToAssetAndRenderer(UniversalRenderPipelineAsset asset, UniversalRendererData rendererData)
{
if (!TryApplyToAssetAndRenderer(asset, rendererData))
Assert.Ignore("We can't run this test for On Tile Validation because some resources could be missing.");
}
}
static TestCaseData[] s_OnTileValidationCases =
{
new TestCaseData(new OnTileValidationConfiguration { supportsCameraOpaqueTexture = true })
.SetName("Camera Opaque Texture on Universal Render Pipeline Asset.").Returns(null),
new TestCaseData(new OnTileValidationConfiguration { supportsCameraDepthTexture = true })
.SetName("Camera Depth Texture on Universal Render Pipeline Asset.").Returns(null),
new TestCaseData(new OnTileValidationConfiguration { supportsHDR = true })
.SetName("Support HDR on Universal Render Pipeline Asset.").Returns(null),
new TestCaseData(new OnTileValidationConfiguration { msaaSampleCount = 4 })
.SetName("MSAA Samples > 1 on Universal Render Pipeline Asset.").Returns(null),
new TestCaseData(new OnTileValidationConfiguration { occlusionCulling = true })
.SetName("GPU Occlusion Culling on Universal Render Pipeline Asset.").Returns(null),
new TestCaseData(new OnTileValidationConfiguration { renderingMode = RenderingMode.Deferred })
.SetName("Deferred Rendering Mode on Universal Renderer.").Returns(null),
new TestCaseData(new OnTileValidationConfiguration { renderingMode = RenderingMode.DeferredPlus })
.SetName("Deferred Plus Rendering Mode on Universal Renderer.").Returns(null),
new TestCaseData(new OnTileValidationConfiguration { renderScale = 0.65f })
.SetName("Render Scale on Universal Renderer.").Returns(null),
new TestCaseData(new OnTileValidationConfiguration { postProcessingEnabled = true })
.SetName("Post Processing on Universal Renderer.").Returns(null),
};
[UnityPlatform(exclude = new RuntimePlatform[] { RuntimePlatform.WebGLPlayer })]
[UnityTest]
[TestCaseSource(nameof(s_OnTileValidationCases))]
public IEnumerator URPSettingsShouldNotCauseNonMemorylessTargets(OnTileValidationConfiguration config)
{
// Arrange
LogAssert.ignoreFailingMessages = true;
config.ApplyToAssetAndRenderer(m_UniversalRenderPipelineAsset, m_UniversalRendererData);
// Act
m_UniversalRendererData.tileOnlyMode = true;
yield return null;
// No need to go further if we don't support memoryless textures
if (SystemInfo.supportsMemorylessTextures)
{
Assert.That(OnlyBackbufferOrMemoryless(outputNonMemoryless: true), Is.True, "Non-memoryless intermediate targets were produced.");
}
LogAssert.ignoreFailingMessages = false;
}
[UnityPlatform(exclude = new RuntimePlatform[] { RuntimePlatform.WebGLPlayer})]
[UnityTest]
public IEnumerator CameraStackingProduceWarning()
{
if (Display.main.requiresSrgbBlitToBackbuffer)
Assert.Ignore("Tile-Only Mode falls back to normal rendering when the display requires an sRGB present blit; the overlay-unsupported warning won't be produced.");
// Arrange
var gameObject = new GameObject();
var camera = gameObject.AddComponent<Camera>();
var additionalCameraData = gameObject.AddComponent<UniversalAdditionalCameraData>();
additionalCameraData.renderType = CameraRenderType.Overlay;
Assume.That(s_AdditionalCameraData.TryAddCameraToStack(camera), "Couldn't add camera to stack.");
yield return null;
Assume.That(OnlyBackbufferOrMemoryless(), Is.False, "Intermediate Targets expected without On Tile Validation.");
yield return null;
// Act
LogAssert.Expect(LogType.Warning, new Regex("does not support Overlay cameras"));
LogAssert.Expect(LogType.Warning, new Regex("camera overlay no longer exists"));
m_UniversalRendererData.tileOnlyMode = true;
yield return null;
m_UniversalRendererData.tileOnlyMode = false;
yield return null;
Object.DestroyImmediate(gameObject);
s_AdditionalCameraData.UpdateCameraStack();
}
bool OnlyBackbufferOrMemoryless(bool outputNonMemoryless = false)
{
var onlyMemoryless = true;
var debugData = RenderGraphDebugSession.GetDebugData("URPRenderGraph", m_CameraEntityId);
var textureList = debugData.resourceLists[(int)RenderGraphResourceType.Texture];
for (int i = 0; i < textureList.Count; i++)
{
var resource = textureList[i];
if (resource is { releasePassIndex: -1, creationPassIndex: -1 })
continue;
if (!IsCameraTargetAttachment(resource.name) || resource.memoryless)
continue;
if (!outputNonMemoryless)
return false;
Debug.Log($"{resource.name} isn't memoryless.");
onlyMemoryless = false;
}
return onlyMemoryless;
}
bool IsCameraTargetAttachment(string name)
{
return m_ResourceTestNames.Contains(name);
}
class TestRenderGraphDebugSession : RenderGraphDebugSession
{
public override bool isActive => true;
public TestRenderGraphDebugSession()
{
RegisterAllLocallyKnownGraphsAndExecutions();
}
}
class TestScriptableRendererFeature : ScriptableRendererFeature
{
TestScriptableRendererPass m_TestScriptableRendererPass;
public override void Create()
{
m_TestScriptableRendererPass = new TestScriptableRendererPass();
}
public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
{
renderer.EnqueuePass(m_TestScriptableRendererPass);
}
}
public class TestPass { }
class TestScriptableRendererPass : ScriptableRenderPass
{
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
using var builder = renderGraph.AddRasterRenderPass<TestPass>("Test Scriptable Renderer Pass", out _);
builder.SetRenderFunc(static (TestPass _, RasterGraphContext _) => { });
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 993d9a6b07bf33c4dbf1f13f5879bd34
@@ -0,0 +1,160 @@
using System;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEngine;
using UnityEngine.Rendering.Universal;
using UnityEngine.Rendering;
using Object = UnityEngine.Object;
[TestFixture]
class RuntimeTests
{
GameObject go;
Camera camera;
RenderPipelineAsset currentAssetGraphics;
RenderPipelineAsset currentAssetQuality;
[SetUp]
public void Setup()
{
go = new GameObject();
camera = go.AddComponent<Camera>();
currentAssetGraphics = GraphicsSettings.defaultRenderPipeline;
currentAssetQuality = QualitySettings.renderPipeline;
}
[TearDown]
public void Cleanup()
{
GraphicsSettings.defaultRenderPipeline = currentAssetGraphics;
QualitySettings.renderPipeline = currentAssetQuality;
Object.DestroyImmediate(go);
}
static readonly (int tier, string textTier)[] k_ShadowResolutions =
{
(UniversalAdditionalLightData.AdditionalLightsShadowResolutionTierLow, "Low"),
(UniversalAdditionalLightData.AdditionalLightsShadowResolutionTierMedium, "Medium"),
(UniversalAdditionalLightData.AdditionalLightsShadowResolutionTierHigh, "High"),
};
[UnityTest]
public IEnumerator AdditionalLightsShadowResolutionTier_SetsExpectedResolution_WhenInPlayerOrPlayMode(
[ValueSource(nameof(k_ShadowResolutions))] (int tier, string textTier) testData)
{
AssetCheck();
UniversalRenderPipelineAsset urpAsset =
QualitySettings.renderPipeline as UniversalRenderPipelineAsset ??
GraphicsSettings.defaultRenderPipeline as UniversalRenderPipelineAsset;
int expectedResolution = urpAsset.additionalLightsShadowResolutionTierLow;
if (testData.tier == UniversalAdditionalLightData.AdditionalLightsShadowResolutionTierMedium)
expectedResolution = urpAsset.additionalLightsShadowResolutionTierMedium;
else if (testData.tier == UniversalAdditionalLightData.AdditionalLightsShadowResolutionTierHigh)
expectedResolution = urpAsset.additionalLightsShadowResolutionTierHigh;
// Create two lights to test that setting the tier on the target light does not affect another light
var targetLight = new GameObject("targetLight").AddComponent<Light>();
targetLight.type = LightType.Point;
targetLight.shadows = LightShadows.Soft;
var targetData = targetLight.gameObject.AddComponent<UniversalAdditionalLightData>();
targetData.additionalLightsShadowResolutionTier = testData.tier;
var anotherLight = new GameObject("anotherLight").AddComponent<Light>();
anotherLight.type = LightType.Point;
anotherLight.shadows = LightShadows.Soft;
var anotherData = anotherLight.gameObject.AddComponent<UniversalAdditionalLightData>();
// Set the other light to a different tier.
anotherData.additionalLightsShadowResolutionTier = UniversalAdditionalLightData.AdditionalLightsShadowResolutionTierMedium;
// Trigger a frame render to ensure URP processes the light data
var rr = new RenderPipeline.StandardRequest
{
destination = new RenderTexture(128, 128, UnityEngine.Experimental.Rendering.GraphicsFormat.R8G8B8A8_SRGB,
CoreUtils.GetDefaultDepthOnlyFormat())
};
RenderPipeline.SubmitRenderRequest(camera, rr);
yield return null;
try
{
int actualResolution = urpAsset.GetAdditionalLightsShadowResolution(targetData.additionalLightsShadowResolutionTier);
int actualOtherResolution = urpAsset.GetAdditionalLightsShadowResolution(anotherData.additionalLightsShadowResolutionTier);
Assert.AreEqual(expectedResolution, actualResolution,
$"URP should resolve {testData.textTier} tier to {expectedResolution} resolution for targetLight");
Assert.AreEqual(urpAsset.additionalLightsShadowResolutionTierMedium, actualOtherResolution,
$"URP should resolve Medium tier to {urpAsset.additionalLightsShadowResolutionTierMedium} resolution for anotherLight");
}
finally
{
Object.DestroyImmediate(targetLight.gameObject);
Object.DestroyImmediate(anotherLight.gameObject);
}
}
// When URP pipeline is active, lightsUseLinearIntensity must match active color space.
[UnityTest]
public IEnumerator PipelineHasCorrectColorSpace()
{
AssetCheck();
var rr = new UnityEngine.Rendering.RenderPipeline.StandardRequest();
rr.destination = new RenderTexture(128, 128, UnityEngine.Experimental.Rendering.GraphicsFormat.R8G8B8A8_SRGB,
CoreUtils.GetDefaultDepthOnlyFormat());
rr.mipLevel = 0;
rr.slice = 0;
rr.face = CubemapFace.Unknown;
UnityEngine.Rendering.RenderPipeline.SubmitRenderRequest(camera, rr);
yield return null;
Assert.AreEqual(QualitySettings.activeColorSpace == ColorSpace.Linear, GraphicsSettings.lightsUseLinearIntensity,
"GraphicsSettings.lightsUseLinearIntensity must match active color space.");
}
// When switching to URP it sets "UniversalPipeline" as global shader tag.
// When switching to Built-in it sets "" as global shader tag.
#if UNITY_EDITOR // TODO This API call does not reset in player
[UnityTest]
[Ignore("Unstable: https://jira.unity3d.com/browse/UUM-122594")]
public IEnumerator PipelineSetsAndRestoreGlobalShaderTagCorrectly()
{
AssetCheck();
var rr = new UnityEngine.Rendering.RenderPipeline.StandardRequest();
rr.destination = new RenderTexture(128, 128, UnityEngine.Experimental.Rendering.GraphicsFormat.R8G8B8A8_SRGB, CoreUtils.GetDefaultDepthOnlyFormat());
rr.mipLevel = 0;
rr.slice = 0;
rr.face = CubemapFace.Unknown;
UnityEngine.Rendering.RenderPipeline.SubmitRenderRequest(camera, rr);
yield return null;
Assert.AreEqual("UniversalPipeline", Shader.globalRenderPipeline, "Wrong render pipeline shader tag.");
GraphicsSettings.defaultRenderPipeline = null;
QualitySettings.renderPipeline = null;
camera.Render();
yield return null;
Assert.AreEqual("", Shader.globalRenderPipeline, "Render Pipeline shader tag is not restored.");
}
#endif
void AssetCheck()
{
//Assert.IsNotNull(currentAssetGraphics, "Render Pipeline Asset is Null");
// Temp fix, test passes if project isnt setup for Universal RP
if (RenderPipelineManager.currentPipeline == null)
Assert.Pass("Render Pipeline Asset is Null, test pass by default");
Assert.AreEqual(RenderPipelineManager.currentPipeline.GetType(), typeof(UniversalRenderPipeline),
"Pipeline Asset is not Universal RP");
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3846104859549aa4eb627e318722149f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,56 @@
#if U2D_ANIMATION_INSTALLED
using NUnit.Framework;
using UnityEngine.U2D.Animation;
namespace UnityEngine.Rendering.Universal.Tests
{
class ShadowCaster2DTests
{
GameObject m_Obj;
[SetUp]
public void Setup()
{
m_Obj = new GameObject();
m_Obj.AddComponent<SpriteRenderer>();
}
[TearDown]
public void Cleanup()
{
Object.DestroyImmediate(m_Obj);
}
[Test]
public void AddShadowCaster2DWithSpriteSkin()
{
m_Obj.AddComponent<SpriteSkin>();
ShadowCaster2D shadowCaster2D = m_Obj.AddComponent<ShadowCaster2D>();
// ShadowCaster2D.shadowShape2DProvider is always null on Standalone.
#if UNITY_EDITOR
Assert.That(shadowCaster2D.shadowShape2DProvider, Is.TypeOf(typeof(ShadowShape2DProvider_SpriteSkin)));
#else
Assert.That(shadowCaster2D.shadowShape2DProvider, Is.Null);
#endif
}
[Test]
public void AddShadowCaster2DWithSpriteSkinWhenInactive()
{
m_Obj.AddComponent<SpriteSkin>();
m_Obj.SetActive(false);
ShadowCaster2D shadowCaster2D = m_Obj.AddComponent<ShadowCaster2D>();
Assert.That(shadowCaster2D.shadowShape2DProvider, Is.Null);
m_Obj.SetActive(true);
// ShadowCaster2D.shadowShape2DProvider is always null on Standalone.
#if UNITY_EDITOR
Assert.That(shadowCaster2D.shadowShape2DProvider, Is.TypeOf(typeof(ShadowShape2DProvider_SpriteSkin)));
#else
Assert.That(shadowCaster2D.shadowShape2DProvider, Is.Null);
#endif
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cf9e72a1bdd854b65a42b0d13738efcd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,85 @@
using NUnit.Framework;
using System;
namespace UnityEngine.Rendering.Universal.Tests
{
/// <summary>
/// Tests for terrain shaders in the Universal Render Pipeline.
/// Verifies that terrain detail shaders are available through both Shader.Find() and UniversalRenderPipelineAsset properties.
/// </summary>
class TerrainShaderTests
{
UniversalRenderPipelineAsset m_UrpAsset;
[SetUp]
public void Setup()
{
// Only run this with URP in smoke tests.
if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset)
Assert.Ignore("URP Only test");
m_UrpAsset = GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset;
}
/// <summary>
/// Tests that the URP terrain detail shaders can be found using Shader.Find().
/// </summary>
[TestCaseSource(nameof(ShaderNames))]
public void TerrainShaders_ShaderFind_ReturnsValidShader(string shaderName)
{
#if !ENABLE_TERRAIN_MODULE && !UNITY_EDITOR
Assert.Ignore("Test is ignored in player build because Terrain module is disabled.");
#endif
var shader = Shader.Find(shaderName);
Assert.IsNotNull(shader, $"{shaderName} should be found via Shader.Find()");
Assert.IsTrue(shader.isSupported, $"{shaderName} should be supported on current platform");
}
private static readonly string[] ShaderNames =
{
"Hidden/TerrainEngine/Details/UniversalPipeline/Vertexlit",
"Hidden/TerrainEngine/Details/UniversalPipeline/WavingDoublePass",
"Hidden/TerrainEngine/Details/UniversalPipeline/BillboardWavingDoublePass"
};
/// <summary>
/// Tests that the UniversalRenderPipelineAsset terrain detail shader properties returns valid shaders.
/// </summary>
[TestCaseSource(nameof(URPShaderAccessors))]
public void UniversalRenderPipelineAsset_TerrainShaders_ReturnsValidShaders(Func<UniversalRenderPipelineAsset, Shader> getShader, string description)
{
#if !ENABLE_TERRAIN_MODULE && !UNITY_EDITOR
Assert.Ignore("Test is ignored in player build because Terrain module is disabled.");
#endif
Assert.IsNotNull(m_UrpAsset, "UniversalRenderPipelineAsset should be available");
var shader = getShader(m_UrpAsset);
Assert.IsNotNull(shader, $"{description} should not be null");
Assert.IsTrue(shader.isSupported, $"{description} should be supported on current platform");
}
/// <summary>
/// Tests that the UniversalRenderPipelineAsset terrain detail shader properties return null when Terrain module is disabled.
/// </summary>
[TestCaseSource(nameof(URPShaderAccessors))]
public void UniversalRenderPipelineAsset_TerrainShaders_AreNullWhenTerrainModuleIsDisabled(Func<UniversalRenderPipelineAsset, Shader> getShader, string description)
{
#if ENABLE_TERRAIN_MODULE
Assert.Ignore("Test is ignored because Terrain module is enabled.");
#endif
#if UNITY_EDITOR
Assert.Ignore("Test is ignored because shaders are always available in the editor.");
#endif
Assert.IsNotNull(m_UrpAsset, "UniversalRenderPipelineAsset should be available");
var shader = getShader(m_UrpAsset);
Assert.IsNull(shader, $"{description} should be be null");
}
private static readonly object[] URPShaderAccessors =
{
new object[] { new Func<UniversalRenderPipelineAsset, Shader>(a => a.terrainDetailLitShader), "URP terrainDetailLitShader" },
new object[] { new Func<UniversalRenderPipelineAsset, Shader>(a => a.terrainDetailGrassShader), "URP terrainDetailGrassShader" },
new object[] { new Func<UniversalRenderPipelineAsset, Shader>(a => a.terrainDetailGrassBillboardShader), "URP terrainDetailGrassBillboardShader" }
};
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4a5118ba2fa293c4b8a60da869ccea72
@@ -0,0 +1,39 @@
{
"name": "Unity.RenderPipelines.Universal.Runtime.Tests",
"rootNamespace": "",
"references": [
"GUID:15fc0a57446b3144c949da3e2b9737a9",
"GUID:27619889b8ba8c24980f49ee34dbb44a",
"GUID:0acc523941302664db1f4e527237feb3",
"GUID:516a5277b8c3b4f4c8cc86b77b1591ff",
"GUID:d8b63aba1907145bea998dd612889d6b",
"GUID:df380645f10b7bc4b97d4f5eb6303d95",
"GUID:41524c21c95e5fe4dbc5b48bd21995a4",
"GUID:4fd6538c1c56b409fb53fdf0183170ec",
"GUID:3eae0364be2026648bf74846acb8a731"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": true,
"precompiledReferences": [
"nunit.framework.dll"
],
"autoReferenced": false,
"defineConstraints": [
"UNITY_INCLUDE_TESTS"
],
"versionDefines": [
{
"name": "com.unity.2d.animation",
"expression": "1.0.0",
"define": "U2D_ANIMATION_INSTALLED"
},
{
"name": "com.unity.modules.terrain",
"expression": "1.0.0",
"define": "ENABLE_TERRAIN_MODULE"
}
],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: bc3b0daec27db604caf7fec37e54bf6d
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: