From 33699438eae72e5e5dc3d35e046b183e81820c6a Mon Sep 17 00:00:00 2001 From: Cian Noonan Date: Tue, 27 Oct 2026 06:22:06 +0000 Subject: [PATCH 01/18] [Port] [6000.3] [UUM-154186] [HDRP] Wait for the GPU before releasing FSR2 contexts on dispose --- .../Runtime/RenderPipeline/RenderPass/FSR2Pass.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FSR2Pass.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FSR2Pass.cs index 3defef3d9c4..5c3b65348a6 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FSR2Pass.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FSR2Pass.cs @@ -61,6 +61,8 @@ public void BeginFrame(HDCamera hdCamera) public void Cleanup() { #if ENABLE_AMD && ENABLE_AMD_MODULE + if (m_CameraStates.cameras.Count > 0) + WaitForGPUIdle(); foreach (var cameraState in m_CameraStates.cameras.Values) m_CameraStates.InvalidateState(cameraState); CleanupCameraStates(); @@ -397,6 +399,12 @@ private void CleanupCameraStates() m_CameraStates.CleanupCameraStates(); } + private static void WaitForGPUIdle() + { + using var syncBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Raw, 1, sizeof(uint)); + AsyncGPUReadback.Request(syncBuffer).WaitForCompletion(); + } + private void InternalAMDSetupDRSScaling(bool enableAutomaticSettings, Camera camera, in HDAdditionalCameraData hdCam, XRPass xrPass, ref GlobalDynamicResolutionSettings dynamicResolutionSettings) { if (m_Device == null) From 02c41f58789e4361ce1bb9f8d9a5f12b2622e00d Mon Sep 17 00:00:00 2001 From: Chris Chu Date: Tue, 27 Oct 2026 17:31:28 +0000 Subject: [PATCH 02/18] [Port] [6000.3] [UUM-147033] Fix 2D collider shadow flicker across Editor views --- .../Runtime/2D/Shadows/ShadowCaster2D.cs | 11 +- .../ShadowShape2DProvider_Collider.cs | 15 ++ .../2D/Shadows/ShadowProvider/ShadowMesh2D.cs | 11 + .../ShadowProvider/ShadowShape2DProvider.cs | 8 + .../ShadowCaster2DColliderCullingTests.cs | 201 ++++++++++++++++++ ...ShadowCaster2DColliderCullingTests.cs.meta | 11 + ...derPipelines.Universal.Editor.Tests.asmdef | 8 +- 7 files changed, 263 insertions(+), 2 deletions(-) create mode 100644 Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DColliderCullingTests.cs create mode 100644 Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DColliderCullingTests.cs.meta diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCaster2D.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCaster2D.cs index d239195ddd1..4f45c24eab4 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCaster2D.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowCaster2D.cs @@ -485,7 +485,16 @@ public void Update() } if(m_ShadowMesh != null) - m_ShadowMesh.UpdateBoundingSphere(transform); + { + // The shadow mesh is culled to the last camera that rendered, so a provider that knows the + // whole shape's bounds sizes the sphere instead. Then IsLit does not depend on the camera. + if (m_ShadowCastingSource == ShadowCastingSources.ShapeProvider && + m_ShadowShape2DProvider != null && m_ShadowShape2DComponent != null && + m_ShadowShape2DProvider.TryGetWorldBounds(m_ShadowShape2DComponent, out var worldBounds)) + m_ShadowMesh.SetBoundingSphere(worldBounds, transform.position.z); + else + m_ShadowMesh.UpdateBoundingSphere(transform); + } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/Providers/ShadowShape2DProvider_Collider.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/Providers/ShadowShape2DProvider_Collider.cs index 81fefbd088a..a2b3dfb9c4c 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/Providers/ShadowShape2DProvider_Collider.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/Providers/ShadowShape2DProvider_Collider.cs @@ -359,6 +359,21 @@ public override void OnPersistantDataCreated(Component sourceComponent, ShadowSh Initialize(); } + internal override bool TryGetWorldBounds(Component sourceComponent, out Bounds worldBounds) + { + var collider = sourceComponent as Collider2D; + if (collider == null || !collider.isActiveAndEnabled || collider.shapeCount == 0) + { + worldBounds = default; + return false; + } + + // Read every time rather than cached. A cache keyed on the pose would keep bounds that were + // read before Physics2D synced a move. + worldBounds = collider.bounds; + return true; + } + public override void OnBeforeRender(Component sourceComponent, Bounds worldCullingBounds, ShadowShape2D persistantShadowShape) { Collider2D collider = (Collider2D)sourceComponent; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/ShadowMesh2D.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/ShadowMesh2D.cs index 2ff85eca9ee..ee0997cf8e8 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/ShadowMesh2D.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/ShadowMesh2D.cs @@ -412,5 +412,16 @@ public void UpdateBoundingSphere(Transform transform) m_BoundingSphere = new BoundingSphere(center, radius); } + + // Sets the bounding sphere from world bounds. Only the x and y extents size it, so the bounds' + // z depth cannot inflate it. The center's z is given by the caller. + internal void SetBoundingSphere(Bounds worldBounds, float z) + { + var center = new Vector3(worldBounds.center.x, worldBounds.center.y, z); + var extents = worldBounds.extents; + var radius = new Vector2(extents.x, extents.y).magnitude; + + m_BoundingSphere = new BoundingSphere(center, radius); + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/ShadowShape2DProvider.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/ShadowShape2DProvider.cs index 85c2eb639c1..d78a6a36c54 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/ShadowShape2DProvider.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/ShadowShape2DProvider.cs @@ -42,6 +42,14 @@ public virtual void Enabled(Component sourceComponent, ShadowShape2D persistan /// An instance of ShadowShape2D that is used by the ShadowCaster2D public virtual void Disabled(Component sourceComponent, ShadowShape2D persistantShadowShape) {} + // World bounds of the whole source shape, independent of any camera's culling. When this returns + // true, the ShadowCaster2D sizes its bounding sphere from them instead of from the (culled) shadow mesh. + internal virtual bool TryGetWorldBounds(Component sourceComponent, out Bounds worldBounds) + { + worldBounds = default; + return false; + } + /// /// Called for each component on a ShadowCaster2D's GameObject. Returns true if the provided component is the data source of the ShadowShapeProvider. /// diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DColliderCullingTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DColliderCullingTests.cs new file mode 100644 index 00000000000..568a182f73b --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DColliderCullingTests.cs @@ -0,0 +1,201 @@ +#if USING_PHYSICS2D +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering.Universal; + +namespace UnityEditor.Rendering.Universal.Tests +{ + /// + /// UUM-147033: a ShadowCaster2D whose casting source is a Collider2D must keep one bounding sphere + /// whichever camera rendered last. + /// + /// Every camera shares the caster's shadow mesh, and ShadowShape2DProvider_Collider2D culls that mesh + /// to the bounds of the camera being rendered. ShadowCaster2D.Update used to size the bounding sphere + /// from the culled mesh, and IsLit tests lights against that sphere. So after a small camera (the + /// Game view, or the Inspector preview camera) the sphere shrank, and the next view skipped the shadow + /// for lights outside it. In the Editor this showed as shadows that flicker between views. + /// + [TestFixture] + class ShadowCaster2DColliderCullingTests + { + const float k_Tolerance = 0.01f; + + GameObject m_GameObject; + + [TearDown] + public void TearDown() + { + Object.DestroyImmediate(m_GameObject); + } + + static Vector2[] Box(float centerX, float centerY) + { + return new[] + { + new Vector2(centerX - 1, centerY - 1), new Vector2(centerX + 1, centerY - 1), + new Vector2(centerX + 1, centerY + 1), new Vector2(centerX - 1, centerY + 1) + }; + } + + // Two separate boxes, like the far ends of a tilemap collider. Two shapes are needed, because the + // provider culls whole shapes, so a single box is never trimmed. + static PolygonCollider2D AddTwoBoxCollider(GameObject gameObject, float leftX, float rightX) + { + var collider = gameObject.AddComponent(); + collider.pathCount = 2; + collider.SetPath(0, Box(leftX, 0)); + collider.SetPath(1, Box(rightX, 0)); + return collider; + } + + static ShadowCaster2D AddColliderCaster(GameObject gameObject, Component collider) + { + var caster = gameObject.AddComponent(); + caster.shadowCastingSource = ShadowCaster2D.ShadowCastingSources.ShapeProvider; + caster.shadowShape2DComponent = collider; + caster.shadowShape2DProvider = new ShadowShape2DProvider_Collider2D(); + caster.m_ForceShadowMeshRebuild = true; + caster.Update(); + return caster; + } + + static void RenderWithCullingBounds(ShadowCaster2D caster, Bounds cullingBounds) + { + ShapeProviderUtility.CallOnBeforeRender(caster.shadowShape2DProvider, caster.shadowShape2DComponent, caster.m_ShadowMesh, cullingBounds); + caster.Update(); + } + + static void AssertSameSphere(BoundingSphere expected, BoundingSphere actual) + { + Assert.That(actual.radius, Is.EqualTo(expected.radius).Within(k_Tolerance), + $"The bounding sphere changed with the last camera's culling bounds (center {actual.position}, radius {actual.radius}; " + + $"expected center {expected.position}, radius {expected.radius}). IsLit then rejects lights the other views still need."); + Assert.That(Vector3.Distance(actual.position, expected.position), Is.LessThan(k_Tolerance), + $"The bounding sphere center moved to {actual.position} (expected {expected.position})."); + } + + static void AssertCovers(BoundingSphere sphere, Vector2 point) + { + var distance = Vector2.Distance(new Vector2(sphere.position.x, sphere.position.y), point); + Assert.That(distance, Is.LessThanOrEqualTo(sphere.radius + k_Tolerance), + $"The bounding sphere (center {sphere.position}, radius {sphere.radius}) does not cover {point}."); + } + + [Test] + public void ColliderShadowCaster_BoundingSphere_DoesNotDependOnLastCameraCullingBounds() + { + m_GameObject = new GameObject("UUM-147033 Caster"); + var collider = AddTwoBoxCollider(m_GameObject, -20, 20); + var caster = AddColliderCaster(m_GameObject, collider); + + // A camera that sees the whole collider, like a zoomed-out Scene view. + RenderWithCullingBounds(caster, new Bounds(Vector3.zero, new Vector3(100, 100, 1000))); + var fullSphere = caster.boundingSphere; + + // A small camera that sees only the left box, like the Game view or the Inspector preview. + RenderWithCullingBounds(caster, new Bounds(new Vector3(-20, 0, 0), new Vector3(4, 4, 1000))); + AssertSameSphere(fullSphere, caster.boundingSphere); + + // The sphere covers both boxes. The radius is sqrt(21^2 + 1^2) plus the polygon skin radius. + Assert.That(Vector2.Distance(fullSphere.position, Vector2.zero), Is.LessThan(k_Tolerance), $"Center is {fullSphere.position}."); + Assert.That(fullSphere.radius, Is.GreaterThanOrEqualTo(21f)); + } + + [Test] + public void ColliderShadowCaster_OffsetFromOrigin_BoundingSphereUnchangedWhenViewMissesCollider() + { + m_GameObject = new GameObject("UUM-147033 Offset Caster"); + var collider = AddTwoBoxCollider(m_GameObject, 100, 140); + var caster = AddColliderCaster(m_GameObject, collider); + + // A view at the GameObject origin that sees none of the collider. The provider empties the mesh, + // but the sphere must still cover both boxes. + var missView = new Bounds(Vector3.zero, new Vector3(10, 10, 1000)); + RenderWithCullingBounds(caster, missView); + var missSphere = caster.boundingSphere; + Assert.That(Vector2.Distance(missSphere.position, new Vector2(120, 0)), Is.LessThan(k_Tolerance), $"Center is {missSphere.position}."); + Assert.That(missSphere.radius, Is.GreaterThanOrEqualTo(21f)); + + RenderWithCullingBounds(caster, new Bounds(new Vector3(120, 0, 0), new Vector3(100, 100, 1000))); + AssertSameSphere(missSphere, caster.boundingSphere); + + RenderWithCullingBounds(caster, new Bounds(new Vector3(140, 0, 0), new Vector3(4, 4, 1000))); + AssertSameSphere(missSphere, caster.boundingSphere); + + RenderWithCullingBounds(caster, missView); + AssertSameSphere(missSphere, caster.boundingSphere); + } + + [Test] + public void ColliderShadowCaster_RotatedRigidbody_BoundingSphereCoversRotatedShapes() + { + m_GameObject = new GameObject("UUM-147033 Rotated Caster"); + m_GameObject.transform.SetPositionAndRotation(new Vector3(5, 5, 0), Quaternion.Euler(0, 0, 90)); + var body = m_GameObject.AddComponent(); + body.bodyType = RigidbodyType2D.Kinematic; + var collider = AddTwoBoxCollider(m_GameObject, 10, 50); + var caster = AddColliderCaster(m_GameObject, collider); + + RenderWithCullingBounds(caster, new Bounds(new Vector3(5, 35, 0), new Vector3(100, 100, 1000))); + var fullSphere = caster.boundingSphere; + + // Rotating by 90 degrees about (5,5) moves the boxes at local x=10 and x=50 to world (5,15) and (5,55). + foreach (var center in new[] { new Vector2(5, 15), new Vector2(5, 55) }) + foreach (var corner in Box(center.x, center.y)) + AssertCovers(fullSphere, corner); + + // A small view on the lower box only. + RenderWithCullingBounds(caster, new Bounds(new Vector3(5, 15, 0), new Vector3(4, 4, 1000))); + AssertSameSphere(fullSphere, caster.boundingSphere); + } + + [Test] + public void ColliderShadowCaster_DisabledOrEmptyCollider_FallsBackWithoutExceptions() + { + m_GameObject = new GameObject("UUM-147033 Disabled Caster"); + var collider = AddTwoBoxCollider(m_GameObject, -20, 20); + var caster = AddColliderCaster(m_GameObject, collider); + var provider = caster.shadowShape2DProvider; + var wholeView = new Bounds(Vector3.zero, new Vector3(100, 100, 1000)); + RenderWithCullingBounds(caster, wholeView); + Assert.That(provider.TryGetWorldBounds(collider, out _), Is.True, "An enabled collider with shapes gives bounds."); + + collider.enabled = false; + Assert.DoesNotThrow(() => RenderWithCullingBounds(caster, wholeView)); + Assert.That(provider.TryGetWorldBounds(collider, out _), Is.False, "A disabled collider gives no bounds."); + + // Re-enabled with no shapes, like a TilemapCollider2D merged into a CompositeCollider2D. + collider.enabled = true; + collider.pathCount = 0; + Assert.DoesNotThrow(() => RenderWithCullingBounds(caster, wholeView)); + Assert.That(provider.TryGetWorldBounds(collider, out _), Is.False, "A collider with no shapes gives no bounds."); + + // Shapes come back: the bounds are read again, not reused from before. + collider.pathCount = 1; + collider.SetPath(0, Box(60, 0)); + Assert.DoesNotThrow(() => RenderWithCullingBounds(caster, new Bounds(new Vector3(60, 0, 0), new Vector3(100, 100, 1000)))); + Assert.That(provider.TryGetWorldBounds(collider, out var bounds), Is.True); + Assert.That(Vector2.Distance(bounds.center, new Vector2(60, 0)), Is.LessThan(k_Tolerance), $"Bounds center is {bounds.center}."); + Assert.That(Vector2.Distance(caster.boundingSphere.position, new Vector2(60, 0)), Is.LessThan(k_Tolerance)); + } + + [Test] + public void ColliderShadowCaster_NullProviderOrComponent_DoesNotThrow() + { + m_GameObject = new GameObject("UUM-147033 Null Caster"); + var collider = AddTwoBoxCollider(m_GameObject, -20, 20); + var caster = AddColliderCaster(m_GameObject, collider); + + caster.shadowShape2DComponent = null; + Assert.DoesNotThrow(() => caster.Update(), "Null component"); + + caster.shadowShape2DComponent = collider; + caster.shadowShape2DProvider = null; + Assert.DoesNotThrow(() => caster.Update(), "Null provider"); + + caster.shadowShape2DComponent = null; + Assert.DoesNotThrow(() => caster.Update(), "Null provider and component"); + } + } +} +#endif diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DColliderCullingTests.cs.meta b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DColliderCullingTests.cs.meta new file mode 100644 index 00000000000..abb02b3aad1 --- /dev/null +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShadowCaster2DColliderCullingTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7c1e4a9b3f2d4e6a8b5c0d9e1f2a3b47 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Unity.RenderPipelines.Universal.Editor.Tests.asmdef b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Unity.RenderPipelines.Universal.Editor.Tests.asmdef index 29f8d15e213..0829f5ca2f0 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/Unity.RenderPipelines.Universal.Editor.Tests.asmdef +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/Unity.RenderPipelines.Universal.Editor.Tests.asmdef @@ -26,6 +26,12 @@ "defineConstraints": [ "UNITY_INCLUDE_TESTS" ], - "versionDefines": [], + "versionDefines": [ + { + "name": "com.unity.modules.physics2d", + "expression": "0.0.0", + "define": "USING_PHYSICS2D" + } + ], "noEngineReferences": false } \ No newline at end of file From b6c189959323e4948d8a023ba7449f3ede2fed9c Mon Sep 17 00:00:00 2001 From: Reach Platform Support Date: Wed, 28 Oct 2026 20:57:07 +0000 Subject: [PATCH 03/18] [Port] [6000.3] Avoid miscompilation in ANGLE DX11 backend in URP clustering code --- .../ShaderLibrary/Clustering.hlsl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Clustering.hlsl b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Clustering.hlsl index a9a5410bca2..6cdc64a0a43 100644 --- a/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Clustering.hlsl +++ b/Packages/com.unity.render-pipelines.universal/ShaderLibrary/Clustering.hlsl @@ -107,7 +107,7 @@ ClusterIterator ClusterInit(float2 normalizedScreenSpaceUV, float3 positionWS, i #if !URP_FP_DISABLE_ZBINNING Select4(asuint(urp_ZBins[zBinWordIndex / 4]), zBinWordIndex % 4) & #endif - (0xFFFFFFFFu << (header & 0x1F)) & (0xFFFFFFFFu >> (31 - (header >> 16))); + (0xFFFFFFFFu << (header & 0x1F)) & ~(0xFFFFFFFEu << (header >> 16)); } #endif @@ -133,7 +133,7 @@ bool ClusterNext(inout ClusterIterator it, out uint entityIndex) Select4(asuint(urp_ZBins[zBinWordIndex / 4]), zBinWordIndex % 4) & #endif // Mask out the beginning and end of the word. - (0xFFFFFFFFu << (it.entityIndexNextMax & 0x1F)) & (0xFFFFFFFFu >> (31 - min(31, maxIndex - wordIndex * 32))); + (0xFFFFFFFFu << (it.entityIndexNextMax & 0x1F)) & ~(0xFFFFFFFEu << min(31, maxIndex - wordIndex * 32)); // The light index can start at a non-multiple of 32, but the following iterations should always be multiples of 32. // So we add 32 and mask out the lower bits. it.entityIndexNextMax = (it.entityIndexNextMax + 32) & ~31; From dc9182b59751f42a9b541b3bf2d41f5cffd39800 Mon Sep 17 00:00:00 2001 From: Yohann Vaast Date: Wed, 28 Oct 2026 20:57:09 +0000 Subject: [PATCH 04/18] [Port] [6000.3] [UUM-158401] [SRP] Apply the native subpass limit to native subpasses, not Render Graph passes --- .../RenderGraph/Compiler/PassesData.cs | 25 ++++- .../NativePassCompilerRenderGraphTests.cs | 101 ++++++++++++++++++ 2 files changed, 121 insertions(+), 5 deletions(-) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/PassesData.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/PassesData.cs index 7cbebad62d1..bae75d69696 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/PassesData.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/PassesData.cs @@ -747,12 +747,18 @@ public SubPassFlags GetSubPassFlagForMerging() throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_CannotDetermineSubPassFlagNoDepth); } + // Depth attachment is always at index 0. + return GetSubPassFlagForMerging(fragments[0].accessFlags); + } + + // Same as above, from the access flags of the native pass depth attachment. + static SubPassFlags GetSubPassFlagForMerging(AccessFlags depthAccessFlags) + { // Only do this for mobile using Vulkan. #if (PLATFORM_ANDROID) if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Vulkan) { - // Depth attachment is always at index 0. - return (fragments[0].accessFlags.HasFlag(AccessFlags.Write)) ? SubPassFlags.None : SubPassFlags.ReadOnlyDepth; + return (depthAccessFlags.HasFlag(AccessFlags.Write)) ? SubPassFlags.None : SubPassFlags.ReadOnlyDepth; } else { @@ -1048,8 +1054,9 @@ public static PassBreakAudit CanMerge(CompilerContextData contextData, int activ } // We check first if we are at risk of having too many subpasses, - // only then we do the costlier subpass merging check, short circuiting it whenever possible - bool canAddAnExtraSubpass = (nativePass.numGraphPasses < NativePassCompiler.k_MaxSubpass); + // only then we do the costlier subpass merging check, short circuiting it whenever possible. + // The limit is on native subpasses: graph passes merged into the same native subpass don't count. + bool canAddAnExtraSubpass = (nativePass.numNativeSubPasses < NativePassCompiler.k_MaxSubpass); if (!canAddAnExtraSubpass && !CanMergeNativeSubPass(contextData, ref nativePass, ref passToMerge)) { return new PassBreakAudit(PassBreakReason.SubPassLimitReached, passIdToMerge); @@ -1199,8 +1206,16 @@ static bool CanMergeNativeSubPass(CompilerContextData contextData, ref NativePas inputIndex++; } + // If the native pass gets its depth attachment from this merge, TryMerge adds it first and updates + // the flags of the existing subpasses, the last one included (see AddDepthAttachmentFirstDuringMerge) + SubPassFlags lastPassFlags = lastPass.flags; + if (currRenderGraphPassHasDepth && !nativePass.hasDepth) + { + lastPassFlags |= GetSubPassFlagForMerging(contextData.fragmentData[passToMerge.firstFragment].accessFlags); + } + // last check for flags - return flags == lastPass.flags; + return flags == lastPassFlags; } // Try to merge the new graph pass into the last native sub pass or create a new one in the current native pass. diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/NativePassCompilerRenderGraphTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/NativePassCompilerRenderGraphTests.cs index a06a82f9e28..5adfc0703c1 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/NativePassCompilerRenderGraphTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/NativePassCompilerRenderGraphTests.cs @@ -743,6 +743,107 @@ public void NativeSubPassesLimitNotExceeded() Assert.AreEqual(Rendering.RenderGraphModule.NativeRenderPassCompiler.PassBreakReason.SubPassLimitReached, passes[0].breakAudit.reason); } + [Test] + public void NativeSubPassesLimitIgnoresGraphPassesMergedIntoSameSubPass() + { + var g = AllocateRenderGraph(); + var renderTargets = ImportAndCreateRenderTargets(g); + + // More graph passes than the native subpasses limit, all using the same attachments so they share a single native subpass + for (int i = 0; i < Rendering.RenderGraphModule.NativeRenderPassCompiler.NativePassCompiler.k_MaxSubpass + 2; i++) + { + using (var builder = g.AddRasterRenderPass($"TestPass_{i}", out var passData)) + { + builder.SetRenderAttachmentDepth(renderTargets.extraDepthBuffer, AccessFlags.Write); + builder.SetRenderAttachment(renderTargets.extraTextures[0], 0, AccessFlags.Write); + builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { }); + builder.AllowPassCulling(false); + } + } + + // Different color attachment, so this graph pass needs a second native subpass + using (var builder = g.AddRasterRenderPass("TestPass_NewSubPass", out var passData)) + { + builder.SetRenderAttachmentDepth(renderTargets.extraDepthBuffer, AccessFlags.Write); + builder.SetRenderAttachment(renderTargets.extraTextures[1], 0, AccessFlags.Write); + builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { }); + builder.AllowPassCulling(false); + } + + var result = g.CompileNativeRenderGraph(g.ComputeGraphHash()); + var passes = result.contextData.GetNativePasses(); + + Assert.AreEqual(1, passes.Count); + Assert.AreEqual(Rendering.RenderGraphModule.NativeRenderPassCompiler.NativePassCompiler.k_MaxSubpass + 3, passes[0].numGraphPasses); + Assert.AreEqual(2, passes[0].numNativeSubPasses); + } + + [Test] + public void NativeSubPassesLimitReachedWithMultipleGraphPassesPerSubPass() + { + var g = AllocateRenderGraph(); + var renderTargets = ImportAndCreateRenderTargets(g); + + // Two graph passes per native subpass, alternating the color attachment so that each pair needs a new native subpass, + // one pair more than the native subpasses limit + for (int i = 0; i < 2 * (Rendering.RenderGraphModule.NativeRenderPassCompiler.NativePassCompiler.k_MaxSubpass + 1); i++) + { + using (var builder = g.AddRasterRenderPass($"TestPass_{i}", out var passData)) + { + builder.SetRenderAttachmentDepth(renderTargets.extraDepthBuffer, AccessFlags.Write); + builder.SetRenderAttachment(renderTargets.extraTextures[(i / 2) % 2], 0, AccessFlags.Write); + builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { }); + builder.AllowPassCulling(false); + } + } + + var result = g.CompileNativeRenderGraph(g.ComputeGraphHash()); + var passes = result.contextData.GetNativePasses(); + + Assert.AreEqual(2, passes.Count); + Assert.AreEqual(2 * Rendering.RenderGraphModule.NativeRenderPassCompiler.NativePassCompiler.k_MaxSubpass, passes[0].numGraphPasses); + Assert.AreEqual(Rendering.RenderGraphModule.NativeRenderPassCompiler.NativePassCompiler.k_MaxSubpass, passes[0].numNativeSubPasses); + Assert.AreEqual(Rendering.RenderGraphModule.NativeRenderPassCompiler.PassBreakReason.SubPassLimitReached, passes[0].breakAudit.reason); + Assert.AreEqual(2, passes[1].numGraphPasses); + Assert.AreEqual(1, passes[1].numNativeSubPasses); + } + + [Test] + public void NativeSubPassesLimitNotExceededWhenMergedPassAddsDepth() + { + var g = AllocateRenderGraph(); + var renderTargets = ImportAndCreateRenderTargets(g); + + // As many graph passes as the native subpasses limit, without depth and alternating the color attachment, so one native subpass each + for (int i = 0; i < Rendering.RenderGraphModule.NativeRenderPassCompiler.NativePassCompiler.k_MaxSubpass; i++) + { + using (var builder = g.AddRasterRenderPass($"TestPass_{i}", out var passData)) + { + builder.SetRenderAttachment(renderTargets.extraTextures[i % 2], 0, AccessFlags.Write); + builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { }); + builder.AllowPassCulling(false); + } + } + + // Same color attachment as the last native subpass, but this graph pass brings the depth attachment of the native pass, + // which changes the flags of the existing native subpasses when merged + using (var builder = g.AddRasterRenderPass("TestPass_AddsDepth", out var passData)) + { + builder.SetRenderAttachmentDepth(renderTargets.extraDepthBuffer, AccessFlags.Write); + builder.SetRenderAttachment(renderTargets.extraTextures[(Rendering.RenderGraphModule.NativeRenderPassCompiler.NativePassCompiler.k_MaxSubpass - 1) % 2], 0, AccessFlags.Write); + builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { }); + builder.AllowPassCulling(false); + } + + var result = g.CompileNativeRenderGraph(g.ComputeGraphHash()); + var passes = result.contextData.GetNativePasses(); + + foreach (var pass in passes) + { + Assert.LessOrEqual(pass.numNativeSubPasses, Rendering.RenderGraphModule.NativeRenderPassCompiler.NativePassCompiler.k_MaxSubpass); + } + } + [Test] public void AllocateFreeInMergedPassesWorks() { From e9357468fef6d5162f1df2f7eeed4470a05e0d4e Mon Sep 17 00:00:00 2001 From: Rose Hirigoyen Date: Sat, 31 Oct 2026 12:38:50 +0000 Subject: [PATCH 05/18] [Port] [6000.3] [UUM-147726] Fix render requests to cubemaps rendering nothing --- .../Runtime/UniversalRenderPipeline.cs | 4 + .../Tests/Runtime/RuntimeTests.cs | 91 +++++++++++++++++++ 2 files changed, 95 insertions(+) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs index d6c7e30e790..a6e3d3f9005 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs @@ -586,6 +586,10 @@ protected override void ProcessRenderRequests(ScriptableRenderConte RTDesc.width = Mathf.Max(1, RTDesc.width); RTDesc.height = Mathf.Max(1, RTDesc.height); + RTDesc.depthStencilFormat = destination.depthStencilFormat; + if (RTDesc.depthStencilFormat == GraphicsFormat.None) + RTDesc.depthStencilFormat = CoreUtils.GetDefaultDepthStencilFormat(); + //if mip is 0 and target is Texture2D we can immediately render to the requested destination if(destination.dimension != TextureDimension.Tex2D || mipLevel != 0) { diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs index 1bca05b7aa3..00f16b8a09a 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs @@ -12,6 +12,7 @@ class RuntimeTests Camera camera; RenderPipelineAsset currentAssetGraphics; RenderPipelineAsset currentAssetQuality; + RenderTexture m_Destination; [SetUp] public void Setup() @@ -28,6 +29,12 @@ public void Cleanup() GraphicsSettings.defaultRenderPipeline = currentAssetGraphics; QualitySettings.renderPipeline = currentAssetQuality; Object.DestroyImmediate(go); + if (m_Destination != null) + { + m_Destination.Release(); + Object.DestroyImmediate(m_Destination); + m_Destination = null; + } } // When URP pipeline is active, lightsUseLinearIntensity must match active color space. @@ -49,6 +56,90 @@ public IEnumerator PipelineHasCorrectColorSpace() "GraphicsSettings.lightsUseLinearIntensity must match active color space."); } + [UnityTest] + public IEnumerator RenderRequest_WithCubemapDestination_RendersIntoRequestedFace( + [Values] bool useSingleCameraRequest, + [Values] bool destinationHasDepth) + { + AssetCheck(); + + if ((SystemInfo.copyTextureSupport & CopyTextureSupport.DifferentTypes) == 0) + Assert.Ignore("Render requests into a cubemap require CopyTextureSupport.DifferentTypes."); + + camera.clearFlags = CameraClearFlags.SolidColor; + camera.backgroundColor = Color.red; + camera.cullingMask = 0; + + var depthStencilFormat = destinationHasDepth + ? CoreUtils.GetDefaultDepthStencilFormat() + : UnityEngine.Experimental.Rendering.GraphicsFormat.None; + m_Destination = new RenderTexture(64, 64, UnityEngine.Experimental.Rendering.GraphicsFormat.R8G8B8A8_UNorm, + depthStencilFormat) + { + dimension = TextureDimension.Cube + }; + m_Destination.Create(); + + if (useSingleCameraRequest) + { + RenderPipeline.SubmitRenderRequest(camera, new UniversalRenderPipeline.SingleCameraRequest + { + destination = m_Destination, + face = CubemapFace.PositiveX + }); + } + else + { + RenderPipeline.SubmitRenderRequest(camera, new RenderPipeline.StandardRequest + { + destination = m_Destination, + face = CubemapFace.PositiveX + }); + } + yield return null; + + var faceCopy = new RenderTexture(m_Destination.width, m_Destination.height, 0, m_Destination.graphicsFormat); + Texture2D readback = null; + var previousActive = RenderTexture.active; + try + { + Graphics.CopyTexture(m_Destination, (int)CubemapFace.PositiveX, 0, faceCopy, 0, 0); + + int centerX = faceCopy.width / 2; + int centerY = faceCopy.height / 2; + Color pixel; + + // ReadPixels does not work on WebGPU when the browser lacks JSPI + if (SystemInfo.supportsAsyncGPUReadback) + { + var request = AsyncGPUReadback.Request(faceCopy, 0, TextureFormat.RGBA32); + while (!request.done) + yield return null; + + Assert.IsFalse(request.hasError, "AsyncGPUReadback of the requested cubemap face failed."); + pixel = request.GetData()[centerY * faceCopy.width + centerX]; + } + else + { + readback = new Texture2D(faceCopy.width, faceCopy.height, TextureFormat.RGBA32, false); + RenderTexture.active = faceCopy; + readback.ReadPixels(new Rect(0, 0, faceCopy.width, faceCopy.height), 0, 0); + readback.Apply(); + pixel = readback.GetPixel(centerX, centerY); + } + + Assert.Greater(pixel.r, 0.9f, $"The requested cubemap face does not contain the camera rendering. Pixel: {pixel}"); + } + finally + { + RenderTexture.active = previousActive; + faceCopy.Release(); + Object.DestroyImmediate(faceCopy); + if (readback != null) + Object.DestroyImmediate(readback); + } + } + // When switching to URP it sets "UniversalPipeline" as global shader tag. // When switching to Built-in it sets "" as global shader tag. #if UNITY_EDITOR // TODO This API call does not reset in player From 5316f41ef9fa55283cae1cca0a5021b1a386d104 Mon Sep 17 00:00:00 2001 From: Reach Platform Support Date: Wed, 4 Nov 2026 08:32:06 +0000 Subject: [PATCH 06/18] [Port] [6000.3] [UUM-153768] [URP] [HDRP] Run the material upgrade during a -batchmode -quit import --- .../AssetProcessors/MaterialPostProcessor.cs | 153 +++++++++--------- .../MaterialPostprocessor.cs | 67 ++++---- 2 files changed, 117 insertions(+), 103 deletions(-) diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs index c309c4511f3..8a4868f7fbd 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/AssetProcessors/MaterialPostProcessor.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using UnityEditor.Callbacks; using UnityEditor.Rendering.Analytics; using UnityEditor.Rendering.HighDefinition.Analytics; @@ -115,86 +116,92 @@ static void RegisterUpgraderReimport() EditorApplication.update += () => { if (Time.renderedFrameCount > 0) - { - if (!HDRenderPipeline.isReady) - return; - - bool reimportAllHDShaderGraphsTriggered = false; - bool reimportAllMaterialsTriggered = false; - bool fileExist = true; - // We check the file existence only once to avoid IO operations every frame. - if (s_NeedToCheckProjSettingExistence) - { - fileExist = System.IO.File.Exists(HDProjectSettings.filePath); - s_NeedToCheckProjSettingExistence = false; - } + UpgradeMaterialsIfNeeded(); + }; - //This method is called at opening and when HDRP package change (update of manifest.json) - int curMaterialVersion = HDProjectSettings.materialVersionForUpgrade; - bool scanMaterialsForUpgradeNeeded = (curMaterialVersion < MaterialPostprocessor.k_Migrations.Length) - || (HDProjectSettings.pluginSubTargetLastSeenMaterialVersionsSum < HDShaderUtils.GetHDPluginSubTargetMaterialVersionsSum()); + if (Application.isBatchMode && Environment.CommandLine.Contains("-quit")) + SynchronizationContext.Current?.Post(_ => UpgradeMaterialsIfNeeded(), null); + } - var curHDSubTargetVersion = HDProjectSettings.hdShaderGraphLastSeenVersion; - bool scanHDShaderGraphsForUpgradeNeeded = (curHDSubTargetVersion < MigrationDescription.LastVersion()) - || (HDProjectSettings.pluginSubTargetLastSeenSubTargetVersionsSum < HDShaderUtils.GetHDPluginSubTargetVersionsSum()); + static void UpgradeMaterialsIfNeeded() + { + if (!HDRenderPipeline.isReady) + return; - // First test if scan for shadergraph version upgrade might be needed (triggered through their importer) - // We do shadergraphs first as the HDMetaData object might need to be updated and the material update might depend - // on it. - // Note: this auto-update is disabled by default for now. - if (s_AutoReimportProjectShaderGraphsOnVersionUpdate && scanHDShaderGraphsForUpgradeNeeded) - { - string commandLineOptions = System.Environment.CommandLine; - bool inTestSuite = commandLineOptions.Contains("-testResults"); - if (!inTestSuite && fileExist && !Application.isBatchMode) - { - EditorUtility.DisplayDialog("HDRP ShaderGraph scan for upgrade", "The ShaderGraphs with HDRP SubTarget in your Project were created using an older version of the High Definition Render Pipeline (HDRP)." + - " Unity must upgrade them to be compatible with your current version of HDRP. \n" + - " Unity will re-import all of the HDRP ShaderGraphs in your project, save them to disk, and check them out in source control if needed.\n" + - " Please see the Material upgrade guide in the HDRP documentation for more information.", "OK"); - } + bool reimportAllHDShaderGraphsTriggered = false; + bool reimportAllMaterialsTriggered = false; + bool fileExist = true; + // We check the file existence only once to avoid IO operations every frame. + if (s_NeedToCheckProjSettingExistence) + { + fileExist = System.IO.File.Exists(HDProjectSettings.filePath); + s_NeedToCheckProjSettingExistence = false; + } - // When we open a project from scratch all the material have been converted and we don't need to do it two time. - // However if we update with an open editor from the package manager we must call reimport. - // As we can't know, we are always calling reimport resulting in unecessary work when opening a project. - ReimportAllHDShaderGraphs(); - reimportAllHDShaderGraphsTriggered = true; - } - // we do else here, as we want to first call SaveAssetsToDisk() for shadergraphs, as it updates the HDProjectSettings version sentinels - // (tocheck: it's probably safe to also do materials right after) - else if (scanMaterialsForUpgradeNeeded) - { - string commandLineOptions = System.Environment.CommandLine; - bool inTestSuite = commandLineOptions.Contains("-testResults"); - if (!inTestSuite && fileExist && !Application.isBatchMode) - { - EditorUtility.DisplayDialog("HDRP Material upgrade", "The Materials in your Project were created using an older version of the High Definition Render Pipeline (HDRP)." + - " Unity must upgrade them to be compatible with your current version of HDRP. \n" + - " Unity will re-import all of the Materials in your project, save the upgraded Materials to disk, and check them out in source control if needed.\n" + - " Please see the Material upgrade guide in the HDRP documentation for more information.", "OK"); - } + //This method is called at opening and when HDRP package change (update of manifest.json) + int curMaterialVersion = HDProjectSettings.materialVersionForUpgrade; + bool scanMaterialsForUpgradeNeeded = (curMaterialVersion < MaterialPostprocessor.k_Migrations.Length) + || (HDProjectSettings.pluginSubTargetLastSeenMaterialVersionsSum < HDShaderUtils.GetHDPluginSubTargetMaterialVersionsSum()); - // When we open a project from scratch all the material have been converted and we don't need to do it two time. - // However if we update with an open editor from the package manager we must call reimport. - // As we can't know, we are always calling reimport resulting in unecessary work when opening a project. - ReimportAllMaterials(); - reimportAllMaterialsTriggered = true; - } + var curHDSubTargetVersion = HDProjectSettings.hdShaderGraphLastSeenVersion; + bool scanHDShaderGraphsForUpgradeNeeded = (curHDSubTargetVersion < MigrationDescription.LastVersion()) + || (HDProjectSettings.pluginSubTargetLastSeenSubTargetVersionsSum < HDShaderUtils.GetHDPluginSubTargetVersionsSum()); - // Note: A reimport all above should really have gone through all .mat or .shadergraph, because the SaveAssetsToDisk() call will update - // our versions in HDProjectSettings on which we base the version change detection and trigger the scan for reimport. - // We can still have these two flags set at the same time, however, if the user multi-selects .mat and .shadergraph, - // as the MaterialPostProcessor.OnPostprocessAllAssets() will be called for both and set both of those flags if needed. - // This should be safe however since by the time we reach this point here, we already checked if we needed a re-import scan just - // above. - if (MaterialPostprocessor.s_NeedsSavingAssets) - { - MaterialPostprocessor.SaveAssetsToDisk(updateMaterialLastSeenVersions: reimportAllMaterialsTriggered, updateShaderGraphLastSeenVersions: reimportAllHDShaderGraphsTriggered); - reimportAllHDShaderGraphsTriggered = false; - reimportAllMaterialsTriggered = false; - } + // First test if scan for shadergraph version upgrade might be needed (triggered through their importer) + // We do shadergraphs first as the HDMetaData object might need to be updated and the material update might depend + // on it. + // Note: this auto-update is disabled by default for now. + if (s_AutoReimportProjectShaderGraphsOnVersionUpdate && scanHDShaderGraphsForUpgradeNeeded) + { + string commandLineOptions = System.Environment.CommandLine; + bool inTestSuite = commandLineOptions.Contains("-testResults"); + if (!inTestSuite && fileExist && !Application.isBatchMode) + { + EditorUtility.DisplayDialog("HDRP ShaderGraph scan for upgrade", "The ShaderGraphs with HDRP SubTarget in your Project were created using an older version of the High Definition Render Pipeline (HDRP)." + + " Unity must upgrade them to be compatible with your current version of HDRP. \n" + + " Unity will re-import all of the HDRP ShaderGraphs in your project, save them to disk, and check them out in source control if needed.\n" + + " Please see the Material upgrade guide in the HDRP documentation for more information.", "OK"); } - }; + + // When we open a project from scratch all the material have been converted and we don't need to do it two time. + // However if we update with an open editor from the package manager we must call reimport. + // As we can't know, we are always calling reimport resulting in unecessary work when opening a project. + ReimportAllHDShaderGraphs(); + reimportAllHDShaderGraphsTriggered = true; + } + // we do else here, as we want to first call SaveAssetsToDisk() for shadergraphs, as it updates the HDProjectSettings version sentinels + // (tocheck: it's probably safe to also do materials right after) + else if (scanMaterialsForUpgradeNeeded) + { + string commandLineOptions = System.Environment.CommandLine; + bool inTestSuite = commandLineOptions.Contains("-testResults"); + if (!inTestSuite && fileExist && !Application.isBatchMode) + { + EditorUtility.DisplayDialog("HDRP Material upgrade", "The Materials in your Project were created using an older version of the High Definition Render Pipeline (HDRP)." + + " Unity must upgrade them to be compatible with your current version of HDRP. \n" + + " Unity will re-import all of the Materials in your project, save the upgraded Materials to disk, and check them out in source control if needed.\n" + + " Please see the Material upgrade guide in the HDRP documentation for more information.", "OK"); + } + + // When we open a project from scratch all the material have been converted and we don't need to do it two time. + // However if we update with an open editor from the package manager we must call reimport. + // As we can't know, we are always calling reimport resulting in unecessary work when opening a project. + ReimportAllMaterials(); + reimportAllMaterialsTriggered = true; + } + + // Note: A reimport all above should really have gone through all .mat or .shadergraph, because the SaveAssetsToDisk() call will update + // our versions in HDProjectSettings on which we base the version change detection and trigger the scan for reimport. + // We can still have these two flags set at the same time, however, if the user multi-selects .mat and .shadergraph, + // as the MaterialPostProcessor.OnPostprocessAllAssets() will be called for both and set both of those flags if needed. + // This should be safe however since by the time we reach this point here, we already checked if we needed a re-import scan just + // above. + if (MaterialPostprocessor.s_NeedsSavingAssets) + { + MaterialPostprocessor.SaveAssetsToDisk(updateMaterialLastSeenVersions: reimportAllMaterialsTriggered, updateShaderGraphLastSeenVersions: reimportAllHDShaderGraphsTriggered); + reimportAllHDShaderGraphsTriggered = false; + reimportAllMaterialsTriggered = false; + } } } diff --git a/Packages/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/MaterialPostprocessor.cs b/Packages/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/MaterialPostprocessor.cs index 0ba9bca43f2..7cce2c0b650 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/MaterialPostprocessor.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/AssetPostProcessors/MaterialPostprocessor.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using UnityEditor.Callbacks; using UnityEditor.Rendering.Analytics; using UnityEditor.Rendering.Universal.Analytics; @@ -44,42 +45,48 @@ static void RegisterUpgraderReimport() { EditorApplication.update += () => { - if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset universalRenderPipeline) - return; - if (Time.renderedFrameCount > 0) - { - bool fileExist = true; - // We check the file existence only once to avoid IO operations every frame. - if (s_NeedToCheckProjSettingExistence) - { - fileExist = System.IO.File.Exists(UniversalProjectSettings.filePath); - s_NeedToCheckProjSettingExistence = false; - } + UpgradeMaterialsIfNeeded(); + }; - //This method is called at opening and when URP package change (update of manifest.json) - var curUpgradeVersion = UniversalProjectSettings.materialVersionForUpgrade; + if (Application.isBatchMode && Environment.CommandLine.Contains("-quit")) + SynchronizationContext.Current?.Post(_ => UpgradeMaterialsIfNeeded(), null); + } - if (curUpgradeVersion != MaterialPostprocessor.k_Upgraders.Length) - { - string commandLineOptions = Environment.CommandLine; - bool inTestSuite = commandLineOptions.Contains("-testResults"); - bool isTemplate = EditorApplication.isCreateFromTemplate; - if (!inTestSuite && fileExist && !isTemplate) - { - EditorUtility.DisplayDialog("URP Material upgrade", "The Materials in your Project were created using an older version of the Universal Render Pipeline (URP)." + - " Unity must upgrade them to be compatible with your current version of URP. \n" + - " Unity will re-import all of the Materials in your project, save the upgraded Materials to disk, and check them out in source control if needed.\n" + - " Please see the Material upgrade guide in the URP documentation for more information.", "OK"); - } + static void UpgradeMaterialsIfNeeded() + { + if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset universalRenderPipeline) + return; - ReimportAllMaterials(); - } + bool fileExist = true; + // We check the file existence only once to avoid IO operations every frame. + if (s_NeedToCheckProjSettingExistence) + { + fileExist = System.IO.File.Exists(UniversalProjectSettings.filePath); + s_NeedToCheckProjSettingExistence = false; + } - if (MaterialPostprocessor.s_NeedsSavingAssets) - MaterialPostprocessor.SaveAssetsToDisk(); + //This method is called at opening and when URP package change (update of manifest.json) + var curUpgradeVersion = UniversalProjectSettings.materialVersionForUpgrade; + + if (curUpgradeVersion != MaterialPostprocessor.k_Upgraders.Length) + { + string commandLineOptions = Environment.CommandLine; + bool inTestSuite = commandLineOptions.Contains("-testResults"); + bool isTemplate = EditorApplication.isCreateFromTemplate; + if (!inTestSuite && fileExist && !isTemplate && !Application.isBatchMode) + { + EditorUtility.DisplayDialog("URP Material upgrade", "The Materials in your Project were created using an older version of the Universal Render Pipeline (URP)." + + " Unity must upgrade them to be compatible with your current version of URP. \n" + + " Unity will re-import all of the Materials in your project, save the upgraded Materials to disk, and check them out in source control if needed.\n" + + " Please see the Material upgrade guide in the URP documentation for more information.", "OK"); } - }; + + ReimportAllMaterials(); + } + + if (MaterialPostprocessor.s_NeedsSavingAssets) + MaterialPostprocessor.SaveAssetsToDisk(); } } From 7c30305d82bd9da5e6cc8b37a20761e6f5d339b0 Mon Sep 17 00:00:00 2001 From: Reach Platform Support Date: Wed, 4 Nov 2026 08:32:06 +0000 Subject: [PATCH 07/18] [Port] [6000.3] [UUM-159093] Fix 2D sprites and UI not rendering with Depth/Stencil Buffer off on GLES --- .../2D/Rendergraph/DrawNormal2DPass.cs | 2 +- .../2D/Rendergraph/Renderer2DRendergraph.cs | 29 ++++++-- .../Runtime/Renderer2DBackbufferDepthTests.cs | 68 +++++++++++++++++-- 3 files changed, 88 insertions(+), 11 deletions(-) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs index c43497621e3..202197d5c47 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/DrawNormal2DPass.cs @@ -55,7 +55,7 @@ public void Render(RenderGraph graph, ContextContainer frameData, Renderer2DData builder.SetRenderAttachment(universal2DResourceData.normalsTexture[batchIndex], 0); // Depth needed for sprite mask stencil or z test for 3d meshes - if (commonResourceData.activeDepthTexture.IsValid()) + if (Renderer2D.IsDepthUsageAllowed(frameData, rendererData) && commonResourceData.activeDepthTexture.IsValid()) { var depth = universal2DResourceData.normalsDepth.IsValid() ? universal2DResourceData.normalsDepth : commonResourceData.activeDepthTexture; builder.SetRenderAttachmentDepth(depth); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs index 9f74719bf97..096e93f5b6a 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs @@ -169,6 +169,26 @@ internal static bool IsDepthUsageAllowed(ContextContainer frameData, Renderer2DD return allowDepth; } + static bool ShouldImportBackBufferDepth(ContextContainer frameData, Renderer2DData rendererData, bool createColorTexture) + { + if (IsDepthUsageAllowed(frameData, rendererData)) + return true; + + // OpenGL binds the default framebuffer's depth with its color even when no pass uses it, so it must still be cleared (UUM-159093) + var deviceType = SystemInfo.graphicsDeviceType; + if (deviceType != GraphicsDeviceType.OpenGLES3 && deviceType != GraphicsDeviceType.OpenGLCore) + return false; + + // Only when the 2D passes draw straight into the back buffer, since they are what attach and clear it + UniversalCameraData cameraData = frameData.Get(); + bool isBackBuffer = cameraData.targetTexture == null && !createColorTexture; +#if ENABLE_VR && ENABLE_XR_MODULE + isBackBuffer &= !cameraData.xr.enabled; +#endif + + return isBackBuffer && Graphics.backBufferHasDepthStencil; + } + private bool IsPixelPerfectCameraEnabled(UniversalCameraData cameraData, out PixelPerfectCamera ppc) { ppc = null; @@ -498,10 +518,7 @@ void CreateResources(RenderGraph renderGraph) depthDescriptor.depthStencilFormat = CoreUtils.GetDefaultDepthStencilFormat(); RenderingUtils.ReAllocateHandleIfNeeded(ref s_RenderGraphCameraDepthHandle, depthDescriptor, FilterMode.Point, TextureWrapMode.Clamp, name: "_CameraDepthAttachment"); - commonResourceData.activeDepthID = ActiveID.Camera; } - else - commonResourceData.activeDepthID = ActiveID.BackBuffer; } else // Overlay camera { @@ -515,9 +532,11 @@ void CreateResources(RenderGraph renderGraph) m_CreateDepthTexture = baseRenderer.m_CreateDepthTexture; commonResourceData.activeColorID = m_CreateColorTexture ? ActiveID.Camera : ActiveID.BackBuffer; - commonResourceData.activeDepthID = m_CreateDepthTexture ? ActiveID.Camera : ActiveID.BackBuffer; } + // An intermediate color target is never paired with the back buffer depth + commonResourceData.activeDepthID = m_CreateDepthTexture || m_CreateColorTexture ? ActiveID.Camera : ActiveID.BackBuffer; + ImportResourceSummary importSummary = GetImportResourceSummary(renderGraph, cameraData); if (m_CreateColorTexture) @@ -554,7 +573,7 @@ void CreateResources(RenderGraph renderGraph) commonResourceData.backBufferColor = renderGraph.ImportTexture(m_RenderGraphBackbufferColorHandle, importSummary.importInfo, importSummary.backBufferColorParams); - if (IsDepthUsageAllowed(frameData, m_Renderer2DData)) + if (ShouldImportBackBufferDepth(frameData, m_Renderer2DData, m_CreateColorTexture)) { if (m_RenderGraphBackbufferDepthHandle == null) { diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/Renderer2DBackbufferDepthTests.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/Renderer2DBackbufferDepthTests.cs index 95946aed7c8..f0359f1ddc7 100644 --- a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/Renderer2DBackbufferDepthTests.cs +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/Renderer2DBackbufferDepthTests.cs @@ -8,9 +8,10 @@ using UnityEngine.TestTools; // Verifies what the 2D renderer actually puts in the frame's resources when depth usage is disallowed: the -// back buffer depth must not be imported, and the rest of the frame must still record without errors (the -// overlay UI pass in particular reads UniversalResourceData.backBufferDepth and has to cope with it being -// invalid). +// back buffer depth is not imported, except on OpenGL when the 2D passes draw straight into a back buffer that +// has one (there it stays bound with the back buffer color whether a pass asks for it or not, so it must be +// cleared, see UUM-159093), and the rest of the frame must still record without errors (the overlay UI pass in +// particular reads UniversalResourceData.backBufferDepth and has to cope with it being invalid). // // A back buffer with no depth/stencil is not something a test can arrange - it is decided when the surface is // created - so the disallowed case is driven here through the renderer's own "Depth/Stencil Buffer" setting, @@ -100,6 +101,7 @@ public void SetUp() public void TearDown() { RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering; + m_ProbePass.requiresIntermediateTexture = false; if (m_RendererData != null) Renderer2DDepthUsageTests.SetUseDepthStencilBuffer(m_RendererData, m_PreviousUseDepthStencilBuffer); @@ -129,13 +131,44 @@ public IEnumerator BackbufferDepthIsImportedWhenDepthUsageIsAllowed() } [UnityTest] - public IEnumerator BackbufferDepthIsNotImportedWhenDepthUsageIsDisallowed() + public IEnumerator BackbufferDepthIsImportedOnlyOnOpenGLWhenDepthUsageIsDisallowed() { Renderer2DDepthUsageTests.SetUseDepthStencilBuffer(m_RendererData, false); yield return RecordFrame(); + IgnoreIfNotRenderingStraightToTheBackbuffer(); - Assert.IsFalse(m_ProbePass.backBufferDepthIsValid, "The 2D renderer imported the back buffer depth even though depth usage is disallowed."); + // On OpenGL the renderer setting must not drop the back buffer depth: left unimported it is never cleared, + // and draws into the back buffer test against undefined contents (UUM-159093). Elsewhere it is not imported. + Assert.AreEqual(BackbufferDepthStaysBound(), m_ProbePass.backBufferDepthIsValid, + "The imported back buffer depth did not match whether the graphics API keeps it bound with the back buffer color."); + } + + [UnityTest] + public IEnumerator ActiveDepthIsBackbufferDepthOnlyOnOpenGLWhenDepthUsageIsDisallowed() + { + Renderer2DDepthUsageTests.SetUseDepthStencilBuffer(m_RendererData, false); + + yield return RecordFrame(); + IgnoreIfNotRenderingStraightToTheBackbuffer(); + + // The 2D passes attach the active depth, which is what gets the back buffer depth cleared on first use + Assert.AreEqual(BackbufferDepthStaysBound(), m_ProbePass.activeDepthIsBackBufferDepth, + "The active depth did not match the back buffer depth when rendering straight to the back buffer."); + } + + [UnityTest] + public IEnumerator NoActiveDepthWithIntermediateColorWhenDepthUsageIsDisallowed() + { + Renderer2DDepthUsageTests.SetUseDepthStencilBuffer(m_RendererData, false); + m_ProbePass.requiresIntermediateTexture = true; + + yield return RecordFrame(); + + // The intermediate color target must not be paired with the back buffer depth, and the back buffer depth is + // not imported at all since no 2D pass would attach it and get it cleared + Assert.IsFalse(m_ProbePass.activeDepthIsValid, "An active depth was set for the intermediate color target even though depth usage is disallowed."); + Assert.IsFalse(m_ProbePass.backBufferDepthIsValid, "The back buffer depth was imported with an intermediate color target even though depth usage is disallowed."); } [UnityTest] @@ -149,6 +182,22 @@ public IEnumerator RenderingSucceedsWhenDepthUsageIsDisallowed() yield return null; } + // OpenGL binds the default framebuffer's depth with its color, so the renderer imports it to get it cleared. + static bool BackbufferDepthStaysBound() + { + var deviceType = SystemInfo.graphicsDeviceType; + bool isOpenGL = deviceType == GraphicsDeviceType.OpenGLES3 || deviceType == GraphicsDeviceType.OpenGLCore; + return isOpenGL && Graphics.backBufferHasDepthStencil; + } + + // The OpenGL import only applies without an intermediate color target, which the setup cannot rule out everywhere + // (e.g. a non-sRGB back buffer in Linear color space needs one for the sRGB conversion) + void IgnoreIfNotRenderingStraightToTheBackbuffer() + { + if (BackbufferDepthStaysBound() && !m_ProbePass.activeColorIsBackBuffer) + Assert.Ignore("The 2D renderer created an intermediate color target, so it does not render straight to the back buffer."); + } + // Renders frames until the probe pass has recorded one with the current settings. IEnumerator RecordFrame() { @@ -174,6 +223,9 @@ class BackbufferDepthProbePass : ScriptableRenderPass { public bool recorded; public bool backBufferDepthIsValid; + public bool activeDepthIsValid; + public bool activeDepthIsBackBufferDepth; + public bool activeColorIsBackBuffer; public BackbufferDepthProbePass() { @@ -187,6 +239,9 @@ public void Reset() { recorded = false; backBufferDepthIsValid = false; + activeDepthIsValid = false; + activeDepthIsBackBufferDepth = false; + activeColorIsBackBuffer = false; } public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) @@ -195,6 +250,9 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer recorded = true; backBufferDepthIsValid = resourceData.backBufferDepth.IsValid(); + activeDepthIsValid = resourceData.activeDepthTexture.IsValid(); + activeDepthIsBackBufferDepth = activeDepthIsValid && resourceData.activeDepthTexture == resourceData.backBufferDepth; + activeColorIsBackBuffer = resourceData.isActiveTargetBackBuffer; } } } From 7fac31db67a12d58cd0714e051f2f63446a5e374 Mon Sep 17 00:00:00 2001 From: Reach Platform Support Date: Wed, 4 Nov 2026 08:32:06 +0000 Subject: [PATCH 08/18] [Port] [6000.3] Fix incorrect offset of probe occlusion in APV when L2 disabled and disk streaming enabled --- .../Lighting/ProbeVolume/ProbeVolumeScratchBufferPool.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeScratchBufferPool.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeScratchBufferPool.cs index 293d8cfc078..b1abbc19670 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeScratchBufferPool.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeScratchBufferPool.cs @@ -70,7 +70,7 @@ public ProbeVolumeScratchBufferPool(ProbeVolumeBakingSet bakingSet, ProbeVolumeS m_ValidityLayerCount = bakingSet.bakedMaskCount; m_SkyOcclusionSize = bakingSet.sharedSkyOcclusionL0L1ChunkSize; m_SkyShadingDirectionSize = bakingSet.sharedSkyShadingDirectionIndicesChunkSize; - m_L2Size = bakingSet.L2TextureChunkSize; + m_L2Size = shBands == ProbeVolumeSHBands.SphericalHarmonicsL2 ? bakingSet.L2TextureChunkSize : 0; m_ProbeOcclusionSize = bakingSet.ProbeOcclusionChunkSize; } From 3e1b22a48be09a1d1577a07057d0e7f2efcdd223 Mon Sep 17 00:00:00 2001 From: Robert Badea Date: Sat, 7 Nov 2026 16:40:07 +0000 Subject: [PATCH 09/18] [Port] [6000.3] [UUM-159960] [VFX] Fix Custom HLSL function body parsing with leading whitespace --- .../Blocks/Implementations/HLSL/HLSLParser.cs | 7 +-- .../AllTests/Editor/Tests/HLSLParserTest.cs | 52 +++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/Packages/com.unity.visualeffectgraph/Editor/Models/Blocks/Implementations/HLSL/HLSLParser.cs b/Packages/com.unity.visualeffectgraph/Editor/Models/Blocks/Implementations/HLSL/HLSLParser.cs index b2b10bfb543..175bfe19920 100644 --- a/Packages/com.unity.visualeffectgraph/Editor/Models/Blocks/Implementations/HLSL/HLSLParser.cs +++ b/Packages/com.unity.visualeffectgraph/Editor/Models/Blocks/Implementations/HLSL/HLSLParser.cs @@ -249,7 +249,8 @@ static HLSLFunction() public static IEnumerable Parse(IVFXAttributesManager attributesManager, string hlsl) { - var matches = s_FunctionParser.Matches(hlsl.Trim()); + string trimmedHLSL = hlsl.Trim(); + var matches = s_FunctionParser.Matches(trimmedHLSL); for (var i = 0; i < matches.Count; i++) { var match = matches[i]; @@ -257,8 +258,8 @@ public static IEnumerable Parse(IVFXAttributesManager attributesMa if (!isHidden) { var bodyStartIndex = match.Index + match.Length; - var bodyEndIndex = (i + 1) < matches.Count ? matches[i + 1].Index - 1 : hlsl.Length - 1; - var body = hlsl.Substring(bodyStartIndex, bodyEndIndex - bodyStartIndex + 1).TrimEnd(); + var bodyEndIndex = (i + 1) < matches.Count ? matches[i + 1].Index - 1 : trimmedHLSL.Length - 1; + var body = trimmedHLSL.Substring(bodyStartIndex, bodyEndIndex - bodyStartIndex + 1).TrimEnd(); yield return new HLSLFunction(attributesManager, match.Index, diff --git a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/HLSLParserTest.cs b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/HLSLParserTest.cs index 25a1c2898c0..8d26b82ba56 100644 --- a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/HLSLParserTest.cs +++ b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/AllTests/Editor/Tests/HLSLParserTest.cs @@ -420,6 +420,58 @@ public void HLSL_Parameters_On_Different_Lines() Assert.AreEqual(new [] { HLSLAccess.INOUT, HLSLAccess.IN, HLSLAccess.IN }, function.inputs.Select(x => x.access)); } + + [TestCase("\n")] + [TestCase("\r\n")] + [TestCase(" ")] + [TestCase("\t")] + [TestCase("\n\n\n")] + [TestCase(" \n\t\n")] + [Test, Description("Covers issue UUM-158603")] + public void HLSL_Check_Leading_Whitespace(string leadingWhitespace) + { + // Arrange + string hlslCode = leadingWhitespace + + "float FloatFunction(in float value)\n" + + "{\n" + + " return value;\n" + + "}\n"; + + // Act + HLSLFunction function = HLSLFunction.Parse(this.attributesManager, hlslCode).Single(); + + // Assert + Assert.AreEqual("FloatFunction", function.name); + Assert.AreEqual(0, function.index); + Assert.AreEqual("{\n return value;\n}", function.body); + } + + [Test, Description("Covers issue UUM-158603")] + public void HLSL_Check_Leading_Whitespace_Multiple_Functions() + { + // Arrange + string hlslCode = + "\n\n" + + "float First(in float value)\n" + + "{\n" + + " return value;\n" + + "}\n" + + "\n" + + "float Second(in float value)\n" + + "{\n" + + " return value * 2;\n" + + "}\n"; + + // Act + HLSLFunction[] functions = HLSLFunction.Parse(this.attributesManager, hlslCode).ToArray(); + + // Assert + Assert.AreEqual(2, functions.Length); + Assert.AreEqual(0, functions[0].index); + Assert.AreEqual(51, functions[1].index); + Assert.AreEqual("{\n return value;\n}", functions[0].body); + Assert.AreEqual("{\n return value * 2;\n}", functions[1].body); + } } } #endif From 15ed69a97e2b4cb91785ac9356dcc0ffeda1df94 Mon Sep 17 00:00:00 2001 From: Rose Hirigoyen Date: Sat, 7 Nov 2026 16:40:07 +0000 Subject: [PATCH 10/18] [Port] [6000.3] [UUM-147726] Make the cubemap render request test use its own URP asset --- .../Tests/Runtime/RuntimeTests.cs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs index 00f16b8a09a..7bbccadc250 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/RuntimeTests.cs @@ -13,6 +13,8 @@ class RuntimeTests RenderPipelineAsset currentAssetGraphics; RenderPipelineAsset currentAssetQuality; RenderTexture m_Destination; + UniversalRenderPipelineAsset m_TestAsset; + UniversalRendererData m_TestRendererData; [SetUp] public void Setup() @@ -35,6 +37,16 @@ public void Cleanup() Object.DestroyImmediate(m_Destination); m_Destination = null; } + if (m_TestAsset != null) + { + Object.DestroyImmediate(m_TestAsset); + m_TestAsset = null; + } + if (m_TestRendererData != null) + { + Object.DestroyImmediate(m_TestRendererData); + m_TestRendererData = null; + } } // When URP pipeline is active, lightsUseLinearIntensity must match active color space. @@ -66,6 +78,15 @@ public IEnumerator RenderRequest_WithCubemapDestination_RendersIntoRequestedFace if ((SystemInfo.copyTextureSupport & CopyTextureSupport.DifferentTypes) == 0) Assert.Ignore("Render requests into a cubemap require CopyTextureSupport.DifferentTypes."); + // The active quality level can use a debug renderer that overwrites the camera color + m_TestRendererData = ScriptableObject.CreateInstance(); + m_TestRendererData.renderingMode = RenderingMode.Forward; + m_TestAsset = ScriptableObject.CreateInstance(); + m_TestAsset.m_RendererDataList[0] = m_TestRendererData; + QualitySettings.renderPipeline = m_TestAsset; + yield return null; + Assert.AreSame(m_TestAsset, GraphicsSettings.currentRenderPipeline, "The test URP asset is not active."); + camera.clearFlags = CameraClearFlags.SolidColor; camera.backgroundColor = Color.red; camera.cullingMask = 0; From 316f43882c8b061afc6a708845ea56e691fdc7b5 Mon Sep 17 00:00:00 2001 From: Reach Platform Support Date: Sat, 7 Nov 2026 23:03:00 +0000 Subject: [PATCH 11/18] [Port] [6000.3] DOCG-9337 Fix typo in Screen Space Lens Flare --- .../shared/lens-flare/reference-screen-space-lens-flare.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md index c9a62c95c4e..96783b8da15 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md +++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/shared/lens-flare/reference-screen-space-lens-flare.md @@ -16,7 +16,7 @@ Use the **Flares** settings to control regular flares, reversed flares and warpe | ----------------------- | ----------------- | ------------------------------------------------------------ | | **Regular Multiplier** | | Set the strength of regular flares. If the value is 0, HDRP doesn't calculate or render regular flares. The default is 1. | | **Reversed Multiplier** | | Set the strength of reversed flares. If the value is 0, HDRP doesn't calculate or render reversed flares. The default is 1. | -| **Warped Multipler** | | Set the strength of warped flares. If the value is 0, HDRP doesn't calculate or render warped flares. The default is 1. | +| **Warped Multiplier** | | Set the strength of warped flares. If the value is 0, HDRP doesn't calculate or render warped flares. The default is 1. | | | **Scale** | Scale the width (**x**) and height (**y**) of warped flares. The defaults are 1. This property only appears if you open the **More** (⋮) menu and select **Show Additional Properties**. | | **Samples** | | Set the number of times HDRP repeats the regular, reversed and warped flares. The range is 1 through 3. The default is 1. Increasing **Samples** has a big impact on performance. | | | **Sample Dimmer** | Set the strength of the lens flares HDRP adds if you set **Samples** to 2 or 3. The higher the value, the less intense the flares. This property only appears if you open the **More** (⋮) menu and select **Show Additional Properties**. | From 606a2760c9daf82b5313111b04a854547a8e6cfc Mon Sep 17 00:00:00 2001 From: Mikkel Simonsen Date: Tue, 10 Nov 2026 10:03:05 +0000 Subject: [PATCH 12/18] [Port] [6000.3] [UUM-146356] [UUM-154016] [UUM-159132] [URP] Fix Forward+ light clustering --- .../Runtime/ForwardLights.cs | 7 +- .../Runtime/Tiling/LightMinMaxZJob.cs | 10 +- .../Tiling/ReflectionProbeMinMaxZJob.cs | 4 + .../Runtime/Tiling/TilingJob.cs | 899 +++++++++--------- .../Runtime/Tiling/ZBinningJob.cs | 2 + 5 files changed, 453 insertions(+), 469 deletions(-) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs b/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs index 467ddedb150..3371d679f42 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/ForwardLights.cs @@ -298,7 +298,8 @@ static bool IsProbeGreater(VisibleReflectionProbe probe, VisibleReflectionProbe { worldToViews = worldToViews, lights = localLights, - minMaxZs = minMaxZs.GetSubArray(0, localLightCount * viewCount) + minMaxZs = minMaxZs.GetSubArray(0, localLightCount * viewCount), + near = nearClipPlane }; // Innerloop batch count of 32 is not special, just a handwavy amount to not have too much scheduling overhead nor too little parallelism. var lightMinMaxZHandle = lightMinMaxZJob.ScheduleParallel(localLightCount * viewCount, 32, new JobHandle()); @@ -310,7 +311,8 @@ static bool IsProbeGreater(VisibleReflectionProbe probe, VisibleReflectionProbe worldToViews = worldToViews, reflectionProbes = probes, reflectionProbeRotation = reflectionProbeRotation, - minMaxZs = minMaxZs.GetSubArray(localLightCount * viewCount, reflectionProbeCount * viewCount) + minMaxZs = minMaxZs.GetSubArray(localLightCount * viewCount, reflectionProbeCount * viewCount), + near = nearClipPlane }; var reflectionProbeMinMaxZHandle = reflectionProbeMinMaxZJob.ScheduleParallel(reflectionProbeCount * viewCount, 32, lightMinMaxZHandle); @@ -356,6 +358,7 @@ static bool IsProbeGreater(VisibleReflectionProbe probe, VisibleReflectionProbe viewToViewportScaleBiases = new Fixed2(viewToViewportScaleBias0, viewToViewportScaleBias1), tileCount = tileResolution, near = nearClipPlane, + far = farClipPlane, isOrthographic = isOrthographic }; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs index 4bae86b9dc1..b6e1e644e37 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/LightMinMaxZJob.cs @@ -14,6 +14,8 @@ struct LightMinMaxZJob : IJobFor public NativeArray lights; public NativeArray minMaxZs; + public float near; + public void Execute(int index) { var lightIndex = index % lights.Length; @@ -40,7 +42,8 @@ public void Execute(int index) var angleB = math.PI * 0.5f - angleA; var coneRadius = light.range * cosAngleA * math.sin(angleA) / math.sin(angleB); var a = endPointVS - originVS; - var e = math.sqrt(1.0f - a.z * a.z / math.dot(a, a)); + // Saturate: rounding can push the argument slightly below 0, where sqrt returns NaN. + var e = math.sqrt(math.saturate(1.0f - a.z * a.z / math.dot(a, a))); // `-a.z` and `a.z` is `dot(a, {0, 0, -1}).z` and `dot(a, {0, 0, 1}).z` optimized // `cosAngleA` is multiplied by `coneHeight` to avoid normalizing `a`, which we know has length `coneHeight` @@ -55,8 +58,9 @@ public void Execute(int index) minMax.y = float.MinValue; } - minMax.x = math.max(minMax.x, 0); - minMax.y = math.max(minMax.y, 0); + // Clamp to near, not 0: an orthographic near plane can be negative. A light entirely closer than the near + // plane keeps max < min, which ZBinningJob treats as empty. + minMax.x = math.max(minMax.x, near); minMaxZs[index] = minMax; } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs index 30aaaf490de..a7cc93726ea 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ReflectionProbeMinMaxZJob.cs @@ -16,6 +16,8 @@ struct ReflectionProbeMinMaxZJob : IJobFor public bool reflectionProbeRotation; public NativeArray minMaxZs; + public float near; + public void Execute(int index) { var minMax = math.float2(float.MaxValue, float.MinValue); @@ -45,6 +47,8 @@ public void Execute(int index) minMax.y = math.max(minMax.y, cornerVS.z); } + // As in LightMinMaxZJob: a probe entirely closer than the near plane keeps max < min. + minMax.x = math.max(minMax.x, near); minMaxZs[index] = minMax; } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.cs index 800ba60da59..05773bb64eb 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/TilingJob.cs @@ -32,6 +32,7 @@ struct TilingJob : IJobFor public Fixed2 viewToViewportScaleBiases; public int2 tileCount; public float near; + public float far; public bool isOrthographic; InclusiveRange m_TileYRange; @@ -75,7 +76,7 @@ void TileLight(int lightIndex) var lightToWorld = (float4x4)light.localToWorldMatrix; var lightPositionVS = math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c3.xyz, 1)).xyz; lightPositionVS.z *= -1; - if (lightPositionVS.z >= near) ExpandY(lightPositionVS); + if (IsInDepthRange(lightPositionVS)) ExpandY(lightPositionVS); var lightDirectionVS = math.normalize(math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c2.xyz, 0)).xyz); lightDirectionVS.z *= -1; @@ -84,39 +85,25 @@ void TileLight(int lightIndex) var rangesq = square(range); var cosHalfAngle = math.cos(halfAngle); var coneHeight = cosHalfAngle * range; - - // Radius of circle formed by intersection of sphere and near plane. - // Found using Pythagoras with a right triangle formed by three points: - // (a) light position - // (b) light position projected to near plane - // (c) a point on the near plane at a distance `range` from the light position - // (i.e. lies both on the sphere and the near plane) - // Thus the hypotenuse is formed by (a) and (c) with length `range`, and the known side is formed - // by (a) and (b) with length equal to the distance between the near plane and the light position. - // The remaining unknown side is formed by (b) and (c) with length equal to the radius of the circle. - // m_ClipCircleRadius = sqrt(sq(light.range) - sq(m_Near - m_LightPosition.z)); - var sphereClipRadius = math.sqrt(rangesq - square(near - lightPositionVS.z)); - - // Assumes a point on the sphere, i.e. at distance `range` from the light position. - // If spot light, we check the angle between the direction vector from the light position and the light direction vector. - // Note that division by range is to normalize the vector, as we know that the resulting vector will have length `range`. - bool SpherePointIsValid(float3 p) => light.lightType == LightType.Point || - math.dot(math.normalize(p - lightPositionVS), lightDirectionVS) >= cosHalfAngle; - - // Project light sphere onto YZ plane, find the horizon points, and re-construct view space position of found points. - // CalculateSphereYBounds(lightPositionVS, range, near, sphereClipRadius, out var sphereBoundY0, out var sphereBoundY1); - GetSphereHorizon(lightPositionVS.yz, range, near, sphereClipRadius, out var sphereBoundYZ0, out var sphereBoundYZ1); - var sphereBoundY0 = math.float3(lightPositionVS.x, sphereBoundYZ0); - var sphereBoundY1 = math.float3(lightPositionVS.x, sphereBoundYZ1); - if (SpherePointIsValid(sphereBoundY0)) ExpandY(sphereBoundY0); - if (SpherePointIsValid(sphereBoundY1)) ExpandY(sphereBoundY1); - - // Project light sphere onto XZ plane, find the horizon points, and re-construct view space position of found points. - GetSphereHorizon(lightPositionVS.xz, range, near, sphereClipRadius, out var sphereBoundXZ0, out var sphereBoundXZ1); - var sphereBoundX0 = math.float3(sphereBoundXZ0.x, lightPositionVS.y, sphereBoundXZ0.y); - var sphereBoundX1 = math.float3(sphereBoundXZ1.x, lightPositionVS.y, sphereBoundXZ1.y); - if (SpherePointIsValid(sphereBoundX0)) ExpandY(sphereBoundX0); - if (SpherePointIsValid(sphereBoundX1)) ExpandY(sphereBoundX1); + var isSpot = light.lightType == LightType.Spot; + + // Outline of the sphere projected onto the YZ and XZ planes: the horizon as seen from the camera, and the + // extremes of the circles cut by the near and far planes. Missing points are NaN. + GetCircleHorizon(lightPositionVS.yz, range, out var horizonY0, out var horizonY1); + GetCircleHorizon(lightPositionVS.xz, range, out var horizonX0, out var horizonX1); + ExpandYIfInSphereCap(math.float3(lightPositionVS.x, horizonY0), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + ExpandYIfInSphereCap(math.float3(lightPositionVS.x, horizonY1), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + ExpandYIfInSphereCap(math.float3(horizonX0.x, lightPositionVS.y, horizonX0.y), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + ExpandYIfInSphereCap(math.float3(horizonX1.x, lightPositionVS.y, horizonX1.y), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + for (var i = 0; i < 2; i++) + { + var depth = i == 0 ? near : far; + var sectionRadius = math.sqrt(rangesq - square(depth - lightPositionVS.z)); + ExpandYIfInSphereCap(math.float3(lightPositionVS.x, lightPositionVS.y - sectionRadius, depth), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + ExpandYIfInSphereCap(math.float3(lightPositionVS.x, lightPositionVS.y + sectionRadius, depth), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + ExpandYIfInSphereCap(math.float3(lightPositionVS.x - sectionRadius, lightPositionVS.y, depth), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + ExpandYIfInSphereCap(math.float3(lightPositionVS.x + sectionRadius, lightPositionVS.y, depth), lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + } if (light.lightType == LightType.Spot) { @@ -137,8 +124,8 @@ bool SpherePointIsValid(float3 p) => light.lightType == LightType.Point || GetProjectedCircleHorizon(baseCenter.yz, baseRadius, baseUY.yz, baseVY.yz, out var baseY1UV, out var baseY2UV); var baseY1 = baseCenter + baseY1UV.x * baseUY + baseY1UV.y * baseVY; var baseY2 = baseCenter + baseY2UV.x * baseUY + baseY2UV.y * baseVY; - if (baseY1.z >= near) ExpandY(baseY1); - if (baseY2.z >= near) ExpandY(baseY2); + if (IsInDepthRange(baseY1)) ExpandY(baseY1); + if (IsInDepthRange(baseY2)) ExpandY(baseY2); // Project cone base into the XZ plane, find the horizon points, and re-construct view space position of found points. // See comment for YZ plane for details. @@ -147,71 +134,67 @@ bool SpherePointIsValid(float3 p) => light.lightType == LightType.Point || GetProjectedCircleHorizon(baseCenter.xz, baseRadius, baseUX.xz, baseVX.xz, out var baseX1UV, out var baseX2UV); var baseX1 = baseCenter + baseX1UV.x * baseUX + baseX1UV.y * baseVX; var baseX2 = baseCenter + baseX2UV.x * baseUX + baseX2UV.y * baseVX; - if (baseX1.z >= near) ExpandY(baseX1); - if (baseX2.z >= near) ExpandY(baseX2); + if (IsInDepthRange(baseX1)) ExpandY(baseX1); + if (IsInDepthRange(baseX2)) ExpandY(baseX2); - // Handle base circle clipping by intersecting it with the near-plane if needed. + // Handle base circle clipping by intersecting it with the near and far planes if needed. if (GetCircleClipPoints(baseCenter, lightDirectionVS, baseRadius, near, out var baseClip0, out var baseClip1)) { ExpandY(baseClip0); ExpandY(baseClip1); } + if (GetCircleClipPoints(baseCenter, lightDirectionVS, baseRadius, far, out var baseFarClip0, out var baseFarClip1)) + { + ExpandY(baseFarClip0); + ExpandY(baseFarClip1); + } - bool ConicPointIsValid(float3 p) => - math.dot(math.normalize(p - lightPositionVS), lightDirectionVS) >= 0 && - math.dot(p - lightPositionVS, lightDirectionVS) <= coneHeight; + var sinHalfAngle = math.sin(halfAngle); + var coneDistanceTolerance = 1e-5f * (math.length(lightPositionVS) + range); + bool ConicPointIsValid(float3 p) => IsOnCone(p, lightPositionVS, lightDirectionVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance); - // Calculate Z bounds of cone and check if it's overlapping with the near plane. + // Calculate Z bounds of cone and check if it's overlapping with the near and far planes. // From https://www.iquilezles.org/www/articles/diskbbox/diskbbox.htm - var baseExtentZ = baseRadius * math.sqrt(1.0f - square(lightDirectionVS.z)); - var coneIsClipping = near >= math.min(baseCenter.z - baseExtentZ, lightPositionVS.z) && near <= math.max(baseCenter.z + baseExtentZ, lightPositionVS.z); - - var coneU = math.cross(lightDirectionVS, lightPositionVS); - // The cross product will be the 0-vector if the light-direction and camera-to-light-position vectors are parallel. - // In that case, {1, 0, 0} is orthogonal to the light direction and we use that instead. - coneU = math.csum(coneU) != 0f ? math.normalize(coneU) : math.float3(1, 0, 0); + var baseExtentZ = baseRadius * math.sqrt(math.saturate(1.0f - square(lightDirectionVS.z))); + var coneMinZ = math.min(baseCenter.z - baseExtentZ, lightPositionVS.z); + var coneMaxZ = math.max(baseCenter.z + baseExtentZ, lightPositionVS.z); + var coneIsClipping = near >= coneMinZ && near <= coneMaxZ; + var coneCrossesFar = far >= coneMinZ && far <= coneMaxZ; + + // Any frame orthogonal to the axis works; cross with the view axis least aligned with it to keep it well conditioned. + var coneU = math.normalize(math.cross(lightDirectionVS, math.abs(lightDirectionVS.x) < 0.5f ? math.float3(1, 0, 0) : math.float3(0, 1, 0))); var coneV = math.cross(lightDirectionVS, coneU); - if (coneIsClipping) + var nearSection = new ConeSection(near, lightPositionVS, lightDirectionVS, cosHalfAngle, sinHalfAngle); + var farSection = new ConeSection(far, lightPositionVS, lightDirectionVS, cosHalfAngle, sinHalfAngle); + for (var i = 0; i < 2; i++) { - var r = baseRadius / coneHeight; - - // Find the Y bounds of the near-plane cone intersection, i.e. where y' = 0 - var thetaY = FindNearConicTangentTheta(lightPositionVS.yz, lightDirectionVS.yz, r, coneU.yz, coneV.yz); - var p0Y = EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, thetaY.x); - var p1Y = EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, thetaY.y); + if (i == 0 ? !coneIsClipping : !coneCrossesFar) + continue; + var section = i == 0 ? nearSection : farSection; + section.GetYExtremes(out var p0Y, out var p1Y); if (ConicPointIsValid(p0Y)) ExpandY(p0Y); if (ConicPointIsValid(p1Y)) ExpandY(p1Y); - // Find the X bounds of the near-plane cone intersection, i.e. where x' = 0 - var thetaX = FindNearConicTangentTheta(lightPositionVS.xz, lightDirectionVS.xz, r, coneU.xz, coneV.xz); - var p0X = EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, thetaX.x); - var p1X = EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, thetaX.y); + section.GetXExtremes(out var p0X, out var p1X); if (ConicPointIsValid(p0X)) ExpandY(p0X); if (ConicPointIsValid(p1X)) ExpandY(p1X); } // Calculate the lines making up the sides of the cone as seen from the camera. `l1` and `l2` form lines // from the light position. - GetConeSideTangentPoints(lightPositionVS, lightDirectionVS, cosHalfAngle, baseRadius, coneHeight, range, coneU, coneV, out var l1, out var l2); + GetConeSideTangentPoints(-lightPositionVS, lightDirectionVS, cosHalfAngle, baseRadius, coneHeight, range, coneU, coneV, out var l1, out var l2); - { - var planeNormal = math.float3(0, 1, viewPlaneBottoms[m_ViewIndex]); - var l1t = math.dot(-lightPositionVS, planeNormal) / math.dot(l1, planeNormal); - var l1x = lightPositionVS + l1 * l1t; - if (l1t >= 0 && l1t <= 1 && l1x.z >= near) ExpandY(l1x); - } - { - var planeNormal = math.float3(0, 1, viewPlaneTops[m_ViewIndex]); - var l1t = math.dot(-lightPositionVS, planeNormal) / math.dot(l1, planeNormal); - var l1x = lightPositionVS + l1 * l1t; - if (l1t >= 0 && l1t <= 1 && l1x.z >= near) ExpandY(l1x); - } + // Where the cone sides cross the bottom and top of the screen. + ExpandYAtViewPlane(lightPositionVS, l1, viewPlaneBottoms[m_ViewIndex]); + ExpandYAtViewPlane(lightPositionVS, l1, viewPlaneTops[m_ViewIndex]); + ExpandYAtViewPlane(lightPositionVS, l2, viewPlaneBottoms[m_ViewIndex]); + ExpandYAtViewPlane(lightPositionVS, l2, viewPlaneTops[m_ViewIndex]); m_TileYRange.Clamp(0, (short)(tileCount.y - 1)); // Calculate tile plane ranges for cone. - for (var planeIndex = m_TileYRange.start + 1; planeIndex <= m_TileYRange.end; planeIndex++) + for (var planeIndex = m_TileYRange.start; planeIndex <= m_TileYRange.end + 1; planeIndex++) { var planeRange = InclusiveRange.empty; @@ -223,51 +206,55 @@ bool ConicPointIsValid(float3 p) => // Intersect lines with y-plane and clip if needed. var l1t = math.dot(-lightPositionVS, planeNormal) / math.dot(l1, planeNormal); var l1x = lightPositionVS + l1 * l1t; - if (l1t >= 0 && l1t <= 1 && l1x.z >= near) planeRange.Expand((short)math.clamp(ViewToTileSpace(l1x).x, 0, tileCount.x - 1)); + if (l1t >= 0 && l1t <= 1 && IsInDepthRange(l1x)) ExpandTileX(ref planeRange, ViewToTileSpace(l1x).x); var l2t = math.dot(-lightPositionVS, planeNormal) / math.dot(l2, planeNormal); var l2x = lightPositionVS + l2 * l2t; - if (l2t >= 0 && l2t <= 1 && l2x.z >= near) planeRange.Expand((short)math.clamp(ViewToTileSpace(l2x).x, 0, tileCount.x - 1)); + if (l2t >= 0 && l2t <= 1 && IsInDepthRange(l2x)) ExpandTileX(ref planeRange, ViewToTileSpace(l2x).x); - if (IntersectCircleYPlane(planeY, baseCenter, lightDirectionVS, baseUY, baseVY, baseRadius, out var circleTile0, out var circleTile1)) + if (IntersectCirclePlane(math.float4(0, 1, -planeY, 0), baseCenter, baseUY, baseVY, baseRadius, out var circleTile0, out var circleTile1)) { - if (circleTile0.z >= near) planeRange.Expand((short)math.clamp(ViewToTileSpace(circleTile0).x, 0, tileCount.x - 1)); - if (circleTile1.z >= near) planeRange.Expand((short)math.clamp(ViewToTileSpace(circleTile1).x, 0, tileCount.x - 1)); + if (IsInDepthRange(circleTile0)) ExpandTileX(ref planeRange, ViewToTileSpace(circleTile0).x); + if (IsInDepthRange(circleTile1)) ExpandTileX(ref planeRange, ViewToTileSpace(circleTile1).x); } if (coneIsClipping) { - var y = planeY * near; - var r = baseRadius / coneHeight; - var theta = FindNearConicYTheta(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, y); - var p0 = math.float3(EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, theta.x).x, y, near); - var p1 = math.float3(EvaluateNearConic(near, lightPositionVS, lightDirectionVS, r, coneU, coneV, theta.y).x, y, near); - if (ConicPointIsValid(p0)) planeRange.Expand((short)math.clamp(ViewToTileSpace(p0).x, 0, tileCount.x - 1)); - if (ConicPointIsValid(p1)) planeRange.Expand((short)math.clamp(ViewToTileSpace(p1).x, 0, tileCount.x - 1)); + nearSection.IntersectRow(planeY * near, out var p0, out var p1); + if (ConicPointIsValid(p0)) ExpandTileX(ref planeRange, ViewToTileSpace(p0).x); + if (ConicPointIsValid(p1)) ExpandTileX(ref planeRange, ViewToTileSpace(p1).x); } - // Write to tile ranges above and below the plane. Note that at `m_Offset` we store Y-range. - var tileIndex = m_Offset + 1 + planeIndex; - tileRanges[tileIndex] = InclusiveRange.Merge(tileRanges[tileIndex], planeRange); - tileRanges[tileIndex - 1] = InclusiveRange.Merge(tileRanges[tileIndex - 1], planeRange); + if (coneCrossesFar) + { + farSection.IntersectRow(planeY * far, out var p0, out var p1); + if (ConicPointIsValid(p0)) ExpandTileX(ref planeRange, ViewToTileSpace(p0).x); + if (ConicPointIsValid(p1)) ExpandTileX(ref planeRange, ViewToTileSpace(p1).x); + } + + MergeTileRangeRows(planeIndex, planeRange); } } m_TileYRange.Clamp(0, (short)(tileCount.y - 1)); // Calculate tile plane ranges for sphere. - for (var planeIndex = m_TileYRange.start + 1; planeIndex <= m_TileYRange.end; planeIndex++) + for (var planeIndex = m_TileYRange.start; planeIndex <= m_TileYRange.end + 1; planeIndex++) { var planeRange = InclusiveRange.empty; var planeY = math.lerp(viewPlaneBottoms[m_ViewIndex], viewPlaneTops[m_ViewIndex], planeIndex * tileScaleInv.y); - GetSphereYPlaneHorizon(lightPositionVS, range, near, sphereClipRadius, planeY, out var sphereTile0, out var sphereTile1); - if (SpherePointIsValid(sphereTile0)) planeRange.Expand((short)math.clamp(ViewToTileSpace(sphereTile0).x, 0, tileCount.x - 1)); - if (SpherePointIsValid(sphereTile1)) planeRange.Expand((short)math.clamp(ViewToTileSpace(sphereTile1).x, 0, tileCount.x - 1)); + GetSphereYPlaneHorizon(lightPositionVS, range, planeY, out var sphereTile0, out var sphereTile1); + ExpandTileXIfInSphereCap(ref planeRange, sphereTile0, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + ExpandTileXIfInSphereCap(ref planeRange, sphereTile1, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + for (var i = 0; i < 2; i++) + { + GetSphereSectionRowPoints(lightPositionVS, rangesq, i == 0 ? near : far, planeY, out var section0, out var section1); + ExpandTileXIfInSphereCap(ref planeRange, section0, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + ExpandTileXIfInSphereCap(ref planeRange, section1, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot); + } - var tileIndex = m_Offset + 1 + planeIndex; - tileRanges[tileIndex] = InclusiveRange.Merge(tileRanges[tileIndex], planeRange); - tileRanges[tileIndex - 1] = InclusiveRange.Merge(tileRanges[tileIndex - 1], planeRange); + MergeTileRangeRows(planeIndex, planeRange); } tileRanges[m_Offset] = m_TileYRange; @@ -276,120 +263,160 @@ bool ConicPointIsValid(float3 p) => void TileLightOrthographic(int lightIndex) { var light = lights[lightIndex]; + if (light.lightType != LightType.Point && light.lightType != LightType.Spot) + { + return; + } + var lightToWorld = (float4x4)light.localToWorldMatrix; var lightPosVS = math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c3.xyz, 1)).xyz; lightPosVS.z *= -1; - ExpandOrthographic(lightPosVS); + if (IsInDepthRange(lightPosVS)) ExpandOrthographic(lightPosVS); var lightDirVS = math.mul(worldToViews[m_ViewIndex], math.float4(lightToWorld.c2.xyz, 0)).xyz; lightDirVS.z *= -1; lightDirVS = math.normalize(lightDirVS); + var isSpot = light.lightType == LightType.Spot; var halfAngle = math.radians(light.spotAngle * 0.5f); var range = light.range; var rangeSq = square(range); var cosHalfAngle = math.cos(halfAngle); + var sinHalfAngle = math.sin(halfAngle); var coneHeight = cosHalfAngle * range; - var coneHeightSq = square(coneHeight); - var coneHeightInv = 1f / coneHeight; - var coneHeightInvSq = square(coneHeightInv); - - bool SpherePointIsValid(float3 p) => light.lightType == LightType.Point || - math.dot(math.normalize(p - lightPosVS), lightDirVS) >= cosHalfAngle; - - var sphereBoundY0 = lightPosVS - math.float3(0, range, 0); - var sphereBoundY1 = lightPosVS + math.float3(0, range, 0); - var sphereBoundX0 = lightPosVS - math.float3(range, 0, 0); - var sphereBoundX1 = lightPosVS + math.float3(range, 0, 0); - if (SpherePointIsValid(sphereBoundY0)) ExpandOrthographic(sphereBoundY0); - if (SpherePointIsValid(sphereBoundY1)) ExpandOrthographic(sphereBoundY1); - if (SpherePointIsValid(sphereBoundX0)) ExpandOrthographic(sphereBoundX0); - if (SpherePointIsValid(sphereBoundX1)) ExpandOrthographic(sphereBoundX1); + // The outline of the sphere is its equator facing the camera, clipped to the depth range, and the circles cut by + // the near and far planes. + var sphereOutline = math.bool3(IsInDepthRange(lightPosVS), math.abs(near - lightPosVS.z) <= range, math.abs(far - lightPosVS.z) <= range); + for (var i = 0; i < 3; i++) + { + if (!sphereOutline[i]) + continue; + var depth = i == 0 ? lightPosVS.z : i == 1 ? near : far; + var radius = math.sqrt(rangeSq - square(depth - lightPosVS.z)); + ExpandOrthographicIfInSphereCap(math.float3(lightPosVS.x - radius, lightPosVS.y, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot); + ExpandOrthographicIfInSphereCap(math.float3(lightPosVS.x + radius, lightPosVS.y, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot); + ExpandOrthographicIfInSphereCap(math.float3(lightPosVS.x, lightPosVS.y - radius, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot); + ExpandOrthographicIfInSphereCap(math.float3(lightPosVS.x, lightPosVS.y + radius, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot); + } var circleCenter = lightPosVS + lightDirVS * coneHeight; - var circleRadius = math.sqrt(rangeSq - coneHeightSq); - var circleRadiusSq = square(circleRadius); - var circleUp = math.normalize(math.float3(0, 1, 0) - lightDirVS * lightDirVS.y); - var circleRight = math.normalize(math.float3(1, 0, 0) - lightDirVS * lightDirVS.x); - var circleBoundY0 = circleCenter - circleUp * circleRadius; - var circleBoundY1 = circleCenter + circleUp * circleRadius; - - if (light.lightType == LightType.Spot) + var circleRadius = range * sinHalfAngle; + var coneU = math.normalize(math.cross(lightDirVS, math.abs(lightDirVS.x) < 0.5f ? math.float3(1, 0, 0) : math.float3(0, 1, 0))); + var coneV = math.cross(lightDirVS, coneU); + var nearSection = new ConeSection(near, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle); + var farSection = new ConeSection(far, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle); + var circleExtentZ = circleRadius * math.sqrt(math.saturate(1.0f - square(lightDirVS.z))); + var coneMinZ = math.min(circleCenter.z - circleExtentZ, lightPosVS.z); + var coneMaxZ = math.max(circleCenter.z + circleExtentZ, lightPosVS.z); + var coneCrosses = math.bool2(near >= coneMinZ && near <= coneMaxZ, far >= coneMinZ && far <= coneMaxZ); + float3 l1 = 0, l2 = 0; + var coneDistanceTolerance = 1e-5f * (math.length(lightPosVS) + range); + + if (isSpot) { - var circleBoundX0 = circleCenter - circleRight * circleRadius; - var circleBoundX1 = circleCenter + circleRight * circleRadius; - ExpandOrthographic(circleBoundY0); - ExpandOrthographic(circleBoundY1); - ExpandOrthographic(circleBoundX0); - ExpandOrthographic(circleBoundX1); - } + // Extremes of the cone base circle, and its points on the near and far planes. + var circleUp = math.normalize(math.float3(0, 1, 0) - lightDirVS * lightDirVS.y) * circleRadius; + var circleRight = math.normalize(math.float3(1, 0, 0) - lightDirVS * lightDirVS.x) * circleRadius; + ExpandOrthographicIfInDepthRange(circleCenter - circleUp); + ExpandOrthographicIfInDepthRange(circleCenter + circleUp); + ExpandOrthographicIfInDepthRange(circleCenter - circleRight); + ExpandOrthographicIfInDepthRange(circleCenter + circleRight); + for (var i = 0; i < 2; i++) + { + if (GetCircleClipPoints(circleCenter, lightDirVS, circleRadius, i == 0 ? near : far, out var clip0, out var clip1)) + { + ExpandOrthographic(clip0); + ExpandOrthographic(clip1); + } + } - m_TileYRange.Clamp(0, (short)(tileCount.y - 1)); + // Extremes of the cone sections with the near and far planes. + for (var i = 0; i < 2; i++) + { + if (!coneCrosses[i]) + continue; + var section = i == 0 ? nearSection : farSection; + section.GetYExtremes(out var p0Y, out var p1Y); + section.GetXExtremes(out var p0X, out var p1X); + if (IsOnCone(p0Y, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p0Y); + if (IsOnCone(p1Y, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p1Y); + if (IsOnCone(p0X, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p0X); + if (IsOnCone(p1X, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandOrthographic(p1X); + } - // Find two lines in screen-space for the cone if the light is a spot. - float coneDir0X = 0, coneDir0YInv = 0, coneDir1X = 0, coneDir1YInv = 0; - if (light.lightType == LightType.Spot) - { - // Distance from light position to and radius of sphere fitted to the end of the cone. - var sphereDistance = coneHeight + circleRadiusSq * coneHeightInv; - var sphereRadius = math.sqrt(square(circleRadiusSq) * coneHeightInvSq + circleRadiusSq); - var directionXYSqInv = math.rcp(math.lengthsq(lightDirVS.xy)); - var polarIntersection = -circleRadiusSq * coneHeightInv * directionXYSqInv * lightDirVS.xy; - var polarDir = math.sqrt((square(sphereRadius) - math.lengthsq(polarIntersection)) * directionXYSqInv) * math.float2(lightDirVS.y, -lightDirVS.x); - var conePBase = lightPosVS.xy + sphereDistance * lightDirVS.xy + polarIntersection; - var coneP0 = conePBase - polarDir; - var coneP1 = conePBase + polarDir; - - coneDir0X = coneP0.x - lightPosVS.x; - coneDir0YInv = math.rcp(coneP0.y - lightPosVS.y); - coneDir1X = coneP1.x - lightPosVS.x; - coneDir1YInv = math.rcp(coneP1.y - lightPosVS.y); + // Silhouette lines of the cone as seen along the view direction. + GetConeSideTangentPoints(math.float3(0, 0, -1), lightDirVS, cosHalfAngle, circleRadius, coneHeight, range, coneU, coneV, out l1, out l2); } - // Tile plane ranges - for (var planeIndex = m_TileYRange.start + 1; planeIndex <= m_TileYRange.end; planeIndex++) + m_TileYRange.Clamp(0, (short)(tileCount.y - 1)); + + // Tile plane ranges; the rows are the planes y = planeY. + for (var planeIndex = m_TileYRange.start; planeIndex <= m_TileYRange.end + 1; planeIndex++) { var planeRange = InclusiveRange.empty; - - // Sphere var planeY = math.lerp(viewPlaneBottoms[m_ViewIndex], viewPlaneTops[m_ViewIndex], planeIndex * tileScaleInv.y); - var sphereX = math.sqrt(rangeSq - square(planeY - lightPosVS.y)); - var sphereX0 = math.float3(lightPosVS.x - sphereX, planeY, lightPosVS.z); - var sphereX1 = math.float3(lightPosVS.x + sphereX, planeY, lightPosVS.z); - if (SpherePointIsValid(sphereX0)) { ExpandRangeOrthographic(ref planeRange, sphereX0.x); } - if (SpherePointIsValid(sphereX1)) { ExpandRangeOrthographic(ref planeRange, sphereX1.x); } - if (light.lightType == LightType.Spot) + for (var i = 0; i < 3; i++) { - // Circle - if (planeY >= circleBoundY0.y && planeY <= circleBoundY1.y) + if (!sphereOutline[i]) + continue; + var depth = i == 0 ? lightPosVS.z : i == 1 ? near : far; + var halfWidth = math.sqrt(rangeSq - square(depth - lightPosVS.z) - square(planeY - lightPosVS.y)); + ExpandRangeOrthographicIfInSphereCap(ref planeRange, math.float3(lightPosVS.x - halfWidth, planeY, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot); + ExpandRangeOrthographicIfInSphereCap(ref planeRange, math.float3(lightPosVS.x + halfWidth, planeY, depth), lightPosVS, lightDirVS, cosHalfAngle, isSpot); + } + + if (isSpot) + { + if (IntersectCirclePlane(math.float4(0, 1, 0, -planeY), circleCenter, coneU, coneV, circleRadius, out var circle0, out var circle1)) { - var intersectionDistance = (planeY - circleCenter.y) / circleUp.y; - var closestPointX = circleCenter.x + intersectionDistance * circleUp.x; - var intersectionDirX = -lightDirVS.z / math.length(math.float3(-lightDirVS.z, 0, lightDirVS.x)); - var sideDistance = math.sqrt(square(circleRadius) - square(intersectionDistance)); - var circleX0 = closestPointX - sideDistance * intersectionDirX; - var circleX1 = closestPointX + sideDistance * intersectionDirX; - ExpandRangeOrthographic(ref planeRange, circleX0); - ExpandRangeOrthographic(ref planeRange, circleX1); + if (IsInDepthRange(circle0)) ExpandRangeOrthographic(ref planeRange, circle0.x); + if (IsInDepthRange(circle1)) ExpandRangeOrthographic(ref planeRange, circle1.x); } - // Cone - var deltaY = planeY - lightPosVS.y; - var coneT0 = deltaY * coneDir0YInv; - var coneT1 = deltaY * coneDir1YInv; - if (coneT0 >= 0 && coneT0 <= 1) { ExpandRangeOrthographic(ref planeRange, lightPosVS.x + coneT0 * coneDir0X); } - if (coneT1 >= 0 && coneT1 <= 1) { ExpandRangeOrthographic(ref planeRange, lightPosVS.x + coneT1 * coneDir1X); } + var line0 = lightPosVS + l1 * ((planeY - lightPosVS.y) / l1.y); + var line1 = lightPosVS + l2 * ((planeY - lightPosVS.y) / l2.y); + if (IsOnSegment(line0, lightPosVS, l1)) ExpandRangeOrthographic(ref planeRange, line0.x); + if (IsOnSegment(line1, lightPosVS, l2)) ExpandRangeOrthographic(ref planeRange, line1.x); + + for (var i = 0; i < 2; i++) + { + if (!coneCrosses[i]) + continue; + (i == 0 ? nearSection : farSection).IntersectRow(planeY, out var p0, out var p1); + if (IsOnCone(p0, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandRangeOrthographic(ref planeRange, p0.x); + if (IsOnCone(p1, lightPosVS, lightDirVS, cosHalfAngle, sinHalfAngle, coneHeight, coneDistanceTolerance)) ExpandRangeOrthographic(ref planeRange, p1.x); + } } - var tileIndex = m_Offset + 1 + planeIndex; - tileRanges[tileIndex] = InclusiveRange.Merge(tileRanges[tileIndex], planeRange); - tileRanges[tileIndex - 1] = InclusiveRange.Merge(tileRanges[tileIndex - 1], planeRange); + MergeTileRangeRows(planeIndex, planeRange); } tileRanges[m_Offset] = m_TileYRange; } + // Whether p = origin + t * line lies on the segment (t in [0, 1]) and in the depth range. + bool IsOnSegment(float3 p, float3 origin, float3 line) + { + var t = math.dot(p - origin, line) / math.lengthsq(line); + return t >= 0 && t <= 1 && IsInDepthRange(p); + } + + void ExpandOrthographicIfInDepthRange(float3 positionVS) + { + if (IsInDepthRange(positionVS)) ExpandOrthographic(positionVS); + } + + void ExpandOrthographicIfInSphereCap(float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot) + { + if (IsInSphereCap(positionVS, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot)) ExpandOrthographic(positionVS); + } + + void ExpandRangeOrthographicIfInSphereCap(ref InclusiveRange range, float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot) + { + if (IsInSphereCap(positionVS, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot)) ExpandRangeOrthographic(ref range, positionVS.x); + } + static readonly float3[] k_CubePoints = { new(-1, -1, -1), @@ -435,8 +462,9 @@ void TileReflectionProbe(int index) // The vertices of the cube in view space. var points = new NativeArray(k_CubePoints.Length, Allocator.Temp); - // This is initially filled with just the cube vertices that lie in front of the near plane. - var clippedPoints = new NativeArray(k_CubePoints.Length + k_CubeLineIndices.Length * 3, Allocator.Temp); + // This is initially filled with just the cube vertices that lie between the near and far planes. Each edge can add + // two more points where it crosses them. + var clippedPoints = new NativeArray(k_CubePoints.Length + k_CubeLineIndices.Length * 3 * 2, Allocator.Temp); var clippedPointsCount = 0; var leftmostIndex = 0; for (var i = 0; i < k_CubePoints.Length; i++) @@ -445,7 +473,7 @@ void TileReflectionProbe(int index) var point = math.mul(worldToViews[m_ViewIndex], math.float4(rotatedPointsWS, 1)).xyz; point.z *= -1; points[i] = point; - if (point.z >= near) + if (IsInDepthRange(point)) { var clippedPoint = isOrthographic ? point.xy : point.xy/point.z; var clippedIndex = clippedPointsCount++; @@ -454,8 +482,8 @@ void TileReflectionProbe(int index) } } - // Clip the cube's line segments with the near plane, and add the new vertices to clippedPoints. Only lines - // that are clipped will generate new vertices. + // Clip the cube's line segments with the near and far planes, and add the new vertices to clippedPoints. Only + // lines that cross a plane generate new vertices. for (var i = 0; i < k_CubeLineIndices.Length; i++) { var indices = k_CubeLineIndices[i]; @@ -463,12 +491,11 @@ void TileReflectionProbe(int index) for (var j = 0; j < 3; j++) { var p1 = points[indices[j+1]]; - // The entire line is in front of the near plane. - if (p0.z < near && p1.z < near) continue; - // Check whether the line needs clipping. - if (p0.z < near || p1.z < near) + for (var k = 0; k < 2; k++) { - var d = (near - p0.z) / (p1.z - p0.z); + var depth = k == 0 ? near : far; + if ((p0.z < depth) == (p1.z < depth)) continue; + var d = (depth - p0.z) / (p1.z - p0.z); var p = math.lerp(p0, p1, d); var clippedPoint = isOrthographic ? p.xy : p.xy/p.z; var clippedIndex = clippedPointsCount++; @@ -517,7 +544,7 @@ void TileReflectionProbe(int index) m_TileYRange.Clamp(0, (short)(tileCount.y - 1)); // Calculate tile plane ranges for sphere. - for (var planeIndex = m_TileYRange.start + 1; planeIndex <= m_TileYRange.end; planeIndex++) + for (var planeIndex = m_TileYRange.start; planeIndex <= m_TileYRange.end + 1; planeIndex++) { var planeRange = InclusiveRange.empty; @@ -535,12 +562,10 @@ void TileReflectionProbe(int index) var p = math.float3(x, planeY, 1); var pTS = isOrthographic ? ViewToTileSpaceOrthographic(p) : ViewToTileSpace(p); - planeRange.Expand((short)math.clamp(pTS.x, 0, tileCount.x - 1)); + ExpandTileX(ref planeRange, pTS.x); } - var tileIndex = m_Offset + 1 + planeIndex; - tileRanges[tileIndex] = InclusiveRange.Merge(tileRanges[tileIndex], planeRange); - tileRanges[tileIndex - 1] = InclusiveRange.Merge(tileRanges[tileIndex - 1], planeRange); + MergeTileRangeRows(planeIndex, planeRange); } tileRanges[m_Offset] = m_TileYRange; @@ -567,182 +592,140 @@ float2 ViewToTileSpaceOrthographic(float3 positionVS) return (positionVS.xy * viewToViewportScaleBiases[m_ViewIndex].xy + viewToViewportScaleBiases[m_ViewIndex].zw) * tileScale; } - /// - /// Expands the tile Y range and the X range in the row containing the position. - /// - void ExpandY(float3 positionVS) + void ExpandY(float3 positionVS) => ExpandTile(ViewToTileSpace(positionVS)); + + bool IsInDepthRange(float3 positionVS) => positionVS.z >= near && positionVS.z <= far; + + // Whether a point of a cone section lies on the cone, up to its base. Also rejects points off the cone, which + // degenerate sections can produce. Tolerates ~1e-4 rad, or a distance from the surface on the order of the float + // precision of the light's coordinates. + internal static bool IsOnCone(float3 p, float3 vertex, float3 axis, float cosHalfAngle, float sinHalfAngle, float coneHeight, float distanceTolerance) { - // var positionTS = math.clamp(ViewToTileSpace(positionVS), 0, tileCount - 1); - var positionTS = ViewToTileSpace(positionVS); - var tileY = (int)positionTS.y; - var tileX = (int)positionTS.x; - m_TileYRange.Expand((short)math.clamp(tileY, 0, tileCount.y - 1)); - if (tileY >= 0 && tileY < tileCount.y && tileX >= 0 && tileX < tileCount.x) - { - var rowXRange = tileRanges[m_Offset + 1 + tileY]; - rowXRange.Expand((short)tileX); - tileRanges[m_Offset + 1 + tileY] = rowXRange; - } + var q = p - vertex; + var length = math.length(q); + var axial = math.dot(q, axis); + return axial >= cosHalfAngle * length - sinHalfAngle * (1e-4f * length + distanceTolerance) && axial <= coneHeight; } - /// - /// Expands the tile Y range and the X range in the row containing the position. - /// - void ExpandOrthographic(float3 positionVS) + // For points on a light's sphere: skips points outside the depth range and, for spot lights, outside the cone. + bool IsInSphereCap(float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot) => + IsInDepthRange(positionVS) && (!isSpot || math.dot(math.normalize(positionVS - lightPositionVS), lightDirectionVS) >= cosHalfAngle); + + void ExpandYIfInSphereCap(float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot) { - // var positionTS = math.clamp(ViewToTileSpace(positionVS), 0, tileCount - 1); - var positionTS = ViewToTileSpaceOrthographic(positionVS); - var tileY = (int)positionTS.y; - var tileX = (int)positionTS.x; - m_TileYRange.Expand((short)math.clamp(tileY, 0, tileCount.y - 1)); - if (tileY >= 0 && tileY < tileCount.y && tileX >= 0 && tileX < tileCount.x) - { - var rowXRange = tileRanges[m_Offset + 1 + tileY]; - rowXRange.Expand((short)tileX); - tileRanges[m_Offset + 1 + tileY] = rowXRange; - } + if (IsInSphereCap(positionVS, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot)) ExpandY(positionVS); } - void ExpandRangeOrthographic(ref InclusiveRange range, float xVS) + void ExpandTileXIfInSphereCap(ref InclusiveRange range, float3 positionVS, float3 lightPositionVS, float3 lightDirectionVS, float cosHalfAngle, bool isSpot) { - range.Expand((short)math.clamp(ViewToTileSpaceOrthographic(xVS).x, 0, tileCount.x - 1)); + if (IsInSphereCap(positionVS, lightPositionVS, lightDirectionVS, cosHalfAngle, isSpot)) ExpandTileX(ref range, ViewToTileSpace(positionVS).x); } - static float square(float x) => x * x; - - /// - /// Finds the two horizon points seen from (0, 0) of a sphere projected onto either XZ or YZ. Takes clipping into account. - /// - static void GetSphereHorizon(float2 center, float radius, float near, float clipRadius, out float2 p0, out float2 p1) + // Expands the tile Y range where the segment from origin to origin + line crosses the view plane y = planeY * z. + void ExpandYAtViewPlane(float3 origin, float3 line, float planeY) { - var direction = math.normalize(center); - - // Distance from camera to center of sphere - var d = math.length(center); - - // Distance from camera to sphere horizon edge - var l = math.sqrt(d * d - radius * radius); - - // Height of circle horizon - var h = l * radius / d; + var planeNormal = math.float3(0, 1, -planeY); + var t = math.dot(-origin, planeNormal) / math.dot(line, planeNormal); + var positionVS = origin + line * t; + if (t >= 0 && t <= 1 && IsInDepthRange(positionVS)) ExpandY(positionVS); + } - // Center of circle horizon - var c = direction * (l * h / radius); + void ExpandOrthographic(float3 positionVS) => ExpandTile(ViewToTileSpaceOrthographic(positionVS)); - p0 = math.float2(float.MinValue, 1f); - p1 = math.float2(float.MaxValue, 1f); + void ExpandRangeOrthographic(ref InclusiveRange range, float xVS) => ExpandTileX(ref range, ViewToTileSpaceOrthographic(xVS).x); - // Handle clipping - if (center.y - radius < near) + /// + /// Expands the tile Y range and the X range in the row containing the tile-space position. + /// + void ExpandTile(float2 positionTS) + { + // NaN marks a missed intersection; skip it, as float-to-int casts of NaN differ across Burst, IL2CPP and Mono. + if (math.any(math.isnan(positionTS))) return; + // Floor, not truncate, so (-1, 0) maps off-screen; clamp before casting to keep the cast in range. + var tile = (int2)math.clamp(math.floor(positionTS), -1f, (float2)tileCount); + m_TileYRange.Expand((short)math.clamp(tile.y, 0, tileCount.y - 1)); + // Keep one tile of off-screen slack; TileRangeExpansionJob only sets on-screen columns, + // so fully off-screen rows cover nothing while rows reaching an edge keep the edge tile. + if (tile.y >= 0 && tile.y < tileCount.y) { - p0 = math.float2(center.x + clipRadius, near); - p1 = math.float2(center.x - clipRadius, near); + var rowXRange = tileRanges[m_Offset + 1 + tile.y]; + rowXRange.Expand((short)tile.x); + tileRanges[m_Offset + 1 + tile.y] = rowXRange; } + } - // Circle horizon points - var c0 = c + math.float2(-direction.y, direction.x) * h; - if (square(d) >= square(radius) && c0.y >= near) + // Tile-space X counterpart of ExpandTile, for a row-boundary range. + void ExpandTileX(ref InclusiveRange range, float tileX) + { + if (math.isnan(tileX)) return; + range.Expand((short)math.clamp(math.floor(tileX), -1f, tileCount.x)); + } + + // Merge planeRange into the rows above and below boundary planeIndex; m_Offset holds the Y range. + void MergeTileRangeRows(int planeIndex, InclusiveRange planeRange) + { + if (planeIndex < tileCount.y) { - if (c0.x > p0.x) { p0 = c0; } - if (c0.x < p1.x) { p1 = c0; } + var above = m_Offset + 1 + planeIndex; + tileRanges[above] = InclusiveRange.Merge(tileRanges[above], planeRange); } - - var c1 = c + math.float2(direction.y, -direction.x) * h; - if (square(d) >= square(radius) && c1.y >= near) + if (planeIndex > 0) { - if (c1.x > p0.x) { p0 = c1; } - if (c1.x < p1.x) { p1 = c1; } + var below = m_Offset + planeIndex; + tileRanges[below] = InclusiveRange.Merge(tileRanges[below], planeRange); } } - static void GetSphereYPlaneHorizon(float3 center, float sphereRadius, float near, float clipRadius, float y, out float3 left, out float3 right) + static float square(float x) => x * x; + + /// + /// Returns the points where the tangents from the origin touch a 2D circle, or NaN if the origin is inside it. + /// + static void GetCircleHorizon(float2 center, float radius, out float2 p0, out float2 p1) { - // Note: The y-plane is the plane that is determined by `y` in that it contains the vector (1, 0, 0) - // and goes through the points (0, y, 1) and (0, 0, 0). This would become a straight line in screen-space, and so it - // represents the boundary between two rows of tiles. - - // Near-plane clipping - will get overwritten if no clipping is needed. - // `y` is given for the view plane (Z=1), scale it so that it is on the near plane instead. - var yNear = y * near; - // Find the two points of intersection between the clip circle of the sphere and the y-plane. - // Found using Pythagoras with a right triangle formed by three points: - // (a) center of the clip circle - // (b) a point straight above the clip circle center on the y-plane - // (c) a point that is both on the circle and the y-plane (this is the point we want to find in the end) - // The hypotenuse is formed by (a) and (c) with length equal to the clip radius. The known side is - // formed by (a) and (b) and is simply the distance from the center to the y-plane along the y-axis. - // The remaining side gives us the x-displacement needed to find the intersection points. - var clipHalfWidth = math.sqrt(square(clipRadius) - square(yNear - center.y)); - left = math.float3(center.x - clipHalfWidth, yNear, near); - right = math.float3(center.x + clipHalfWidth, yNear, near); - - // Basis vectors in the y-plane for being able to parameterize the plane. + // With d the distance to the center and l the tangent length, the points are (l^2 * center +- l * r * perp(center)) / d^2. + var dSq = math.lengthsq(center); + var l = math.sqrt(dSq - square(radius)); + var side = l * radius * math.float2(-center.y, center.x); + p0 = (square(l) * center + side) / dSq; + p1 = (square(l) * center - side) / dSq; + } + + /// + /// Returns the horizon points, as seen from the origin, of the circle cut from a sphere by the plane through the + /// origin and the view-plane row at height y. NaN if the plane misses the sphere or the origin is inside the circle. + /// + static void GetSphereYPlaneHorizon(float3 center, float sphereRadius, float y, out float3 left, out float3 right) + { + // Basis vectors in the y-plane, which contains (1, 0, 0) and (0, y, 1), and its normal (0, 1, -y). var planeU = math.normalize(math.float3(0, y, 1)); var planeV = math.float3(1, 0, 0); - - // Calculate the normal of the y-plane. Found from: (0, y, 1) × (1, 0, 0) = (0, 1, -y) - // This is used to represent the plane along with the origin, which is just 0 and thus doesn't show up - // in the calculations. var normal = math.normalize(math.float3(0, 1, -y)); - // We want to first find the circle from the intersection of the y-plane and the sphere. - - // The shortest distance from the sphere center and the y-plane. The sign determines which side of the plane - // the center is on. - var signedDistance = math.dot(normal, center); - - // Unsigned shortest distance from the sphere center to the plane. - var distanceToPlane = math.abs(signedDistance); - - // The center of the intersection circle in the y-plane, which is the point on the plane closest to the - // sphere center. I.e. this is at `distanceToPlane` from the center. + // The section circle is centered at the point of the plane closest to the sphere center. + var distanceToPlane = math.dot(normal, center); var centerOnPlane = math.float2(math.dot(center, planeU), math.dot(center, planeV)); - - // Distance from origin to the circle center. - var distanceInPlane = math.length(centerOnPlane); - - // Direction from origin to the circle center. - var directionPS = centerOnPlane / distanceInPlane; - - // Calculate the radius of the circle using Pythagoras. We know that any point on the circle is a point on - // the sphere. Thus we can construct a triangle with the sphere center, circle center, and a point on the - // circle. We then want to find its distance to the circle center, as that will be equal to the radius. As - // the point is on the sphere, it must be `sphereRadius` from the sphere center, forming the hypotenuse. The - // other side is between the sphere and circle centers, which we've already calculated to be - // `distanceToPlane`. var circleRadius = math.sqrt(square(sphereRadius) - square(distanceToPlane)); - // Now that we have the circle, we can find the horizon points. Since we've parametrized the plane, we can - // just do this in 2D. - - // Any of these conditions will yield NaN due to negative square roots. They are signs that clipping is needed, - // so we fallback on the already calculated values in that case. - if (square(distanceToPlane) <= square(sphereRadius) && square(circleRadius) <= square(distanceInPlane)) - { - // Distance from origin to circle horizon edge. - var l = math.sqrt(square(distanceInPlane) - square(circleRadius)); - - // Height of circle horizon. - var h = l * circleRadius / distanceInPlane; - - // Center of circle horizon. - var c = directionPS * (l * h / circleRadius); - - // Calculate the horizon points in the plane. - var leftOnPlane = c + math.float2(directionPS.y, -directionPS.x) * h; - var rightOnPlane = c + math.float2(-directionPS.y, directionPS.x) * h; - - // Transform horizon points to view space and use if not clipped. - var leftCandidate = leftOnPlane.x * planeU + leftOnPlane.y * planeV; - if (leftCandidate.z >= near) left = leftCandidate; + GetCircleHorizon(centerOnPlane, circleRadius, out var leftOnPlane, out var rightOnPlane); + left = leftOnPlane.x * planeU + leftOnPlane.y * planeV; + right = rightOnPlane.x * planeU + rightOnPlane.y * planeV; + } - var rightCandidate = rightOnPlane.x * planeU + rightOnPlane.y * planeV; - if (rightCandidate.z >= near) right = rightCandidate; - } + /// + /// Returns the points where the plane through the origin and the view-plane row at height planeY crosses the + /// circle cut from a sphere by the plane z = depth, or NaN if there are none. + /// + static void GetSphereSectionRowPoints(float3 center, float radiusSq, float depth, float planeY, out float3 p0, out float3 p1) + { + var y = planeY * depth; + var halfWidth = math.sqrt(radiusSq - square(depth - center.z) - square(y - center.y)); + p0 = math.float3(center.x - halfWidth, y, depth); + p1 = math.float3(center.x + halfWidth, y, depth); } /// - /// Finds the two points of intersection of a 3D circle and the near plane. + /// Finds the two points of intersection of a 3D circle and the plane z = near. /// static bool GetCircleClipPoints(float3 circleCenter, float3 circleNormal, float circleRadius, float near, out float3 p0, out float3 p1) { @@ -779,32 +762,6 @@ static bool GetCircleClipPoints(float3 circleCenter, float3 circleNormal, float return math.abs(distance) <= circleRadius; } - static (float, float) IntersectEllipseLine(float a, float b, float3 line) - { - // The line is represented as a homogenous 2D line {u, v, w} such that ux + vy + w = 0. - // The ellipse is represented by the implicit equation x^2/a^2 + y^2/b^2 = 1. - // We solve the line equation for y: y = (ux + w) / v - // We then substitute this into the ellipse equation and expand and re-arrange a bit: - // x^2/a^2 + ((ux + w) / v)^2/b^2 = 1 => - // x^2/a^2 + ((ux + w)^2 / v^2)/b^2 = 1 => - // x^2/a^2 + (ux + w)^2/(v^2 b^2) = 1 => - // x^2/a^2 + (u^2 x^2 + w^2 + 2 u x w)/(v^2 b^2) = 1 => - // x^2/a^2 + x^2 u^2 / (v^2 b^2) + w^2/(v^2 b^2) + x 2 u w / (v^2 b^2) = 1 => - // x^2 (1/a^2 + u^2 / (v^2 b^2)) + x 2 u w / (v^2 b^2) + w^2 / (v^2 b^2) - 1 = 0 - // We now have a quadratic equation with: - // a = 1/a^2 + u^2 / (v^2 b^2) - // b = 2 u w / (v^2 b^2) - // c = w^2 / (v^2 b^2) - 1 - var div = math.rcp(square(line.y) * square(b)); - var qa = 1f / square(a) + square(line.x) * div; - var qb = 2f * line.x * line.z * div; - var qc = square(line.z) * div - 1f; - var sqrtD = math.sqrt(qb * qb - 4f * qa * qc); - var x1 = (-qb + sqrtD) / (2f * qa); - var x2 = (-qb - sqrtD) / (2f * qa); - return (x1, x2); - } - /// /// Calculates the horizon of a circle orthogonally projected to a plane as seen from the origin on the plane. /// @@ -814,7 +771,7 @@ static bool GetCircleClipPoints(float3 circleCenter, float3 circleNormal, float /// The minor axis of the ellipse formed by the projection of the circle. /// The first horizon point expressed as factors of and . /// The second horizon point expressed as factors of and . - static void GetProjectedCircleHorizon(float2 center, float radius, float2 U, float2 V, out float2 uv1, out float2 uv2) + internal static void GetProjectedCircleHorizon(float2 center, float radius, float2 U, float2 V, out float2 uv1, out float2 uv2) { // U is assumed to be constructed such that it is never 0, but V can be if the circle projects to a line segment. // In that case, the solution can be trivially found using U only. @@ -827,76 +784,47 @@ static void GetProjectedCircleHorizon(float2 center, float radius, float2 U, flo else { var ul = math.length(U); - var ulinv = math.rcp(ul); - var vlinv = math.rcp(vl); // Normalize U and V in the plane. - var u = U * ulinv; - var v = V * vlinv; + var u = U / ul; + var v = V / vl; // Major and minor axis of the ellipse. var a = ul * radius; var b = vl * radius; - // Project the camera position into a 2D coordinate system with the circle at (0, 0) and - // the ellipse major and minor axes as the coordinate system axes. This allows us to use the standard - // form of the ellipse equation, greatly simplifying the calculations. - var cameraUV = math.float2(math.dot(-center, u), math.dot(-center, v)); - - // Find the polar line of the camera position in the normalized UV coordinate system. - var polar = math.float3(cameraUV.x / square(a), cameraUV.y / square(b), -1); - var (t1, t2) = IntersectEllipseLine(a, b, polar); - - // Find Y by putting polar into line equation and solving. Denormalize by dividing by U and V lengths. - uv1 = math.float2(t1 * ulinv, (-polar.x / polar.y * t1 - polar.z / polar.y) * vlinv); - uv2 = math.float2(t2 * ulinv, (-polar.x / polar.y * t2 - polar.z / polar.y) * vlinv); + // Scale the ellipse to the unit circle, where the tangent points from the camera q are + // (q +- sqrt(|q|^2 - 1) * perp(q)) / |q|^2. A camera inside the ellipse has no horizon and yields NaN. + var q = math.float2(math.dot(-center, u), math.dot(-center, v)) / math.float2(a, b); + var qq = math.lengthsq(q); + var side = math.sqrt(qq - 1f) * math.float2(-q.y, q.x); + uv1 = (q + side) / qq * radius; + uv2 = (q - side) / qq * radius; } } - static bool IntersectCircleYPlane( - float y, float3 circleCenter, float3 circleNormal, float3 circleU, float3 circleV, float circleRadius, + /// + /// Intersects a 3D circle with the plane dot(plane.xyz, p) + plane.w = 0. + /// + static bool IntersectCirclePlane( + float4 plane, float3 circleCenter, float3 circleU, float3 circleV, float circleRadius, out float3 p1, out float3 p2) { p1 = p2 = 0; - // Intersecting a circle with a plane yields 2 points, or the whole circle if the plane and the plane of the - // circle are the same, or nothing if the planes are parallel but offset. We're only interested in the first - // case. Our other tests will catch the other cases. - - // The two points will be on the line of intersection of the two planes. Thus we first have to find that line. - - // Shoot 2 rays along the y-plane and intersect the circle plane. We then transform them into the circle - // plane, so that we can work in 2D. - var CdotN = math.dot(circleCenter, circleNormal); - var h1v = math.float3(1, y, 1) * CdotN / math.dot(math.float3(1, y, 1), circleNormal) - circleCenter; - var h1 = math.float2(math.dot(h1v, circleU), math.dot(h1v, circleV)); - var h2v = math.float3(-1, y, 1) * CdotN / math.dot(math.float3(-1, y, 1), circleNormal) - circleCenter; - var h2 = math.float2(math.dot(h2v, circleU), math.dot(h2v, circleV)); - - var lineDirection = math.normalize(h2 - h1); - // We now have the direction of the line, and would like to find the point on it that is closest to the - // circle center. A line in 2D is similar to a plane in 3D. So we can calculate a normal, which is just a - // perpendicular/orthogonal direction, and then take the dot product to find the distance. This is similar - // to when calculating the d-term for a plane in 3D, which is also just calculating the closest distance - // from the origin to the plane. - var lineNormal = math.float2(lineDirection.y, -lineDirection.x); - var distToLine = math.dot(h1, lineNormal); - // We can then get that point on the line by following our normal with the distance we just calculated. - var lineCenter = lineNormal * distToLine; - - // Avoid negative square roots, as this means we've hit one of the cases that we do not care about. - if (distToLine > circleRadius) return false; - - // What's left now is to intersect the line with the circle. We can do so with Pythagoras. Our triangle - // is made up of `lineCenter`, the circle center and one of the intersection points. - // We know the distance from `lineCenter` to the circle center (`distToLine`), and the distance from - // the circle center to one of the intersection points must be the circle radius, as it lies on the - // circle, forming the hypotenuse. - var l = math.sqrt(circleRadius * circleRadius - distToLine * distToLine); - - // What we found above is the distance from `lineCenter` to each of the intersection points. So we just - // scrub along the line in both directions using the found distance, and then transform back into view - // space. + // In circle coordinates (s, t), the plane is the line a * s + b * t + k = 0. Parallel planes (a = b = 0) + // give the whole circle or nothing, which the other bounds cover. + var lineNormal = math.float2(math.dot(plane.xyz, circleU), math.dot(plane.xyz, circleV)); + var lineNormalLengthSq = math.lengthsq(lineNormal); + if (lineNormalLengthSq == 0f) return false; + + var k = math.dot(plane.xyz, circleCenter) + plane.w; + var distToLineSq = k * k / lineNormalLengthSq; + if (distToLineSq > circleRadius * circleRadius) return false; + + var lineCenter = -k / lineNormalLengthSq * lineNormal; + var lineDirection = math.float2(-lineNormal.y, lineNormal.x) * math.rsqrt(lineNormalLengthSq); + var l = math.sqrt(circleRadius * circleRadius - distToLineSq); var x1 = lineCenter + l * lineDirection; var x2 = lineCenter - l * lineDirection; p1 = circleCenter + x1.x * circleU + x1.y * circleV; @@ -905,67 +833,110 @@ static bool IntersectCircleYPlane( return true; } - static void GetConeSideTangentPoints(float3 vertex, float3 axis, float cosHalfAngle, float circleRadius, float coneHeight, float range, float3 circleU, float3 circleV, out float3 l1, out float3 l2) + /// + /// Finds the cone's silhouette lines from its vertex, as seen along toCamera: the vector from the vertex to the + /// camera, or the direction towards the camera for an orthographic projection. + /// + static void GetConeSideTangentPoints(float3 toCamera, float3 axis, float cosHalfAngle, float circleRadius, float coneHeight, float range, float3 circleU, float3 circleV, out float3 l1, out float3 l2) { l1 = l2 = 0; - if (math.dot(math.normalize(-vertex), axis) >= cosHalfAngle) + if (math.dot(math.normalize(toCamera), axis) >= cosHalfAngle) { return; } - var d = -math.dot(vertex, axis); - // If d is zero, this leads to a numerical instability in the code later on. This is why we make the value - // an epsilon if it is zero. - if (d == 0f) d = 1e-6f; - var sign = d < 0 ? -1f : 1f; - // sign *= vertex.z < 0 ? -1f : 1f; - // `origin` is the center of the circular slice we're about to calculate at distance `d` from the `vertex`. - var origin = vertex + axis * d; - // Get the radius of the circular slice of the cone at the `origin`. - var radius = math.abs(d) * circleRadius / coneHeight; - // `circleU` and `circleV` are the two vectors perpendicular to the cone's axis. `cameraUV` is thus the - // position of the camera projected onto the plane of the circular slice. This basically creates a new - // 2D coordinate space, with (0, 0) located at the center of the circular slice, which why this variable - // is called `origin`. - var cameraUV = math.float2(math.dot(circleU, -origin), math.dot(circleV, -origin)); - // Use homogeneous coordinates to find the tangents. - var polar = math.float3(cameraUV, -square(radius)); - var p1 = math.float2(-1, -polar.x / polar.y * (-1) - polar.z / polar.y); - var p2 = math.float2(1, -polar.x / polar.y * 1 - polar.z / polar.y); - var lineDirection = math.normalize(p2 - p1); - var lineNormal = math.float2(lineDirection.y, -lineDirection.x); - var distToLine = math.dot(p1, lineNormal); - var lineCenter = lineNormal * distToLine; - var l = math.sqrt(radius * radius - distToLine * distToLine); - var x1UV = lineCenter + l * lineDirection; - var x2UV = lineCenter - l * lineDirection; - var dir1 = math.normalize((origin + x1UV.x * circleU + x1UV.y * circleV) - vertex) * sign; - var dir2 = math.normalize((origin + x2UV.x * circleU + x2UV.y * circleV) - vertex) * sign; - l1 = dir1 * range; - l2 = dir2 * range; - } + // Silhouette generators satisfy dot(e, w.xy) = tan * w.z for unit e in the u/v plane, w = toCamera in the cone frame. + // Solved directly so it stays stable when the camera lies near the plane through the vertex. + var w = math.float3(math.dot(toCamera, circleU), math.dot(toCamera, circleV), math.dot(toCamera, axis)); + var distToAxisSq = math.lengthsq(w.xy); + if (distToAxisSq == 0f) + { + return; + } - static float3 EvaluateNearConic(float near, float3 o, float3 d, float r, float3 u, float3 v, float theta) - { - var h = (near - o.z) / (d.z + r * u.z * math.cos(theta) + r * v.z * math.sin(theta)); - return math.float3(o.xy + h * (d.xy + r * u.xy * math.cos(theta) + r * v.xy * math.sin(theta)), near); + var invDistToAxis = math.rsqrt(distToAxisSq); + var n = w.xy * invDistToAxis; + var c = math.clamp(circleRadius / coneHeight * w.z * invDistToAxis, -1f, 1f); + var s = math.sqrt(1f - c * c); + var e1 = c * n + s * math.float2(-n.y, n.x); + var e2 = c * n - s * math.float2(-n.y, n.x); + var sinHalfAngle = circleRadius / range; + l1 = (cosHalfAngle * axis + sinHalfAngle * (e1.x * circleU + e1.y * circleV)) * range; + l2 = (cosHalfAngle * axis + sinHalfAngle * (e2.x * circleU + e2.y * circleV)) * range; } - // o, d, u and v are expected to contain {x or y, z}. I.e. pass in x values to find tangents where x' = 0 - // Returns the two theta values as a float2. - static float2 FindNearConicTangentTheta(float2 o, float2 d, float r, float2 u, float2 v) + /// + /// Section of a cone with the plane z = depth. With q = p - vertex = (x, y, z) and z = depth - vertex.z fixed, the cone + /// is dot(q, axis)^2 = cos^2 * dot(q, q), which is solved directly in the plane to stay stable when the vertex is close to it. + /// + internal struct ConeSection { - var sqrt = math.sqrt(square(d.x) * square(u.y) + square(d.x) * square(v.y) - 2f * d.x * d.y * u.x * u.y - 2f * d.x * d.y * v.x * v.y + square(d.y) * square(u.x) + square(d.y) * square(v.x) - square(r) * square(u.x) * square(v.y) + 2f * square(r) * u.x * u.y * v.x * v.y - square(r) * square(u.y) * square(v.x)); - var denom = d.x * v.y - d.y * v.x - r * u.x * v.y + r * u.y * v.x; - return 2 * math.atan((-d.x * u.y + d.y * u.x + math.float2(1, -1) * sqrt) / denom); + float3 m_Vertex; + float3 m_Axis; + float m_Depth; + float m_Z; + float m_CosSq; + float m_SinSq; + + public ConeSection(float depth, float3 vertex, float3 axis, float cosHalfAngle, float sinHalfAngle) + { + m_Vertex = vertex; + m_Axis = axis; + m_Depth = depth; + m_Z = depth - vertex.z; + m_CosSq = cosHalfAngle * cosHalfAngle; + m_SinSq = sinHalfAngle * sinHalfAngle; + } + + /// + /// Returns the points with extreme y, NaN or infinite where there are none. + /// + public void GetYExtremes(out float3 p0, out float3 p1) + { + var d = m_Axis; + var y = SolveQuadratic(d.z * d.z - m_SinSq, -d.y * d.z * m_Z, m_Z * m_Z * (d.y * d.y - m_SinSq)); + var x = -d.x * (d.y * y + d.z * m_Z) / (d.x * d.x - m_CosSq); + p0 = ToView(x.x, y.x); + p1 = ToView(x.y, y.y); + } + + /// + /// Returns the points with extreme x, NaN or infinite where there are none. + /// + public void GetXExtremes(out float3 p0, out float3 p1) + { + var d = m_Axis; + var x = SolveQuadratic(d.z * d.z - m_SinSq, -d.x * d.z * m_Z, m_Z * m_Z * (d.x * d.x - m_SinSq)); + var y = -d.y * (d.x * x + d.z * m_Z) / (d.y * d.y - m_CosSq); + p0 = ToView(x.x, y.x); + p1 = ToView(x.y, y.y); + } + + /// + /// Returns the points at view-space height y, NaN or infinite where there are none. + /// + public void IntersectRow(float yVS, out float3 p0, out float3 p1) + { + var d = m_Axis; + var y = yVS - m_Vertex.y; + var k = d.y * y + d.z * m_Z; + var x = SolveQuadratic(d.x * d.x - m_CosSq, d.x * k, k * k - m_CosSq * (y * y + m_Z * m_Z)); + p0 = ToView(x.x, y); + p1 = ToView(x.y, y); + } + + float3 ToView(float x, float y) => math.float3(m_Vertex.xy + math.float2(x, y), m_Depth); } - static float2 FindNearConicYTheta(float near, float3 o, float3 d, float r, float3 u, float3 v, float y) + /// + /// Returns the roots of a * t^2 + 2 * b * t + c = 0: NaN if there are none, and one is infinite if a is 0. + /// + static float2 SolveQuadratic(float a, float b, float c) { - var sqrt = math.sqrt(-square(d.y) * square(o.z) + 2 * square(d.y) * o.z * near - square(d.y) * square(near) + 2 * d.y * d.z * o.y * o.z - 2 * d.y * d.z * o.y * near - 2 * d.y * d.z * o.z * y + 2 * d.y * d.z * y * near - square(d.z) * square(o.y) + 2 * square(d.z) * o.y * y - square(d.z) * square(y) + square(o.y) * square(r) * square(u.z) + square(o.y) * square(r) * square(v.z) - 2 * o.y * o.z * square(r) * u.y * u.z - 2 * o.y * o.z * square(r) * v.y * v.z - 2 * o.y * y * square(r) * square(u.z) - 2 * o.y * y * square(r) * square(v.z) + 2 * o.y * square(r) * u.y * u.z * near + 2 * o.y * square(r) * v.y * v.z * near + square(o.z) * square(r) * square(u.y) + square(o.z) * square(r) * square(v.y) + 2 * o.z * y * square(r) * u.y * u.z + 2 * o.z * y * square(r) * v.y * v.z - 2 * o.z * square(r) * square(u.y) * near - 2 * o.z * square(r) * square(v.y) * near + square(y) * square(r) * square(u.z) + square(y) * square(r) * square(v.z) - 2 * y * square(r) * u.y * u.z * near - 2 * y * square(r) * v.y * v.z * near + square(r) * square(u.y) * square(near) + square(r) * square(v.y) * square(near)); - var denom = d.y * o.z - d.y * near - d.z * o.y + d.z * y + o.y * r * u.z - o.z * r * u.y - y * r * u.z + r * u.y * near; - return 2 * math.atan((r * (o.y * v.z - o.z * v.y - y * v.z + v.y * near) + math.float2(1, -1) * sqrt) / denom); + // Avoids the cancellation in -b + sqrt(b^2 - ac) by computing that root as c / q. + var q = -(b + (b < 0f ? -math.sqrt(b * b - a * c) : math.sqrt(b * b - a * c))); + return math.float2(q / a, c / q); } } } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ZBinningJob.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ZBinningJob.cs index 1c4e6b7f95b..247292de32f 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ZBinningJob.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Tiling/ZBinningJob.cs @@ -81,6 +81,8 @@ void FillZBins(int binStart, int binEnd, int itemStart, int itemEnd, int headerI for (var index = itemStart; index < itemEnd; index++) { var minMax = minMaxZs[itemOffset + index]; + // Empty depth range, e.g. an item entirely closer than the near plane; skipping it also keeps log2 away from non-positive depths. + if (minMax.x > minMax.y) continue; var minBin = math.max((int)((isOrthographic ? minMax.x : math.log2(minMax.x)) * zBinScale + zBinOffset), binStart); var maxBin = math.min((int)((isOrthographic ? minMax.y : math.log2(minMax.y)) * zBinScale + zBinOffset), binEnd); From dd47e92fa678ec4511f4a6d8e11025bf5227e382 Mon Sep 17 00:00:00 2001 From: Esmeralda Salamone Date: Tue, 10 Nov 2026 10:03:06 +0000 Subject: [PATCH 13/18] [6000.3][VFX] Add the RenderPipeline SubShader tag for URP VFX --- .../Editor/VFXGraph/VFXURPSubOutput.cs | 4 +++ .../Contexts/VFXAbstractParticleOutput.cs | 5 +++- .../Editor/Models/Contexts/VFXSRPSubOutput.cs | 6 ++++ .../Tests/Editor/VFXCodeGenerationTest.cs | 30 +++++++++++++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/VFXURPSubOutput.cs b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/VFXURPSubOutput.cs index e72efd65498..07ea6a4475a 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/VFXURPSubOutput.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/VFXGraph/VFXURPSubOutput.cs @@ -1,11 +1,15 @@ #if HAS_VFX_GRAPH +using UnityEngine.Rendering.Universal; + namespace UnityEditor.VFX.URP { class VFXURPSubOutput : VFXSRPSubOutput { //URP only support motion vector on opaque geometry (with or without ShaderGraph) public override bool supportsMotionVector => owner.isBlendModeOpaque; + + public override string GetRenderPipelineTagStr() => UniversalRenderPipeline.k_ShaderTagName; } } #endif diff --git a/Packages/com.unity.visualeffectgraph/Editor/Models/Contexts/VFXAbstractParticleOutput.cs b/Packages/com.unity.visualeffectgraph/Editor/Models/Contexts/VFXAbstractParticleOutput.cs index 735c96046e3..e0518e8d2ec 100644 --- a/Packages/com.unity.visualeffectgraph/Editor/Models/Contexts/VFXAbstractParticleOutput.cs +++ b/Packages/com.unity.visualeffectgraph/Editor/Models/Contexts/VFXAbstractParticleOutput.cs @@ -722,7 +722,10 @@ public override IEnumerable> additionalRep var shaderTags = new VFXShaderWriter(); var renderQueueStr = subOutput.GetRenderQueueStr(); var renderTypeStr = isBlendModeOpaque ? "Opaque" : "Transparent"; - shaderTags.Write(string.Format("Tags {{ \"Queue\"=\"{0}\" \"IgnoreProjector\"=\"{1}\" \"RenderType\"=\"{2}\" }}", renderQueueStr, !isBlendModeOpaque, renderTypeStr)); + // The pipeline tag is what scopes the SRP shader keyword filtering rules to these shaders + var renderPipelineTagStr = subOutput.GetRenderPipelineTagStr(); + var renderPipelineTag = string.IsNullOrEmpty(renderPipelineTagStr) ? string.Empty : string.Format(" \"RenderPipeline\"=\"{0}\"", renderPipelineTagStr); + shaderTags.Write(string.Format("Tags {{ \"Queue\"=\"{0}\" \"IgnoreProjector\"=\"{1}\" \"RenderType\"=\"{2}\"{3} }}", renderQueueStr, !isBlendModeOpaque, renderTypeStr, renderPipelineTag)); yield return new KeyValuePair("${VFXShaderTags}", shaderTags); foreach (var additionnalStencilReplacement in subOutput.GetStencilStateOverridesStr()) diff --git a/Packages/com.unity.visualeffectgraph/Editor/Models/Contexts/VFXSRPSubOutput.cs b/Packages/com.unity.visualeffectgraph/Editor/Models/Contexts/VFXSRPSubOutput.cs index fd463d88621..1ba4de98140 100644 --- a/Packages/com.unity.visualeffectgraph/Editor/Models/Contexts/VFXSRPSubOutput.cs +++ b/Packages/com.unity.visualeffectgraph/Editor/Models/Contexts/VFXSRPSubOutput.cs @@ -60,6 +60,12 @@ public virtual string GetBlendModeStr() } } + // Empty when the render pipeline has no shader tag to advertise + public virtual string GetRenderPipelineTagStr() + { + return string.Empty; + } + public virtual string GetRenderQueueStr() { var baseRenderQueue = string.Empty; diff --git a/Tests/SRPTests/Packages/com.unity.testing.visualeffectgraph/Tests/Editor/VFXCodeGenerationTest.cs b/Tests/SRPTests/Packages/com.unity.testing.visualeffectgraph/Tests/Editor/VFXCodeGenerationTest.cs index aef51da2f87..3f62a82d7a5 100644 --- a/Tests/SRPTests/Packages/com.unity.testing.visualeffectgraph/Tests/Editor/VFXCodeGenerationTest.cs +++ b/Tests/SRPTests/Packages/com.unity.testing.visualeffectgraph/Tests/Editor/VFXCodeGenerationTest.cs @@ -655,5 +655,35 @@ public IEnumerator Check_Validate_Graph_With_Sample_Gradient() yield return null; } + +#if VFX_TESTS_HAS_URP + [UnityTest] + public IEnumerator Check_Classic_Output_Has_Universal_Pipeline_Tag() + { + // This assembly doesn't reference the URP runtime, so match the asset type or any base type by name. + var isUniversalPipeline = false; + for (var type = UnityEngine.Rendering.GraphicsSettings.currentRenderPipelineAssetType; type != null && !isUniversalPipeline; type = type.BaseType) + isUniversalPipeline = type.Name == "UniversalRenderPipelineAsset"; + if (!isUniversalPipeline) + Assert.Ignore("Requires URP as the active render pipeline"); + + var vfxGraph = VFXTestCommon.CreateGraph_And_System(); + foreach (var yield in VFXTestCommon.CheckCompilation(vfxGraph)) + { + yield return yield; + } + + var path = AssetDatabase.GetAssetPath(vfxGraph); + var shaders = AssetDatabase.LoadAllAssetsAtPath(path).OfType().ToArray(); + Assert.AreNotEqual(0, shaders.Length); + var renderPipelineTag = new UnityEngine.Rendering.ShaderTagId("RenderPipeline"); + foreach (var shader in shaders) + { + Assert.AreNotEqual(0, shader.subshaderCount, shader.name); + for (int i = 0; i < shader.subshaderCount; ++i) + Assert.AreEqual("UniversalPipeline", shader.FindSubshaderTagValue(i, renderPipelineTag).name, $"{shader.name} SubShader {i}"); + } + } +#endif } } From 5f6f39fb9a318640d9ea18a5d157f4fbcffa6389 Mon Sep 17 00:00:00 2001 From: Louis-Philippe Ledoux Date: Tue, 10 Nov 2026 10:03:06 +0000 Subject: [PATCH 14/18] [Port][HDRP]Fix HDRP XR depth copy scale when RTHandle allocation exceeds viewport --- .../RenderPipeline/HDRenderPipeline.RenderGraph.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs index 263f9e130a9..652c4c973ce 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs @@ -377,7 +377,7 @@ void RecordRenderGraph(RenderRequest renderRequest, // Copy and rescale depth buffer for XR devices if (hdCamera.xr.enabled && hdCamera.xr.copyDepth && depthBackBuffer.IsValid()) - CopyDepth(m_RenderGraph, hdCamera, prepassOutput.resolvedDepthBuffer, depthBackBuffer, true); + CopyDepth(m_RenderGraph, prepassOutput.resolvedDepthBuffer, depthBackBuffer, true); if (m_CurrentDebugDisplaySettings.data.historyBuffersView != -1) { @@ -736,7 +736,7 @@ class CopyXRDepthPassData public int passIndex; } - void CopyDepth(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthBuffer, TextureHandle output, bool copyForXR) + void CopyDepth(RenderGraph renderGraph, TextureHandle depthBuffer, TextureHandle output, bool copyForXR) { string name = copyForXR ? "Copy XR Depth" : "Copy Depth"; var profileID = copyForXR ? HDProfileId.XRDepthCopy : HDProfileId.DuplicateDepthBuffer; @@ -747,8 +747,7 @@ void CopyDepth(RenderGraph renderGraph, HDCamera hdCamera, TextureHandle depthBu builder.UseTexture(passData.depthBuffer, AccessFlags.Read); passData.output = output; builder.SetRenderAttachmentDepth(output, AccessFlags.Write); - passData.blitScaleBias = copyForXR ? new Vector2(hdCamera.actualWidth / hdCamera.finalViewport.width, hdCamera.actualHeight / hdCamera.finalViewport.height) - : RTHandles.rtHandleProperties.rtHandleScale; + passData.blitScaleBias = RTHandles.rtHandleProperties.rtHandleScale; passData.flipY = copyForXR; passData.passIndex = renderGraph.GetTextureDesc(depthBuffer).msaaSamples != MSAASamples.None ? 1 : 0; Debug.Assert(!(copyForXR && passData.passIndex != 0), "MSAA depth copies do not support XR scaling and Y-flipping."); @@ -1736,7 +1735,7 @@ TransparentPrepassOutput RenderTransparentPrepass(RenderGraph renderGraph, Culli renderQueueRange: GetTransparentRenderQueueRange(hdCamera, false))); // Copy depth buffer for refraction - CopyDepth(renderGraph, hdCamera, prepassOutput.depthBuffer, output.depthBufferPreRefraction, false); + CopyDepth(renderGraph, prepassOutput.depthBuffer, output.depthBufferPreRefraction, false); if (hasWater) { From 1ff539fbe3a1219a3f41502351a2b9643266f5ba Mon Sep 17 00:00:00 2001 From: Arttu Peltonen Date: Tue, 10 Nov 2026 10:03:07 +0000 Subject: [PATCH 15/18] [Port] [6000.3] [UUM-160579] Keep prefab conversions when the converter opens closed scenes --- .../ReadonlyMaterialConverter/ReadonlyMaterialConverter.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/ReadonlyMaterialConverter/ReadonlyMaterialConverter.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/ReadonlyMaterialConverter/ReadonlyMaterialConverter.cs index a987f36bba5..66d77ce7e80 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/ReadonlyMaterialConverter/ReadonlyMaterialConverter.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/Converters/ReadonlyMaterialConverter/ReadonlyMaterialConverter.cs @@ -200,6 +200,9 @@ private Object LoadObject(ref RunItemContext ctx, StringBuilder sb) { var containerPath = AssetDatabase.GUIDToAssetPath(gid.assetGUID); + // Opening the scene unloads converted assets that are not saved, such as prefabs + AssetDatabase.SaveAssets(); + var mainInstanceID = AssetDatabase.LoadAssetAtPath(containerPath); AssetDatabase.OpenAsset(mainInstanceID); From 98ede3ce65a01d1c865b20d7ce44701a67cf88f3 Mon Sep 17 00:00:00 2001 From: Delia Hamwood Date: Wed, 11 Nov 2026 10:15:11 +0000 Subject: [PATCH 16/18] [Port] [6000.3] Graphics/URP - [UUM-155833] - Fix multi-display support in URP 2D/3D (second try, faster) --- .../Runtime/2D/PixelPerfectCamera.cs | 6 +++-- .../2D/Rendergraph/Renderer2DRendergraph.cs | 10 +++----- .../Runtime/FrameData/UniversalCameraData.cs | 6 +++++ .../Runtime/Passes/DrawScreenSpaceUIPass.cs | 8 +++--- .../Runtime/Passes/FinalBlitPass.cs | 6 ++--- .../Passes/PostProcessPassRenderGraph.cs | 4 +-- .../Runtime/RenderingUtils.cs | 25 +++++++++++++++++-- .../Runtime/UniversalRenderPipeline.cs | 5 ++++ .../Runtime/UniversalRendererRenderGraph.cs | 8 +++--- 9 files changed, 56 insertions(+), 22 deletions(-) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs index b9a42d6ac21..218498a91b3 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/PixelPerfectCamera.cs @@ -339,10 +339,12 @@ Vector2Int cameraRTSize get { var targetTexture = m_Camera.targetTexture; - return targetTexture == null ? new Vector2Int(Screen.width, Screen.height) : new Vector2Int(targetTexture.width, targetTexture.height); + return targetTexture == null ? screenRTSize : new Vector2Int(targetTexture.width, targetTexture.height); } } + Vector2Int screenRTSize => RenderingUtils.GetScreenBackbufferSize(m_Camera); + // Snap camera position to pixels using Camera.worldToCameraMatrix. void PixelSnap() { @@ -438,7 +440,7 @@ void OnGUI() } var targetTexture = m_Camera.targetTexture; - Vector2Int rtSize = targetTexture == null ? new Vector2Int(Screen.width, Screen.height) : new Vector2Int(targetTexture.width, targetTexture.height); + Vector2Int rtSize = targetTexture == null ? screenRTSize : new Vector2Int(targetTexture.width, targetTexture.height); if (rtSize.x < refResolutionX || rtSize.y < refResolutionY) { diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs index 096e93f5b6a..7f292de4e41 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Rendergraph/Renderer2DRendergraph.cs @@ -341,11 +341,8 @@ ImportResourceSummary GetImportResourceSummary(RenderGraph renderGraph, Universa // in some cases we disable multisampling for optimization purpose int numSamples = AdjustAndGetScreenMSAASamples(renderGraph, m_CreateColorTexture); - //NOTE: Careful what you use here as many of the properties bake-in the camera rect so for example - //cameraData.cameraTargetDescriptor.width is the width of the rectangle but not the actual render target - //same with cameraData.camera.pixelWidth - output.importInfo.width = Screen.width; - output.importInfo.height = Screen.height; + output.importInfo.width = cameraData.backbufferWidth; + output.importInfo.height = cameraData.backbufferHeight; output.importInfo.volumeDepth = 1; output.importInfo.msaaSamples = numSamples; output.importInfo.format = cameraData.cameraTargetDescriptor.graphicsFormat; @@ -710,8 +707,9 @@ void CreateCameraDepthCopyTexture(RenderGraph renderGraph, RenderTextureDescript void CreateOffscreenUITexture(RenderGraph renderGraph, in RenderTextureDescriptor descriptor) { UniversalResourceData resourceData = frameData.Get(); + UniversalCameraData cameraData = frameData.Get(); TextureDesc textureDesc = new TextureDesc(descriptor); - DrawScreenSpaceUIPass.ConfigureOffscreenUITextureDesc(ref textureDesc); + DrawScreenSpaceUIPass.ConfigureOffscreenUITextureDesc(ref textureDesc, cameraData); RenderingUtils.ReAllocateHandleIfNeeded(ref s_OffscreenUIColorHandle, textureDesc, name: "_OverlayUITexture"); resourceData.overlayUITexture = renderGraph.ImportTexture(s_OffscreenUIColorHandle); } diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs index bf87e78b5ee..d314a563d9e 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs @@ -211,6 +211,10 @@ internal Matrix4x4 GetGPUProjectionMatrix(bool renderIntoTexture, int viewIndex /// Render texture settings used to create intermediate camera textures for rendering. /// public RenderTextureDescriptor cameraTargetDescriptor; + + internal int backbufferWidth; + internal int backbufferHeight; + internal Rect pixelRect; internal bool useScreenCoordOverride; internal Vector4 screenSizeOverride; @@ -673,6 +677,8 @@ public override void Reset() renderType = CameraRenderType.Base; targetTexture = null; cameraTargetDescriptor = default; + backbufferWidth = 0; + backbufferHeight = 0; pixelRect = default; useScreenCoordOverride = false; screenSizeOverride = default; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawScreenSpaceUIPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawScreenSpaceUIPass.cs index e89ac526896..e776a8acd2f 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawScreenSpaceUIPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawScreenSpaceUIPass.cs @@ -54,12 +54,12 @@ private static void ConfigureColorDescriptor(ref RenderTextureDescriptor descrip /// /// Get a descriptor for the required color texture for offscreen UI pass. /// - internal static void ConfigureOffscreenUITextureDesc(ref TextureDesc textureDesc) + internal static void ConfigureOffscreenUITextureDesc(ref TextureDesc textureDesc, UniversalCameraData cameraData) { textureDesc.format = GraphicsFormat.R8G8B8A8_SRGB; textureDesc.depthBufferBits = 0; - textureDesc.width = Screen.width; - textureDesc.height = Screen.height; + textureDesc.width = cameraData.backbufferWidth; + textureDesc.height = cameraData.backbufferHeight; } /// @@ -186,7 +186,7 @@ internal void RenderOffscreen(RenderGraph renderGraph, ContextContainer frameDat { UniversalCameraData cameraData = frameData.Get(); RenderTextureDescriptor depthDescriptor = cameraData.cameraTargetDescriptor; - ConfigureDepthDescriptor(ref depthDescriptor, depthStencilFormat, Screen.width, Screen.height); + ConfigureDepthDescriptor(ref depthDescriptor, depthStencilFormat, cameraData.backbufferWidth, cameraData.backbufferHeight); TextureHandle depthBuffer = UniversalRenderer.CreateRenderGraphTexture(renderGraph, depthDescriptor, "_OverlayUITexture_Depth", false); // Render uGUI and UIToolkit overlays diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs index 4fe9644658f..37f1d334ffe 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs @@ -234,11 +234,11 @@ private static void ExecutePass(RasterCommandBuffer cmd, PassData data, RTHandle if (cameraData.xr.enabled) isRenderToBackBufferTarget = new RenderTargetIdentifier(destination.nameID, 0, CubemapFace.Unknown, -1) == new RenderTargetIdentifier(cameraData.xr.renderTarget, 0, CubemapFace.Unknown, -1); #endif - var pixelRect = data.useFullScreenViewport ? new Rect(0f, 0f, Screen.width, Screen.height) : cameraData.pixelRect; + var pixelRect = data.useFullScreenViewport ? new Rect(0f, 0f, cameraData.backbufferWidth, cameraData.backbufferHeight) : cameraData.pixelRect; #if URP_COMPATIBILITY_MODE - RenderingUtils.SetupOffscreenUIViewportParams(data.blitMaterialData.material, ref pixelRect, GraphicsSettings.GetRenderPipelineSettings().enableRenderCompatibilityMode ? false : isRenderToBackBufferTarget); + RenderingUtils.SetupOffscreenUIViewportParams(cameraData, data.blitMaterialData.material, ref pixelRect, GraphicsSettings.GetRenderPipelineSettings().enableRenderCompatibilityMode ? false : isRenderToBackBufferTarget); #else - RenderingUtils.SetupOffscreenUIViewportParams(data.blitMaterialData.material, ref pixelRect, isRenderToBackBufferTarget); + RenderingUtils.SetupOffscreenUIViewportParams(cameraData, data.blitMaterialData.material, ref pixelRect, isRenderToBackBufferTarget); #endif if (isRenderToBackBufferTarget) cmd.SetViewport(pixelRect); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPassRenderGraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPassRenderGraph.cs index 6921171c057..9928f772caf 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPassRenderGraph.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPassRenderGraph.cs @@ -2349,7 +2349,7 @@ public void RenderFinalPassRenderGraph(RenderGraph renderGraph, ContextContainer settings.hdrOperations |= HDROutputUtils.Operation.ColorConversion; SetupHDROutput(cameraData.hdrDisplayInformation, cameraData.hdrDisplayColorGamut, material, settings.hdrOperations, cameraData.rendersOverlayUI); - RenderingUtils.SetupOffscreenUIViewportParams(material, ref cameraData.pixelRect, cameraData.resolveFinalTarget); + RenderingUtils.SetupOffscreenUIViewportParams(cameraData, material, ref cameraData.pixelRect, cameraData.resolveFinalTarget); } DebugHandler debugHandler = ScriptableRenderPass.GetActiveDebugHandler(cameraData); bool resolveToDebugScreen = debugHandler != null && debugHandler.WriteToDebugScreenTexture(cameraData.resolveFinalTarget); @@ -2911,7 +2911,7 @@ public void RenderPostProcessingRenderGraph(RenderGraph renderGraph, ContextCont HDROutputUtils.Operation hdrOperations = !m_HasFinalPass && m_EnableColorEncodingIfNeeded ? HDROutputUtils.Operation.ColorEncoding : HDROutputUtils.Operation.None; SetupHDROutput(cameraData.hdrDisplayInformation, cameraData.hdrDisplayColorGamut, m_Materials.uber, hdrOperations, cameraData.rendersOverlayUI); - RenderingUtils.SetupOffscreenUIViewportParams(m_Materials.uber, ref cameraData.pixelRect, resourceData.isActiveTargetBackBuffer); + RenderingUtils.SetupOffscreenUIViewportParams(cameraData, m_Materials.uber, ref cameraData.pixelRect, resourceData.isActiveTargetBackBuffer); } bool enableAlphaOutput = cameraData.isAlphaOutputEnabled; diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs index 38920622892..04f2ecab7e9 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RenderingUtils.cs @@ -167,12 +167,33 @@ internal static void SetScaleBiasRt(RasterCommandBuffer cmd, in UniversalCameraD cmd.SetGlobalVector(Shader.PropertyToID("_ScaleBiasRt"), scaleBiasRt); } - internal static void SetupOffscreenUIViewportParams(Material material, ref Rect pixelRect, bool isRenderToBackBufferTarget) + // Returns the size of the backbuffer the camera renders to, in pixels. + internal static Vector2Int GetScreenBackbufferSize(Camera camera) + { + // Screen.width/height only ever describe the main display, so cameras targeting a secondary + // display need to query that display instead. + // + // UUM-149562: on QNX and Embedded Linux the graphics backend still reports the main display's + // resolution for the backbuffer of a secondary display. Returning the secondary display's real + // resolution here would no longer match what the backend reports, the render pass would fail + // validation and the secondary display would stop rendering altogether. Falling back to the main + // display size keeps those platforms rendering as usual. Remove the platform exclusions + // above once the backend reports per-display backbuffer dimensions. +#if ENABLE_MULTIPLE_DISPLAYS && !UNITY_QNX && !UNITY_EMBEDDED_LINUX + int targetDisplay = camera.targetDisplay; + var displays = Display.displays; + if (targetDisplay > 0 && targetDisplay < displays.Length) + return new Vector2Int(displays[targetDisplay].renderingWidth, displays[targetDisplay].renderingHeight); +#endif + return new Vector2Int(Screen.width, Screen.height); + } + + internal static void SetupOffscreenUIViewportParams(UniversalCameraData cameraData, Material material, ref Rect pixelRect, bool isRenderToBackBufferTarget) { Vector4 offscreenUIViewportParams = new Vector4(0f, 0f, 1f, 1f); if (isRenderToBackBufferTarget) { - var rcpScreenSize = new Vector2(1f / Screen.width, 1f / Screen.height); + var rcpScreenSize = new Vector2(1f / cameraData.backbufferWidth, 1f / cameraData.backbufferHeight); offscreenUIViewportParams = new Vector4(pixelRect.x * rcpScreenSize.x, pixelRect.y * rcpScreenSize.y, pixelRect.width * rcpScreenSize.x, pixelRect.height * rcpScreenSize.y); } material.SetVector(ShaderPropertyId.offscreenUIViewportParams, offscreenUIViewportParams); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs index a6e3d3f9005..007936f2301 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRenderPipeline.cs @@ -1423,6 +1423,11 @@ static UniversalCameraData CreateCameraData(ContextContainer frameData, Camera c bool needsAlphaChannel = Graphics.preserveFramebufferAlpha; cameraData.hdrColorBufferPrecision = asset ? asset.hdrColorBufferPrecision : HDRColorBufferPrecision._32Bits; + + Vector2Int backbufferSize = RenderingUtils.GetScreenBackbufferSize(camera); + cameraData.backbufferWidth = backbufferSize.x; + cameraData.backbufferHeight = backbufferSize.y; + cameraData.cameraTargetDescriptor = CreateRenderTextureDescriptor(camera, cameraData, cameraData.isHdrEnabled, cameraData.hdrColorBufferPrecision, msaaSamples, needsAlphaChannel, cameraData.requiresOpaqueTexture); diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs index 09a640f9e5e..3c315ab44d7 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs @@ -1765,8 +1765,8 @@ void ImportBackBuffers(RenderGraph renderGraph, UniversalCameraData cameraData, //NOTE: Careful what you use here as many of the properties bake-in the camera rect so for example //cameraData.cameraTargetDescriptor.width is the width of the rectangle but not the actual render target //same with cameraData.camera.pixelWidth - importInfo.width = Screen.width; - importInfo.height = Screen.height; + importInfo.width = cameraData.backbufferWidth; + importInfo.height = cameraData.backbufferHeight; importInfo.volumeDepth = 1; importInfo.msaaSamples = numSamples; importInfo.format = cameraData.cameraTargetDescriptor.graphicsFormat; @@ -2010,8 +2010,10 @@ void CreateAfterPostProcessTexture(RenderGraph renderGraph, RenderTextureDescrip void CreateOffscreenUITexture(RenderGraph renderGraph, TextureDesc descriptor) { UniversalResourceData resourceData = frameData.Get(); - DrawScreenSpaceUIPass.ConfigureOffscreenUITextureDesc(ref descriptor); + UniversalCameraData cameraData = frameData.Get(); + DrawScreenSpaceUIPass.ConfigureOffscreenUITextureDesc(ref descriptor, cameraData); RenderingUtils.ReAllocateHandleIfNeeded(ref m_OffscreenUIColorHandle, descriptor, name: "_OverlayUITexture"); + // Clear the texture to avoid stale data from previous frames ImportResourceParams importParams = new ImportResourceParams(); importParams.clearOnFirstUse = true; From 4061e3d5bb5adb75f5ef360a78654731fe35618e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Toru=20Nayuki=20=EF=BC=88=E5=90=8D=E9=9B=AA=20=E9=80=9A=20?= =?UTF-8?q?-=20=E3=81=AA=E3=82=86=E3=81=8D=20=E3=81=A8=E3=81=8A=E3=82=8B?= =?UTF-8?q?=EF=BC=89?= Date: Wed, 11 Nov 2026 10:15:11 +0000 Subject: [PATCH 17/18] [Port] [6000.3] [UUM-158409] [URP 2D] Fix Shadow Caster 2D not following Sprite Skin flip --- .../ShadowShape2DProvider_SpriteSkin.cs | 15 ++- .../Tests/Runtime/ShadowCaster2DTests.cs | 108 ++++++++++++++++++ 2 files changed, 118 insertions(+), 5 deletions(-) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/Providers/ShadowShape2DProvider_SpriteSkin.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/Providers/ShadowShape2DProvider_SpriteSkin.cs index ed2d298e8af..16c05aab804 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/Providers/ShadowShape2DProvider_SpriteSkin.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Shadows/ShadowProvider/Providers/ShadowShape2DProvider_SpriteSkin.cs @@ -55,12 +55,17 @@ public override void OnPersistantDataCreated(Component sourceComponent, ShadowSh public override void OnBeforeRender(Component sourceComponent, Bounds worldCullingBounds, ShadowShape2D persistantShadowShape) { SpriteSkin spriteSkin = (SpriteSkin)sourceComponent; - if (spriteSkin != null && spriteSkin.vertexDeformationHash != m_LastDeformedVertexHash) - { - SpriteRenderer spriteRenderer; - spriteSkin.TryGetComponent(out spriteRenderer); - persistantShadowShape.SetFlip(spriteRenderer.flipX, spriteRenderer.flipY); + if (spriteSkin == null) + return; + // Flipping does not deform the vertices, so it does not change vertexDeformationHash and has to be + // picked up every frame. A SpriteSkin whose bones do not move is not deformed again. + SpriteRenderer spriteRenderer; + spriteSkin.TryGetComponent(out spriteRenderer); + persistantShadowShape.SetFlip(spriteRenderer.flipX, spriteRenderer.flipY); + + if (spriteSkin.vertexDeformationHash != m_LastDeformedVertexHash) + { TryToSetPersistantShapeData(spriteSkin, persistantShadowShape, false); m_LastDeformedVertexHash = spriteSkin.vertexDeformationHash; } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowCaster2DTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowCaster2DTests.cs index da84421001e..b2bf9888a5f 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowCaster2DTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/ShadowCaster2DTests.cs @@ -1,5 +1,9 @@ #if U2D_ANIMATION_INSTALLED +using System.Collections; using NUnit.Framework; +using Unity.Collections; +using UnityEngine.TestTools; +using UnityEngine.U2D; using UnityEngine.U2D.Animation; namespace UnityEngine.Rendering.Universal.Tests @@ -7,6 +11,8 @@ namespace UnityEngine.Rendering.Universal.Tests class ShadowCaster2DTests { GameObject m_Obj; + Texture2D m_Texture; + Sprite m_Sprite; [SetUp] public void Setup() @@ -19,6 +25,10 @@ public void Setup() public void Cleanup() { Object.DestroyImmediate(m_Obj); + if (m_Sprite != null) + Object.DestroyImmediate(m_Sprite); + if (m_Texture != null) + Object.DestroyImmediate(m_Texture); } [Test] @@ -51,6 +61,104 @@ public void AddShadowCaster2DWithSpriteSkinWhenInactive() Assert.That(shadowCaster2D.shadowShape2DProvider, Is.Null); #endif } + +// ShadowCaster2D.shadowShape2DProvider is always null on Standalone. +#if UNITY_EDITOR + // A quad skinned to a single bone, built at runtime so the test needs no asset. + Sprite CreateSkinnedQuadSprite() + { + m_Texture = new Texture2D(4, 4); + m_Sprite = Sprite.Create(m_Texture, new Rect(0, 0, 4, 4), new Vector2(0.5f, 0.5f), 4, 0, SpriteMeshType.FullRect); + + m_Sprite.SetVertexCount(4); + using (var positions = new NativeArray(4, Allocator.Temp)) + using (var weights = new NativeArray(4, Allocator.Temp)) + using (var indices = new NativeArray(new ushort[] { 0, 1, 2, 2, 3, 0 }, Allocator.Temp)) + using (var bindPoses = new NativeArray(1, Allocator.Temp)) + { + var p = positions; + p[0] = new Vector3(-0.5f, -0.5f, 0); + p[1] = new Vector3(-0.5f, 0.5f, 0); + p[2] = new Vector3(0.5f, 0.5f, 0); + p[3] = new Vector3(0.5f, -0.5f, 0); + + var w = weights; + for (int i = 0; i < w.Length; ++i) + w[i] = new BoneWeight { boneIndex0 = 0, weight0 = 1 }; + + var b = bindPoses; + b[0] = Matrix4x4.identity; + + m_Sprite.SetVertexAttribute(VertexAttribute.Position, positions); + m_Sprite.SetVertexAttribute(VertexAttribute.BlendWeight, weights); + m_Sprite.SetIndices(indices); + m_Sprite.SetBindPoses(bindPoses); + } + + m_Sprite.SetBones(new[] + { + new SpriteBone { name = "root", position = Vector3.zero, rotation = Quaternion.identity, length = 1, parentId = -1 } + }); + + return m_Sprite; + } + + static void CallOnBeforeRender(ShadowCaster2D shadowCaster2D) + { + ShapeProviderUtility.CallOnBeforeRender(shadowCaster2D.shadowShape2DProvider, shadowCaster2D.shadowShape2DComponent, + shadowCaster2D.m_ShadowMesh, new Bounds(Vector3.zero, Vector3.one * 100)); + } + + // UUM-158409: a SpriteSkin whose bones do not move is not deformed again, so the shadow has to + // pick up the SpriteRenderer flip without waiting for a new deformation. + [UnityTest] + public IEnumerator ShadowCaster2DWithSpriteSkin_FollowsFlipWhenBonesAreStill([Values(false, true)] bool forceCpuDeformation) + { + SpriteRenderer spriteRenderer = m_Obj.GetComponent(); + spriteRenderer.sprite = CreateSkinnedQuadSprite(); + + var bone = new GameObject("root"); + bone.transform.SetParent(m_Obj.transform, false); + + SpriteSkin spriteSkin = m_Obj.AddComponent(); + spriteSkin.forceCpuDeformation = forceCpuDeformation; + spriteSkin.SetRootBone(bone.transform); + SpriteSkinState state = spriteSkin.SetBoneTransforms(new[] { bone.transform }); + Assert.That(state, Is.EqualTo(SpriteSkinState.Ready), "Test setup: the SpriteSkin must be valid for deformation."); + + ShadowCaster2D shadowCaster2D = m_Obj.AddComponent(); + Assert.That(shadowCaster2D.shadowShape2DProvider, Is.TypeOf(typeof(ShadowShape2DProvider_SpriteSkin))); + + // Let the first deformation land and the bones settle, so later frames do not deform again. + for (int i = 0; i < 5; ++i) + { + yield return null; + CallOnBeforeRender(shadowCaster2D); + } + Assert.That(spriteSkin.HasCurrentDeformedVertices(), Is.True, "Test setup: the SpriteSkin must have been deformed."); + + shadowCaster2D.m_ShadowMesh.GetFlip(out bool flipX, out bool flipY); + Assert.That(flipX, Is.False); + Assert.That(flipY, Is.False); + + spriteRenderer.flipX = true; + yield return null; + CallOnBeforeRender(shadowCaster2D); + + shadowCaster2D.m_ShadowMesh.GetFlip(out flipX, out flipY); + Assert.That(flipX, Is.True, "The shadow did not follow SpriteRenderer.flipX."); + Assert.That(flipY, Is.False); + + spriteRenderer.flipX = false; + spriteRenderer.flipY = true; + yield return null; + CallOnBeforeRender(shadowCaster2D); + + shadowCaster2D.m_ShadowMesh.GetFlip(out flipX, out flipY); + Assert.That(flipX, Is.False, "The shadow did not follow SpriteRenderer.flipX."); + Assert.That(flipY, Is.True, "The shadow did not follow SpriteRenderer.flipY."); + } +#endif } } #endif From 2454057027e289374ac3b2ba66945751b0cfbbd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?GeunHee=20Park=20=EF=BC=88=EB=B0=95=EA=B7=BC=ED=9D=AC=20-?= =?UTF-8?q?=20=E6=9C=B4=E6=A0=B9=E5=B8=8C=EF=BC=89?= Date: Sat, 21 Nov 2026 03:58:05 +0000 Subject: [PATCH 18/18] [Port] [6000.3] [Core] Fix bad type on DebugOccluder shader causing warning at build --- .../RenderPipelineResources/GPUDriven/DebugOccluder.shader | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOccluder.shader b/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOccluder.shader index 24149a67fb8..f4ad6b52e37 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOccluder.shader +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOccluder.shader @@ -29,7 +29,7 @@ Shader "Hidden/Core/DebugOccluder" return output; } - float GetOutputColor(float occluderValue) + float4 GetOutputColor(float occluderValue) { float value = saturate((occluderValue - _ValidRange.x) * _ValidRange.y); return float4(value.xxx, 1);